builtin-commit: Refresh cache after adding files.
[git/git.git] / builtin-commit.c
CommitLineData
f5bbc322
KH
1/*
2 * Builtin "git commit"
3 *
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6 */
7
8#include "cache.h"
9#include "cache-tree.h"
10#include "builtin.h"
11#include "diff.h"
12#include "diffcore.h"
13#include "commit.h"
14#include "revision.h"
15#include "wt-status.h"
16#include "run-command.h"
17#include "refs.h"
18#include "log-tree.h"
19#include "strbuf.h"
20#include "utf8.h"
21#include "parse-options.h"
22
23static const char * const builtin_commit_usage[] = {
24 "git-commit [options] [--] <filepattern>...",
25 NULL
26};
27
28static unsigned char head_sha1[20], merge_head_sha1[20];
29static char *use_message_buffer;
30static const char commit_editmsg[] = "COMMIT_EDITMSG";
31static struct lock_file lock_file;
32
33static char *logfile, *force_author, *message, *template_file;
34static char *edit_message, *use_message;
35static int all, edit_flag, also, interactive, only, amend, signoff;
36static int quiet, verbose, untracked_files, no_verify;
37
38static int no_edit, initial_commit, in_merge;
39const char *only_include_assumed;
40
41static struct option builtin_commit_options[] = {
42 OPT__QUIET(&quiet),
43 OPT__VERBOSE(&verbose),
44 OPT_GROUP("Commit message options"),
45
46 OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
47 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
48 OPT_STRING('m', "message", &message, "MESSAGE", "specify commit message"),
49 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
50 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
51 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
52 OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
53 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
54
55 OPT_GROUP("Commit contents options"),
56 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
57 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
58 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
59 OPT_BOOLEAN('o', "only", &only, ""),
60 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
61 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
62 OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
63
64 OPT_END()
65};
66
67static char *prepare_index(const char **files, const char *prefix)
68{
69 int fd;
70 struct tree *tree;
71 struct lock_file *next_index_lock;
72
73 if (interactive) {
74 interactive_add();
75 return get_index_file();
76 }
77
78 fd = hold_locked_index(&lock_file, 1);
79 if (read_cache() < 0)
80 die("index file corrupt");
81
82 if (all || also) {
83 add_files_to_cache(verbose, also ? prefix : NULL, files);
d37d3203 84 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
85 if (write_cache(fd, active_cache, active_nr) || close(fd))
86 die("unable to write new_index file");
87 return lock_file.filename;
88 }
89
90 if (*files == NULL) {
91 /* Commit index as-is. */
92 rollback_lock_file(&lock_file);
93 return get_index_file();
94 }
95
96 /* update the user index file */
97 add_files_to_cache(verbose, prefix, files);
98 if (write_cache(fd, active_cache, active_nr) || close(fd))
99 die("unable to write new_index file");
100
101 if (!initial_commit) {
102 tree = parse_tree_indirect(head_sha1);
103 if (!tree)
104 die("failed to unpack HEAD tree object");
105 if (read_tree(tree, 0, NULL))
106 die("failed to read HEAD tree object");
107 }
108
109 /* Use a lock file to garbage collect the temporary index file. */
110 next_index_lock = xmalloc(sizeof(*next_index_lock));
111 fd = hold_lock_file_for_update(next_index_lock,
112 git_path("next-index-%d", getpid()), 1);
113 add_files_to_cache(verbose, prefix, files);
d37d3203 114 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
115 if (write_cache(fd, active_cache, active_nr) || close(fd))
116 die("unable to write new_index file");
117
118 return next_index_lock->filename;
119}
120
121static int run_status(FILE *fp, const char *index_file)
122{
123 struct wt_status s;
124
125 wt_status_prepare(&s);
126
127 if (amend) {
128 s.amend = 1;
129 s.reference = "HEAD^1";
130 }
131 s.verbose = verbose;
132 s.untracked = untracked_files;
133 s.index_file = index_file;
134 s.fp = fp;
135
136 wt_status_print(&s);
137
138 return s.commitable;
139}
140
141static const char sign_off_header[] = "Signed-off-by: ";
142
143static int prepare_log_message(const char *index_file)
144{
145 struct stat statbuf;
146 int commitable;
147 struct strbuf sb;
148 char *buffer;
149 FILE *fp;
150
151 strbuf_init(&sb, 0);
152 if (message) {
153 strbuf_add(&sb, message, strlen(message));
154 } else if (logfile && !strcmp(logfile, "-")) {
155 if (isatty(0))
156 fprintf(stderr, "(reading log message from standard input)\n");
157 if (strbuf_read(&sb, 0, 0) < 0)
158 die("could not read log from standard input");
159 } else if (logfile) {
160 if (strbuf_read_file(&sb, logfile, 0) < 0)
161 die("could not read log file '%s': %s",
162 logfile, strerror(errno));
163 } else if (use_message) {
164 buffer = strstr(use_message_buffer, "\n\n");
165 if (!buffer || buffer[2] == '\0')
166 die("commit has empty message");
167 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
168 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
169 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
170 die("could not read MERGE_MSG: %s", strerror(errno));
171 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
172 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
173 die("could not read SQUASH_MSG: %s", strerror(errno));
174 } else if (template_file && !stat(template_file, &statbuf)) {
175 if (strbuf_read_file(&sb, template_file, 0) < 0)
176 die("could not read %s: %s",
177 template_file, strerror(errno));
178 }
179
180 fp = fopen(git_path(commit_editmsg), "w");
181 if (fp == NULL)
182 die("could not open %s\n", git_path(commit_editmsg));
183
184 stripspace(&sb, 0);
185 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
186 die("could not write commit template: %s\n",
187 strerror(errno));
188
189 if (signoff) {
190 const char *info, *bol;
191
192 info = git_committer_info(1);
193 strbuf_addch(&sb, '\0');
194 bol = strrchr(sb.buf + sb.len - 1, '\n');
195 if (!bol || prefixcmp(bol, sign_off_header))
196 fprintf(fp, "\n");
197 fprintf(fp, "%s%s\n", sign_off_header, git_committer_info(1));
198 }
199
200 strbuf_release(&sb);
201
202 if (in_merge && !no_edit)
203 fprintf(fp,
204 "#\n"
205 "# It looks like you may be committing a MERGE.\n"
206 "# If this is not correct, please remove the file\n"
207 "# %s\n"
208 "# and try again.\n"
209 "#\n",
210 git_path("MERGE_HEAD"));
211
212 fprintf(fp,
213 "\n"
214 "# Please enter the commit message for your changes.\n"
215 "# (Comment lines starting with '#' will not be included)\n");
216 if (only_include_assumed)
217 fprintf(fp, "# %s\n", only_include_assumed);
218
219 commitable = run_status(fp, index_file);
220
221 fclose(fp);
222
223 return commitable;
224}
225
226/*
227 * Find out if the message starting at position 'start' in the strbuf
228 * contains only whitespace and Signed-off-by lines.
229 */
230static int message_is_empty(struct strbuf *sb, int start)
231{
232 struct strbuf tmpl;
233 const char *nl;
234 int eol, i;
235
236 /* See if the template is just a prefix of the message. */
237 strbuf_init(&tmpl, 0);
238 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
239 stripspace(&tmpl, 1);
240 if (start + tmpl.len <= sb->len &&
241 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
242 start += tmpl.len;
243 }
244 strbuf_release(&tmpl);
245
246 /* Check if the rest is just whitespace and Signed-of-by's. */
247 for (i = start; i < sb->len; i++) {
248 nl = memchr(sb->buf + i, '\n', sb->len - i);
249 if (nl)
250 eol = nl - sb->buf;
251 else
252 eol = sb->len;
253
254 if (strlen(sign_off_header) <= eol - i &&
255 !prefixcmp(sb->buf + i, sign_off_header)) {
256 i = eol;
257 continue;
258 }
259 while (i < eol)
260 if (!isspace(sb->buf[i++]))
261 return 0;
262 }
263
264 return 1;
265}
266
267static void determine_author_info(struct strbuf *sb)
268{
269 char *name, *email, *date;
270
271 name = getenv("GIT_AUTHOR_NAME");
272 email = getenv("GIT_AUTHOR_EMAIL");
273 date = getenv("GIT_AUTHOR_DATE");
274
275 if (use_message) {
276 const char *a, *lb, *rb, *eol;
277
278 a = strstr(use_message_buffer, "\nauthor ");
279 if (!a)
280 die("invalid commit: %s\n", use_message);
281
282 lb = strstr(a + 8, " <");
283 rb = strstr(a + 8, "> ");
284 eol = strchr(a + 8, '\n');
285 if (!lb || !rb || !eol)
286 die("invalid commit: %s\n", use_message);
287
288 name = xstrndup(a + 8, lb - (a + 8));
289 email = xstrndup(lb + 2, rb - (lb + 2));
290 date = xstrndup(rb + 2, eol - (rb + 2));
291 }
292
293 if (force_author) {
294 const char *lb = strstr(force_author, " <");
295 const char *rb = strchr(force_author, '>');
296
297 if (!lb || !rb)
298 die("malformed --author parameter\n");
299 name = xstrndup(force_author, lb - force_author);
300 email = xstrndup(lb + 2, rb - (lb + 2));
301 }
302
303 strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, 1));
304}
305
306static int parse_and_validate_options(int argc, const char *argv[])
307{
308 int f = 0;
309
310 argc = parse_options(argc, argv, builtin_commit_options,
311 builtin_commit_usage, 0);
312
313 if (logfile || message || use_message)
314 no_edit = 1;
315 if (edit_flag)
316 no_edit = 0;
317
318 if (get_sha1("HEAD", head_sha1))
319 initial_commit = 1;
320
321 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
322 in_merge = 1;
323
324 /* Sanity check options */
325 if (amend && initial_commit)
326 die("You have nothing to amend.");
327 if (amend && in_merge)
328 die("You are in the middle of a merger -- cannot amend.");
329
330 if (use_message)
331 f++;
332 if (edit_message)
333 f++;
334 if (logfile)
335 f++;
336 if (f > 1)
337 die("Only one of -c/-C/-F can be used.");
338 if (message && f > 0)
339 die("Option -m cannot be combined with -c/-C/-F.");
340 if (edit_message)
341 use_message = edit_message;
342 if (amend)
343 use_message = "HEAD";
344 if (use_message) {
345 unsigned char sha1[20];
346 static char utf8[] = "UTF-8";
347 const char *out_enc;
348 char *enc, *end;
349 struct commit *commit;
350
351 if (get_sha1(use_message, sha1))
352 die("could not lookup commit %s", use_message);
353 commit = lookup_commit(sha1);
354 if (!commit || parse_commit(commit))
355 die("could not parse commit %s", use_message);
356
357 enc = strstr(commit->buffer, "\nencoding");
358 if (enc) {
359 end = strchr(enc + 10, '\n');
360 enc = xstrndup(enc + 10, end - (enc + 10));
361 } else {
362 enc = utf8;
363 }
364 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
365
366 if (strcmp(out_enc, enc))
367 use_message_buffer =
368 reencode_string(commit->buffer, out_enc, enc);
369
370 /*
371 * If we failed to reencode the buffer, just copy it
372 * byte for byte so the user can try to fix it up.
373 * This also handles the case where input and output
374 * encodings are identical.
375 */
376 if (use_message_buffer == NULL)
377 use_message_buffer = xstrdup(commit->buffer);
378 if (enc != utf8)
379 free(enc);
380 }
381
382 if (!!also + !!only + !!all + !!interactive > 1)
383 die("Only one of --include/--only/--all/--interactive can be used.");
384 if (argc == 0 && (also || (only && !amend)))
385 die("No paths with --include/--only does not make sense.");
386 if (argc == 0 && only && amend)
387 only_include_assumed = "Clever... amending the last one with dirty index.";
388 if (argc > 0 && !also && !only) {
389 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
390 also = 0;
391 }
392
393 if (all && argc > 0)
394 die("Paths with -a does not make sense.");
395 else if (interactive && argc > 0)
396 die("Paths with --interactive does not make sense.");
397
398 return argc;
399}
400
401int cmd_status(int argc, const char **argv, const char *prefix)
402{
403 const char *index_file;
404 int commitable;
405
406 git_config(git_status_config);
407
408 argc = parse_and_validate_options(argc, argv);
409
410 index_file = prepare_index(argv, prefix);
411
412 commitable = run_status(stdout, index_file);
413
414 rollback_lock_file(&lock_file);
415
416 return commitable ? 0 : 1;
417}
418
419static int run_hook(const char *index_file, const char *name, const char *arg)
420{
421 struct child_process hook;
422 const char *argv[3], *env[2];
423 char index[PATH_MAX];
424
425 argv[0] = git_path("hooks/%s", name);
426 argv[1] = arg;
427 argv[2] = NULL;
428 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
429 env[0] = index;
430 env[1] = NULL;
431
432 if (access(argv[0], X_OK) < 0)
433 return 0;
434
435 memset(&hook, 0, sizeof(hook));
436 hook.argv = argv;
437 hook.no_stdin = 1;
438 hook.stdout_to_stderr = 1;
439 hook.env = env;
440
441 return run_command(&hook);
442}
443
444static void print_summary(const char *prefix, const unsigned char *sha1)
445{
446 struct rev_info rev;
447 struct commit *commit;
448
449 commit = lookup_commit(sha1);
450 if (!commit)
451 die("couldn't look up newly created commit\n");
452 if (!commit || parse_commit(commit))
453 die("could not parse newly created commit");
454
455 init_revisions(&rev, prefix);
456 setup_revisions(0, NULL, &rev, NULL);
457
458 rev.abbrev = 0;
459 rev.diff = 1;
460 rev.diffopt.output_format =
461 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
462
463 rev.verbose_header = 1;
464 rev.show_root_diff = 1;
465 rev.commit_format = get_commit_format("format:%h: %s");
466 rev.always_show_header = 1;
467
468 printf("Created %scommit ", initial_commit ? "initial " : "");
469
470 log_tree_commit(&rev, commit);
471}
472
473int git_commit_config(const char *k, const char *v)
474{
475 if (!strcmp(k, "commit.template")) {
476 template_file = xstrdup(v);
477 return 0;
478 }
479
480 return git_status_config(k, v);
481}
482
483static const char commit_utf8_warn[] =
484"Warning: commit message does not conform to UTF-8.\n"
485"You may want to amend it after fixing the message, or set the config\n"
486"variable i18n.commitencoding to the encoding your project uses.\n";
487
488int cmd_commit(int argc, const char **argv, const char *prefix)
489{
490 int header_len, parent_count = 0;
491 struct strbuf sb;
492 const char *index_file, *reflog_msg;
741707b1 493 char *nl;
f5bbc322
KH
494 unsigned char commit_sha1[20];
495 struct ref_lock *ref_lock;
496
497 git_config(git_commit_config);
498
499 argc = parse_and_validate_options(argc, argv);
500
501 index_file = prepare_index(argv, prefix);
502
503 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
504 exit(1);
505
506 if (!prepare_log_message(index_file) && !in_merge) {
507 run_status(stdout, index_file);
508 unlink(commit_editmsg);
509 return 1;
510 }
511
512 strbuf_init(&sb, 0);
513
514 /* Start building up the commit header */
515 read_cache_from(index_file);
516 active_cache_tree = cache_tree();
517 if (cache_tree_update(active_cache_tree,
518 active_cache, active_nr, 0, 0) < 0)
519 die("Error building trees");
520 strbuf_addf(&sb, "tree %s\n",
521 sha1_to_hex(active_cache_tree->sha1));
522
523 /* Determine parents */
524 if (initial_commit) {
525 reflog_msg = "commit (initial)";
526 parent_count = 0;
527 } else if (amend) {
528 struct commit_list *c;
529 struct commit *commit;
530
531 reflog_msg = "commit (amend)";
532 commit = lookup_commit(head_sha1);
533 if (!commit || parse_commit(commit))
534 die("could not parse HEAD commit");
535
536 for (c = commit->parents; c; c = c->next)
537 strbuf_addf(&sb, "parent %s\n",
538 sha1_to_hex(c->item->object.sha1));
539 } else if (in_merge) {
540 struct strbuf m;
541 FILE *fp;
542
543 reflog_msg = "commit (merge)";
544 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
545 strbuf_init(&m, 0);
546 fp = fopen(git_path("MERGE_HEAD"), "r");
547 if (fp == NULL)
548 die("could not open %s for reading: %s",
549 git_path("MERGE_HEAD"), strerror(errno));
550 while (strbuf_getline(&m, fp, '\n') != EOF)
551 strbuf_addf(&sb, "parent %s\n", m.buf);
552 fclose(fp);
553 strbuf_release(&m);
554 } else {
555 reflog_msg = "commit";
556 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
557 }
558
559 determine_author_info(&sb);
560 strbuf_addf(&sb, "committer %s\n", git_committer_info(1));
561 if (!is_encoding_utf8(git_commit_encoding))
562 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
563 strbuf_addch(&sb, '\n');
564
565 /* Get the commit message and validate it */
566 header_len = sb.len;
567 if (!no_edit) {
568 fprintf(stderr, "launching editor, log %s\n", logfile);
569 launch_editor(git_path(commit_editmsg), &sb);
570 } else if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0)
571 die("could not read commit message\n");
572 if (run_hook(index_file, "commit-msg", commit_editmsg))
573 exit(1);
574 stripspace(&sb, 1);
575 if (sb.len < header_len ||
576 message_is_empty(&sb, header_len))
577 die("* no commit message? aborting commit.");
578 strbuf_addch(&sb, '\0');
579 if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
580 fprintf(stderr, commit_utf8_warn);
581
582 if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1))
583 die("failed to write commit object");
584
585 ref_lock = lock_any_ref_for_update("HEAD",
586 initial_commit ? NULL : head_sha1,
587 0);
588
589 nl = strchr(sb.buf + header_len, '\n');
741707b1
JS
590 if (nl)
591 strbuf_setlen(&sb, nl + 1 - sb.buf);
592 else
593 strbuf_addch(&sb, '\n');
594 strbuf_remove(&sb, 0, header_len);
595 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
596 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
f5bbc322
KH
597
598 if (!ref_lock)
599 die("cannot lock HEAD ref");
600 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0)
601 die("cannot update HEAD ref");
602
603 unlink(git_path("MERGE_HEAD"));
604 unlink(git_path("MERGE_MSG"));
605
606 if (lock_file.filename[0] && commit_locked_index(&lock_file))
607 die("failed to write new index");
608
609 rerere();
610
611 run_hook(index_file, "post-commit", NULL);
612
613 if (!quiet)
614 print_summary(prefix, commit_sha1);
615
616 return 0;
617}