Merge branch 'tc/http-urls-ends-with-slash'
[git] / builtin / commit.c
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 "color.h"
11 #include "dir.h"
12 #include "builtin.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "commit.h"
16 #include "revision.h"
17 #include "wt-status.h"
18 #include "run-command.h"
19 #include "refs.h"
20 #include "log-tree.h"
21 #include "strbuf.h"
22 #include "utf8.h"
23 #include "parse-options.h"
24 #include "string-list.h"
25 #include "rerere.h"
26 #include "unpack-trees.h"
27 #include "quote.h"
28 #include "submodule.h"
29
30 static const char * const builtin_commit_usage[] = {
31         "git commit [options] [--] <filepattern>...",
32         NULL
33 };
34
35 static const char * const builtin_status_usage[] = {
36         "git status [options] [--] <filepattern>...",
37         NULL
38 };
39
40 static const char implicit_ident_advice[] =
41 "Your name and email address were configured automatically based\n"
42 "on your username and hostname. Please check that they are accurate.\n"
43 "You can suppress this message by setting them explicitly:\n"
44 "\n"
45 "    git config --global user.name \"Your Name\"\n"
46 "    git config --global user.email you@example.com\n"
47 "\n"
48 "If the identity used for this commit is wrong, you can fix it with:\n"
49 "\n"
50 "    git commit --amend --author='Your Name <you@example.com>'\n";
51
52 static const char empty_amend_advice[] =
53 "You asked to amend the most recent commit, but doing so would make\n"
54 "it empty. You can repeat your command with --allow-empty, or you can\n"
55 "remove the commit entirely with \"git reset HEAD^\".\n";
56
57 static unsigned char head_sha1[20];
58
59 static char *use_message_buffer;
60 static const char commit_editmsg[] = "COMMIT_EDITMSG";
61 static struct lock_file index_lock; /* real index */
62 static struct lock_file false_lock; /* used only for partial commits */
63 static enum {
64         COMMIT_AS_IS = 1,
65         COMMIT_NORMAL,
66         COMMIT_PARTIAL
67 } commit_style;
68
69 static const char *logfile, *force_author;
70 static const char *template_file;
71 static char *edit_message, *use_message;
72 static char *fixup_message, *squash_message;
73 static char *author_name, *author_email, *author_date;
74 static int all, edit_flag, also, interactive, only, amend, signoff;
75 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
76 static int no_post_rewrite, allow_empty_message;
77 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
78 /*
79  * The default commit message cleanup mode will remove the lines
80  * beginning with # (shell comments) and leading and trailing
81  * whitespaces (empty lines or containing only whitespaces)
82  * if editor is used, and only the whitespaces if the message
83  * is specified explicitly.
84  */
85 static enum {
86         CLEANUP_SPACE,
87         CLEANUP_NONE,
88         CLEANUP_ALL
89 } cleanup_mode;
90 static char *cleanup_arg;
91
92 static int use_editor = 1, initial_commit, in_merge, include_status = 1;
93 static int show_ignored_in_status;
94 static const char *only_include_assumed;
95 static struct strbuf message;
96
97 static int null_termination;
98 static enum {
99         STATUS_FORMAT_LONG,
100         STATUS_FORMAT_SHORT,
101         STATUS_FORMAT_PORCELAIN
102 } status_format = STATUS_FORMAT_LONG;
103 static int status_show_branch;
104
105 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
106 {
107         struct strbuf *buf = opt->value;
108         if (unset)
109                 strbuf_setlen(buf, 0);
110         else {
111                 strbuf_addstr(buf, arg);
112                 strbuf_addstr(buf, "\n\n");
113         }
114         return 0;
115 }
116
117 static struct option builtin_commit_options[] = {
118         OPT__QUIET(&quiet, "suppress summary after successful commit"),
119         OPT__VERBOSE(&verbose, "show diff in commit message template"),
120
121         OPT_GROUP("Commit message options"),
122         OPT_FILENAME('F', "file", &logfile, "read log from file"),
123         OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
124         OPT_STRING(0, "date", &force_date, "DATE", "override date for commit"),
125         OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
126         OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
127         OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
128         OPT_STRING(0, "fixup", &fixup_message, "COMMIT", "use autosquash formatted message to fixup specified commit"),
129         OPT_STRING(0, "squash", &squash_message, "COMMIT", "use autosquash formatted message to squash specified commit"),
130         OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
131         OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
132         OPT_FILENAME('t', "template", &template_file, "use specified template file"),
133         OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
134         OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
135         OPT_BOOLEAN(0, "status", &include_status, "include status in commit message template"),
136         /* end commit message options */
137
138         OPT_GROUP("Commit contents options"),
139         OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
140         OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
141         OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
142         OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
143         OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
144         OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
145         OPT_SET_INT(0, "short", &status_format, "show status concisely",
146                     STATUS_FORMAT_SHORT),
147         OPT_BOOLEAN(0, "branch", &status_show_branch, "show branch information"),
148         OPT_SET_INT(0, "porcelain", &status_format,
149                     "show porcelain output format", STATUS_FORMAT_PORCELAIN),
150         OPT_BOOLEAN('z', "null", &null_termination,
151                     "terminate entries with NUL"),
152         OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
153         OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, "bypass post-rewrite hook"),
154         { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, "mode", "show untracked files, optional modes: all, normal, no (Default: all)", PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
155         /* end commit contents options */
156
157         { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
158           "ok to record an empty change",
159           PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
160         { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
161           "ok to record a change with an empty message",
162           PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
163
164         OPT_END()
165 };
166
167 static void rollback_index_files(void)
168 {
169         switch (commit_style) {
170         case COMMIT_AS_IS:
171                 break; /* nothing to do */
172         case COMMIT_NORMAL:
173                 rollback_lock_file(&index_lock);
174                 break;
175         case COMMIT_PARTIAL:
176                 rollback_lock_file(&index_lock);
177                 rollback_lock_file(&false_lock);
178                 break;
179         }
180 }
181
182 static int commit_index_files(void)
183 {
184         int err = 0;
185
186         switch (commit_style) {
187         case COMMIT_AS_IS:
188                 break; /* nothing to do */
189         case COMMIT_NORMAL:
190                 err = commit_lock_file(&index_lock);
191                 break;
192         case COMMIT_PARTIAL:
193                 err = commit_lock_file(&index_lock);
194                 rollback_lock_file(&false_lock);
195                 break;
196         }
197
198         return err;
199 }
200
201 /*
202  * Take a union of paths in the index and the named tree (typically, "HEAD"),
203  * and return the paths that match the given pattern in list.
204  */
205 static int list_paths(struct string_list *list, const char *with_tree,
206                       const char *prefix, const char **pattern)
207 {
208         int i;
209         char *m;
210
211         for (i = 0; pattern[i]; i++)
212                 ;
213         m = xcalloc(1, i);
214
215         if (with_tree)
216                 overlay_tree_on_cache(with_tree, prefix);
217
218         for (i = 0; i < active_nr; i++) {
219                 struct cache_entry *ce = active_cache[i];
220                 struct string_list_item *item;
221
222                 if (ce->ce_flags & CE_UPDATE)
223                         continue;
224                 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
225                         continue;
226                 item = string_list_insert(list, ce->name);
227                 if (ce_skip_worktree(ce))
228                         item->util = item; /* better a valid pointer than a fake one */
229         }
230
231         return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
232 }
233
234 static void add_remove_files(struct string_list *list)
235 {
236         int i;
237         for (i = 0; i < list->nr; i++) {
238                 struct stat st;
239                 struct string_list_item *p = &(list->items[i]);
240
241                 /* p->util is skip-worktree */
242                 if (p->util)
243                         continue;
244
245                 if (!lstat(p->string, &st)) {
246                         if (add_to_cache(p->string, &st, 0))
247                                 die("updating files failed");
248                 } else
249                         remove_file_from_cache(p->string);
250         }
251 }
252
253 static void create_base_index(void)
254 {
255         struct tree *tree;
256         struct unpack_trees_options opts;
257         struct tree_desc t;
258
259         if (initial_commit) {
260                 discard_cache();
261                 return;
262         }
263
264         memset(&opts, 0, sizeof(opts));
265         opts.head_idx = 1;
266         opts.index_only = 1;
267         opts.merge = 1;
268         opts.src_index = &the_index;
269         opts.dst_index = &the_index;
270
271         opts.fn = oneway_merge;
272         tree = parse_tree_indirect(head_sha1);
273         if (!tree)
274                 die("failed to unpack HEAD tree object");
275         parse_tree(tree);
276         init_tree_desc(&t, tree->buffer, tree->size);
277         if (unpack_trees(1, &t, &opts))
278                 exit(128); /* We've already reported the error, finish dying */
279 }
280
281 static void refresh_cache_or_die(int refresh_flags)
282 {
283         /*
284          * refresh_flags contains REFRESH_QUIET, so the only errors
285          * are for unmerged entries.
286          */
287         if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
288                 die_resolve_conflict("commit");
289 }
290
291 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
292 {
293         int fd;
294         struct string_list partial;
295         const char **pathspec = NULL;
296         int refresh_flags = REFRESH_QUIET;
297
298         if (is_status)
299                 refresh_flags |= REFRESH_UNMERGED;
300         if (interactive) {
301                 if (interactive_add(argc, argv, prefix) != 0)
302                         die("interactive add failed");
303                 if (read_cache_preload(NULL) < 0)
304                         die("index file corrupt");
305                 commit_style = COMMIT_AS_IS;
306                 return get_index_file();
307         }
308
309         if (*argv)
310                 pathspec = get_pathspec(prefix, argv);
311
312         if (read_cache_preload(pathspec) < 0)
313                 die("index file corrupt");
314
315         /*
316          * Non partial, non as-is commit.
317          *
318          * (1) get the real index;
319          * (2) update the_index as necessary;
320          * (3) write the_index out to the real index (still locked);
321          * (4) return the name of the locked index file.
322          *
323          * The caller should run hooks on the locked real index, and
324          * (A) if all goes well, commit the real index;
325          * (B) on failure, rollback the real index.
326          */
327         if (all || (also && pathspec && *pathspec)) {
328                 fd = hold_locked_index(&index_lock, 1);
329                 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
330                 refresh_cache_or_die(refresh_flags);
331                 if (write_cache(fd, active_cache, active_nr) ||
332                     close_lock_file(&index_lock))
333                         die("unable to write new_index file");
334                 commit_style = COMMIT_NORMAL;
335                 return index_lock.filename;
336         }
337
338         /*
339          * As-is commit.
340          *
341          * (1) return the name of the real index file.
342          *
343          * The caller should run hooks on the real index,
344          * and create commit from the_index.
345          * We still need to refresh the index here.
346          */
347         if (!pathspec || !*pathspec) {
348                 fd = hold_locked_index(&index_lock, 1);
349                 refresh_cache_or_die(refresh_flags);
350                 if (active_cache_changed) {
351                         if (write_cache(fd, active_cache, active_nr) ||
352                             commit_locked_index(&index_lock))
353                                 die("unable to write new_index file");
354                 } else {
355                         rollback_lock_file(&index_lock);
356                 }
357                 commit_style = COMMIT_AS_IS;
358                 return get_index_file();
359         }
360
361         /*
362          * A partial commit.
363          *
364          * (0) find the set of affected paths;
365          * (1) get lock on the real index file;
366          * (2) update the_index with the given paths;
367          * (3) write the_index out to the real index (still locked);
368          * (4) get lock on the false index file;
369          * (5) reset the_index from HEAD;
370          * (6) update the_index the same way as (2);
371          * (7) write the_index out to the false index file;
372          * (8) return the name of the false index file (still locked);
373          *
374          * The caller should run hooks on the locked false index, and
375          * create commit from it.  Then
376          * (A) if all goes well, commit the real index;
377          * (B) on failure, rollback the real index;
378          * In either case, rollback the false index.
379          */
380         commit_style = COMMIT_PARTIAL;
381
382         if (in_merge)
383                 die("cannot do a partial commit during a merge.");
384
385         memset(&partial, 0, sizeof(partial));
386         partial.strdup_strings = 1;
387         if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
388                 exit(1);
389
390         discard_cache();
391         if (read_cache() < 0)
392                 die("cannot read the index");
393
394         fd = hold_locked_index(&index_lock, 1);
395         add_remove_files(&partial);
396         refresh_cache(REFRESH_QUIET);
397         if (write_cache(fd, active_cache, active_nr) ||
398             close_lock_file(&index_lock))
399                 die("unable to write new_index file");
400
401         fd = hold_lock_file_for_update(&false_lock,
402                                        git_path("next-index-%"PRIuMAX,
403                                                 (uintmax_t) getpid()),
404                                        LOCK_DIE_ON_ERROR);
405
406         create_base_index();
407         add_remove_files(&partial);
408         refresh_cache(REFRESH_QUIET);
409
410         if (write_cache(fd, active_cache, active_nr) ||
411             close_lock_file(&false_lock))
412                 die("unable to write temporary index file");
413
414         discard_cache();
415         read_cache_from(false_lock.filename);
416
417         return false_lock.filename;
418 }
419
420 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
421                       struct wt_status *s)
422 {
423         unsigned char sha1[20];
424
425         if (s->relative_paths)
426                 s->prefix = prefix;
427
428         if (amend) {
429                 s->amend = 1;
430                 s->reference = "HEAD^1";
431         }
432         s->verbose = verbose;
433         s->index_file = index_file;
434         s->fp = fp;
435         s->nowarn = nowarn;
436         s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
437
438         wt_status_collect(s);
439
440         switch (status_format) {
441         case STATUS_FORMAT_SHORT:
442                 wt_shortstatus_print(s, null_termination, status_show_branch);
443                 break;
444         case STATUS_FORMAT_PORCELAIN:
445                 wt_porcelain_print(s, null_termination);
446                 break;
447         case STATUS_FORMAT_LONG:
448                 wt_status_print(s);
449                 break;
450         }
451
452         return s->commitable;
453 }
454
455 static int is_a_merge(const unsigned char *sha1)
456 {
457         struct commit *commit = lookup_commit(sha1);
458         if (!commit || parse_commit(commit))
459                 die("could not parse HEAD commit");
460         return !!(commit->parents && commit->parents->next);
461 }
462
463 static const char sign_off_header[] = "Signed-off-by: ";
464
465 static void determine_author_info(void)
466 {
467         char *name, *email, *date;
468
469         name = getenv("GIT_AUTHOR_NAME");
470         email = getenv("GIT_AUTHOR_EMAIL");
471         date = getenv("GIT_AUTHOR_DATE");
472
473         if (use_message && !renew_authorship) {
474                 const char *a, *lb, *rb, *eol;
475
476                 a = strstr(use_message_buffer, "\nauthor ");
477                 if (!a)
478                         die("invalid commit: %s", use_message);
479
480                 lb = strchrnul(a + strlen("\nauthor "), '<');
481                 rb = strchrnul(lb, '>');
482                 eol = strchrnul(rb, '\n');
483                 if (!*lb || !*rb || !*eol)
484                         die("invalid commit: %s", use_message);
485
486                 if (lb == a + strlen("\nauthor "))
487                         /* \nauthor <foo@example.com> */
488                         name = xcalloc(1, 1);
489                 else
490                         name = xmemdupz(a + strlen("\nauthor "),
491                                         (lb - strlen(" ") -
492                                          (a + strlen("\nauthor "))));
493                 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
494                 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
495         }
496
497         if (force_author) {
498                 const char *lb = strstr(force_author, " <");
499                 const char *rb = strchr(force_author, '>');
500
501                 if (!lb || !rb)
502                         die("malformed --author parameter");
503                 name = xstrndup(force_author, lb - force_author);
504                 email = xstrndup(lb + 2, rb - (lb + 2));
505         }
506
507         if (force_date)
508                 date = force_date;
509
510         author_name = name;
511         author_email = email;
512         author_date = date;
513 }
514
515 static int ends_rfc2822_footer(struct strbuf *sb)
516 {
517         int ch;
518         int hit = 0;
519         int i, j, k;
520         int len = sb->len;
521         int first = 1;
522         const char *buf = sb->buf;
523
524         for (i = len - 1; i > 0; i--) {
525                 if (hit && buf[i] == '\n')
526                         break;
527                 hit = (buf[i] == '\n');
528         }
529
530         while (i < len - 1 && buf[i] == '\n')
531                 i++;
532
533         for (; i < len; i = k) {
534                 for (k = i; k < len && buf[k] != '\n'; k++)
535                         ; /* do nothing */
536                 k++;
537
538                 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
539                         continue;
540
541                 first = 0;
542
543                 for (j = 0; i + j < len; j++) {
544                         ch = buf[i + j];
545                         if (ch == ':')
546                                 break;
547                         if (isalnum(ch) ||
548                             (ch == '-'))
549                                 continue;
550                         return 0;
551                 }
552         }
553         return 1;
554 }
555
556 static int prepare_to_commit(const char *index_file, const char *prefix,
557                              struct wt_status *s)
558 {
559         struct stat statbuf;
560         int commitable, saved_color_setting;
561         struct strbuf sb = STRBUF_INIT;
562         char *buffer;
563         FILE *fp;
564         const char *hook_arg1 = NULL;
565         const char *hook_arg2 = NULL;
566         int ident_shown = 0;
567
568         if (!no_verify && run_hook(index_file, "pre-commit", NULL))
569                 return 0;
570
571         if (squash_message) {
572                 /*
573                  * Insert the proper subject line before other commit
574                  * message options add their content.
575                  */
576                 if (use_message && !strcmp(use_message, squash_message))
577                         strbuf_addstr(&sb, "squash! ");
578                 else {
579                         struct pretty_print_context ctx = {0};
580                         struct commit *c;
581                         c = lookup_commit_reference_by_name(squash_message);
582                         if (!c)
583                                 die("could not lookup commit %s", squash_message);
584                         ctx.output_encoding = get_commit_output_encoding();
585                         format_commit_message(c, "squash! %s\n\n", &sb,
586                                               &ctx);
587                 }
588         }
589
590         if (message.len) {
591                 strbuf_addbuf(&sb, &message);
592                 hook_arg1 = "message";
593         } else if (logfile && !strcmp(logfile, "-")) {
594                 if (isatty(0))
595                         fprintf(stderr, "(reading log message from standard input)\n");
596                 if (strbuf_read(&sb, 0, 0) < 0)
597                         die_errno("could not read log from standard input");
598                 hook_arg1 = "message";
599         } else if (logfile) {
600                 if (strbuf_read_file(&sb, logfile, 0) < 0)
601                         die_errno("could not read log file '%s'",
602                                   logfile);
603                 hook_arg1 = "message";
604         } else if (use_message) {
605                 buffer = strstr(use_message_buffer, "\n\n");
606                 if (!buffer || buffer[2] == '\0')
607                         die("commit has empty message");
608                 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
609                 hook_arg1 = "commit";
610                 hook_arg2 = use_message;
611         } else if (fixup_message) {
612                 struct pretty_print_context ctx = {0};
613                 struct commit *commit;
614                 commit = lookup_commit_reference_by_name(fixup_message);
615                 if (!commit)
616                         die("could not lookup commit %s", fixup_message);
617                 ctx.output_encoding = get_commit_output_encoding();
618                 format_commit_message(commit, "fixup! %s\n\n",
619                                       &sb, &ctx);
620                 hook_arg1 = "message";
621         } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
622                 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
623                         die_errno("could not read MERGE_MSG");
624                 hook_arg1 = "merge";
625         } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
626                 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
627                         die_errno("could not read SQUASH_MSG");
628                 hook_arg1 = "squash";
629         } else if (template_file && !stat(template_file, &statbuf)) {
630                 if (strbuf_read_file(&sb, template_file, 0) < 0)
631                         die_errno("could not read '%s'", template_file);
632                 hook_arg1 = "template";
633         }
634
635         /*
636          * This final case does not modify the template message,
637          * it just sets the argument to the prepare-commit-msg hook.
638          */
639         else if (in_merge)
640                 hook_arg1 = "merge";
641
642         if (squash_message) {
643                 /*
644                  * If squash_commit was used for the commit subject,
645                  * then we're possibly hijacking other commit log options.
646                  * Reset the hook args to tell the real story.
647                  */
648                 hook_arg1 = "message";
649                 hook_arg2 = "";
650         }
651
652         fp = fopen(git_path(commit_editmsg), "w");
653         if (fp == NULL)
654                 die_errno("could not open '%s'", git_path(commit_editmsg));
655
656         if (cleanup_mode != CLEANUP_NONE)
657                 stripspace(&sb, 0);
658
659         if (signoff) {
660                 struct strbuf sob = STRBUF_INIT;
661                 int i;
662
663                 strbuf_addstr(&sob, sign_off_header);
664                 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
665                                              getenv("GIT_COMMITTER_EMAIL")));
666                 strbuf_addch(&sob, '\n');
667                 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
668                         ; /* do nothing */
669                 if (prefixcmp(sb.buf + i, sob.buf)) {
670                         if (!i || !ends_rfc2822_footer(&sb))
671                                 strbuf_addch(&sb, '\n');
672                         strbuf_addbuf(&sb, &sob);
673                 }
674                 strbuf_release(&sob);
675         }
676
677         if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
678                 die_errno("could not write commit template");
679
680         strbuf_release(&sb);
681
682         determine_author_info();
683
684         /* This checks if committer ident is explicitly given */
685         git_committer_info(0);
686         if (use_editor && include_status) {
687                 char *author_ident;
688                 const char *committer_ident;
689
690                 if (in_merge)
691                         fprintf(fp,
692                                 "#\n"
693                                 "# It looks like you may be committing a MERGE.\n"
694                                 "# If this is not correct, please remove the file\n"
695                                 "#      %s\n"
696                                 "# and try again.\n"
697                                 "#\n",
698                                 git_path("MERGE_HEAD"));
699
700                 fprintf(fp,
701                         "\n"
702                         "# Please enter the commit message for your changes.");
703                 if (cleanup_mode == CLEANUP_ALL)
704                         fprintf(fp,
705                                 " Lines starting\n"
706                                 "# with '#' will be ignored, and an empty"
707                                 " message aborts the commit.\n");
708                 else /* CLEANUP_SPACE, that is. */
709                         fprintf(fp,
710                                 " Lines starting\n"
711                                 "# with '#' will be kept; you may remove them"
712                                 " yourself if you want to.\n"
713                                 "# An empty message aborts the commit.\n");
714                 if (only_include_assumed)
715                         fprintf(fp, "# %s\n", only_include_assumed);
716
717                 author_ident = xstrdup(fmt_name(author_name, author_email));
718                 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
719                                            getenv("GIT_COMMITTER_EMAIL"));
720                 if (strcmp(author_ident, committer_ident))
721                         fprintf(fp,
722                                 "%s"
723                                 "# Author:    %s\n",
724                                 ident_shown++ ? "" : "#\n",
725                                 author_ident);
726                 free(author_ident);
727
728                 if (!user_ident_sufficiently_given())
729                         fprintf(fp,
730                                 "%s"
731                                 "# Committer: %s\n",
732                                 ident_shown++ ? "" : "#\n",
733                                 committer_ident);
734
735                 if (ident_shown)
736                         fprintf(fp, "#\n");
737
738                 saved_color_setting = s->use_color;
739                 s->use_color = 0;
740                 commitable = run_status(fp, index_file, prefix, 1, s);
741                 s->use_color = saved_color_setting;
742         } else {
743                 unsigned char sha1[20];
744                 const char *parent = "HEAD";
745
746                 if (!active_nr && read_cache() < 0)
747                         die("Cannot read index");
748
749                 if (amend)
750                         parent = "HEAD^1";
751
752                 if (get_sha1(parent, sha1))
753                         commitable = !!active_nr;
754                 else
755                         commitable = index_differs_from(parent, 0);
756         }
757
758         fclose(fp);
759
760         if (!commitable && !in_merge && !allow_empty &&
761             !(amend && is_a_merge(head_sha1))) {
762                 run_status(stdout, index_file, prefix, 0, s);
763                 if (amend)
764                         fputs(empty_amend_advice, stderr);
765                 return 0;
766         }
767
768         /*
769          * Re-read the index as pre-commit hook could have updated it,
770          * and write it out as a tree.  We must do this before we invoke
771          * the editor and after we invoke run_status above.
772          */
773         discard_cache();
774         read_cache_from(index_file);
775         if (!active_cache_tree)
776                 active_cache_tree = cache_tree();
777         if (cache_tree_update(active_cache_tree,
778                               active_cache, active_nr, 0, 0) < 0) {
779                 error("Error building trees");
780                 return 0;
781         }
782
783         if (run_hook(index_file, "prepare-commit-msg",
784                      git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
785                 return 0;
786
787         if (use_editor) {
788                 char index[PATH_MAX];
789                 const char *env[2] = { NULL };
790                 env[0] =  index;
791                 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
792                 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
793                         fprintf(stderr,
794                         "Please supply the message using either -m or -F option.\n");
795                         exit(1);
796                 }
797         }
798
799         if (!no_verify &&
800             run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
801                 return 0;
802         }
803
804         return 1;
805 }
806
807 /*
808  * Find out if the message in the strbuf contains only whitespace and
809  * Signed-off-by lines.
810  */
811 static int message_is_empty(struct strbuf *sb)
812 {
813         struct strbuf tmpl = STRBUF_INIT;
814         const char *nl;
815         int eol, i, start = 0;
816
817         if (cleanup_mode == CLEANUP_NONE && sb->len)
818                 return 0;
819
820         /* See if the template is just a prefix of the message. */
821         if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
822                 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
823                 if (start + tmpl.len <= sb->len &&
824                     memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
825                         start += tmpl.len;
826         }
827         strbuf_release(&tmpl);
828
829         /* Check if the rest is just whitespace and Signed-of-by's. */
830         for (i = start; i < sb->len; i++) {
831                 nl = memchr(sb->buf + i, '\n', sb->len - i);
832                 if (nl)
833                         eol = nl - sb->buf;
834                 else
835                         eol = sb->len;
836
837                 if (strlen(sign_off_header) <= eol - i &&
838                     !prefixcmp(sb->buf + i, sign_off_header)) {
839                         i = eol;
840                         continue;
841                 }
842                 while (i < eol)
843                         if (!isspace(sb->buf[i++]))
844                                 return 0;
845         }
846
847         return 1;
848 }
849
850 static const char *find_author_by_nickname(const char *name)
851 {
852         struct rev_info revs;
853         struct commit *commit;
854         struct strbuf buf = STRBUF_INIT;
855         const char *av[20];
856         int ac = 0;
857
858         init_revisions(&revs, NULL);
859         strbuf_addf(&buf, "--author=%s", name);
860         av[++ac] = "--all";
861         av[++ac] = "-i";
862         av[++ac] = buf.buf;
863         av[++ac] = NULL;
864         setup_revisions(ac, av, &revs, NULL);
865         prepare_revision_walk(&revs);
866         commit = get_revision(&revs);
867         if (commit) {
868                 struct pretty_print_context ctx = {0};
869                 ctx.date_mode = DATE_NORMAL;
870                 strbuf_release(&buf);
871                 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
872                 return strbuf_detach(&buf, NULL);
873         }
874         die("No existing author found with '%s'", name);
875 }
876
877
878 static void handle_untracked_files_arg(struct wt_status *s)
879 {
880         if (!untracked_files_arg)
881                 ; /* default already initialized */
882         else if (!strcmp(untracked_files_arg, "no"))
883                 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
884         else if (!strcmp(untracked_files_arg, "normal"))
885                 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
886         else if (!strcmp(untracked_files_arg, "all"))
887                 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
888         else
889                 die("Invalid untracked files mode '%s'", untracked_files_arg);
890 }
891
892 static int parse_and_validate_options(int argc, const char *argv[],
893                                       const char * const usage[],
894                                       const char *prefix,
895                                       struct wt_status *s)
896 {
897         int f = 0;
898
899         argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
900                              0);
901
902         if (force_author && !strchr(force_author, '>'))
903                 force_author = find_author_by_nickname(force_author);
904
905         if (force_author && renew_authorship)
906                 die("Using both --reset-author and --author does not make sense");
907
908         if (logfile || message.len || use_message || fixup_message)
909                 use_editor = 0;
910         if (edit_flag)
911                 use_editor = 1;
912         if (!use_editor)
913                 setenv("GIT_EDITOR", ":", 1);
914
915         if (get_sha1("HEAD", head_sha1))
916                 initial_commit = 1;
917
918         /* Sanity check options */
919         if (amend && initial_commit)
920                 die("You have nothing to amend.");
921         if (amend && in_merge)
922                 die("You are in the middle of a merge -- cannot amend.");
923         if (fixup_message && squash_message)
924                 die("Options --squash and --fixup cannot be used together");
925         if (use_message)
926                 f++;
927         if (edit_message)
928                 f++;
929         if (fixup_message)
930                 f++;
931         if (logfile)
932                 f++;
933         if (f > 1)
934                 die("Only one of -c/-C/-F/--fixup can be used.");
935         if (message.len && f > 0)
936                 die("Option -m cannot be combined with -c/-C/-F/--fixup.");
937         if (edit_message)
938                 use_message = edit_message;
939         if (amend && !use_message && !fixup_message)
940                 use_message = "HEAD";
941         if (!use_message && renew_authorship)
942                 die("--reset-author can be used only with -C, -c or --amend.");
943         if (use_message) {
944                 const char *out_enc;
945                 struct commit *commit;
946
947                 commit = lookup_commit_reference_by_name(use_message);
948                 if (!commit)
949                         die("could not lookup commit %s", use_message);
950                 out_enc = get_commit_output_encoding();
951                 use_message_buffer = logmsg_reencode(commit, out_enc);
952
953                 /*
954                  * If we failed to reencode the buffer, just copy it
955                  * byte for byte so the user can try to fix it up.
956                  * This also handles the case where input and output
957                  * encodings are identical.
958                  */
959                 if (use_message_buffer == NULL)
960                         use_message_buffer = xstrdup(commit->buffer);
961         }
962
963         if (!!also + !!only + !!all + !!interactive > 1)
964                 die("Only one of --include/--only/--all/--interactive can be used.");
965         if (argc == 0 && (also || (only && !amend)))
966                 die("No paths with --include/--only does not make sense.");
967         if (argc == 0 && only && amend)
968                 only_include_assumed = "Clever... amending the last one with dirty index.";
969         if (argc > 0 && !also && !only)
970                 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
971         if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
972                 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
973         else if (!strcmp(cleanup_arg, "verbatim"))
974                 cleanup_mode = CLEANUP_NONE;
975         else if (!strcmp(cleanup_arg, "whitespace"))
976                 cleanup_mode = CLEANUP_SPACE;
977         else if (!strcmp(cleanup_arg, "strip"))
978                 cleanup_mode = CLEANUP_ALL;
979         else
980                 die("Invalid cleanup mode %s", cleanup_arg);
981
982         handle_untracked_files_arg(s);
983
984         if (all && argc > 0)
985                 die("Paths with -a does not make sense.");
986         else if (interactive && argc > 0)
987                 die("Paths with --interactive does not make sense.");
988
989         if (null_termination && status_format == STATUS_FORMAT_LONG)
990                 status_format = STATUS_FORMAT_PORCELAIN;
991         if (status_format != STATUS_FORMAT_LONG)
992                 dry_run = 1;
993
994         return argc;
995 }
996
997 static int dry_run_commit(int argc, const char **argv, const char *prefix,
998                           struct wt_status *s)
999 {
1000         int commitable;
1001         const char *index_file;
1002
1003         index_file = prepare_index(argc, argv, prefix, 1);
1004         commitable = run_status(stdout, index_file, prefix, 0, s);
1005         rollback_index_files();
1006
1007         return commitable ? 0 : 1;
1008 }
1009
1010 static int parse_status_slot(const char *var, int offset)
1011 {
1012         if (!strcasecmp(var+offset, "header"))
1013                 return WT_STATUS_HEADER;
1014         if (!strcasecmp(var+offset, "updated")
1015                 || !strcasecmp(var+offset, "added"))
1016                 return WT_STATUS_UPDATED;
1017         if (!strcasecmp(var+offset, "changed"))
1018                 return WT_STATUS_CHANGED;
1019         if (!strcasecmp(var+offset, "untracked"))
1020                 return WT_STATUS_UNTRACKED;
1021         if (!strcasecmp(var+offset, "nobranch"))
1022                 return WT_STATUS_NOBRANCH;
1023         if (!strcasecmp(var+offset, "unmerged"))
1024                 return WT_STATUS_UNMERGED;
1025         return -1;
1026 }
1027
1028 static int git_status_config(const char *k, const char *v, void *cb)
1029 {
1030         struct wt_status *s = cb;
1031
1032         if (!strcmp(k, "status.submodulesummary")) {
1033                 int is_bool;
1034                 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1035                 if (is_bool && s->submodule_summary)
1036                         s->submodule_summary = -1;
1037                 return 0;
1038         }
1039         if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1040                 s->use_color = git_config_colorbool(k, v, -1);
1041                 return 0;
1042         }
1043         if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1044                 int slot = parse_status_slot(k, 13);
1045                 if (slot < 0)
1046                         return 0;
1047                 if (!v)
1048                         return config_error_nonbool(k);
1049                 color_parse(v, k, s->color_palette[slot]);
1050                 return 0;
1051         }
1052         if (!strcmp(k, "status.relativepaths")) {
1053                 s->relative_paths = git_config_bool(k, v);
1054                 return 0;
1055         }
1056         if (!strcmp(k, "status.showuntrackedfiles")) {
1057                 if (!v)
1058                         return config_error_nonbool(k);
1059                 else if (!strcmp(v, "no"))
1060                         s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1061                 else if (!strcmp(v, "normal"))
1062                         s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1063                 else if (!strcmp(v, "all"))
1064                         s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1065                 else
1066                         return error("Invalid untracked files mode '%s'", v);
1067                 return 0;
1068         }
1069         return git_diff_ui_config(k, v, NULL);
1070 }
1071
1072 int cmd_status(int argc, const char **argv, const char *prefix)
1073 {
1074         struct wt_status s;
1075         int fd;
1076         unsigned char sha1[20];
1077         static struct option builtin_status_options[] = {
1078                 OPT__VERBOSE(&verbose, "be verbose"),
1079                 OPT_SET_INT('s', "short", &status_format,
1080                             "show status concisely", STATUS_FORMAT_SHORT),
1081                 OPT_BOOLEAN('b', "branch", &status_show_branch,
1082                             "show branch information"),
1083                 OPT_SET_INT(0, "porcelain", &status_format,
1084                             "show porcelain output format",
1085                             STATUS_FORMAT_PORCELAIN),
1086                 OPT_BOOLEAN('z', "null", &null_termination,
1087                             "terminate entries with NUL"),
1088                 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1089                   "mode",
1090                   "show untracked files, optional modes: all, normal, no. (Default: all)",
1091                   PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1092                 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1093                             "show ignored files"),
1094                 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, "when",
1095                   "ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)",
1096                   PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1097                 OPT_END(),
1098         };
1099
1100         if (argc == 2 && !strcmp(argv[1], "-h"))
1101                 usage_with_options(builtin_status_usage, builtin_status_options);
1102
1103         if (null_termination && status_format == STATUS_FORMAT_LONG)
1104                 status_format = STATUS_FORMAT_PORCELAIN;
1105
1106         wt_status_prepare(&s);
1107         gitmodules_config();
1108         git_config(git_status_config, &s);
1109         in_merge = file_exists(git_path("MERGE_HEAD"));
1110         argc = parse_options(argc, argv, prefix,
1111                              builtin_status_options,
1112                              builtin_status_usage, 0);
1113         handle_untracked_files_arg(&s);
1114         if (show_ignored_in_status)
1115                 s.show_ignored_files = 1;
1116         if (*argv)
1117                 s.pathspec = get_pathspec(prefix, argv);
1118
1119         read_cache_preload(s.pathspec);
1120         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1121
1122         fd = hold_locked_index(&index_lock, 0);
1123         if (0 <= fd) {
1124                 if (active_cache_changed &&
1125                     !write_cache(fd, active_cache, active_nr))
1126                         commit_locked_index(&index_lock);
1127                 else
1128                         rollback_lock_file(&index_lock);
1129         }
1130
1131         s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1132         s.in_merge = in_merge;
1133         s.ignore_submodule_arg = ignore_submodule_arg;
1134         wt_status_collect(&s);
1135
1136         if (s.relative_paths)
1137                 s.prefix = prefix;
1138         if (s.use_color == -1)
1139                 s.use_color = git_use_color_default;
1140         if (diff_use_color_default == -1)
1141                 diff_use_color_default = git_use_color_default;
1142
1143         switch (status_format) {
1144         case STATUS_FORMAT_SHORT:
1145                 wt_shortstatus_print(&s, null_termination, status_show_branch);
1146                 break;
1147         case STATUS_FORMAT_PORCELAIN:
1148                 wt_porcelain_print(&s, null_termination);
1149                 break;
1150         case STATUS_FORMAT_LONG:
1151                 s.verbose = verbose;
1152                 s.ignore_submodule_arg = ignore_submodule_arg;
1153                 wt_status_print(&s);
1154                 break;
1155         }
1156         return 0;
1157 }
1158
1159 static void print_summary(const char *prefix, const unsigned char *sha1)
1160 {
1161         struct rev_info rev;
1162         struct commit *commit;
1163         struct strbuf format = STRBUF_INIT;
1164         unsigned char junk_sha1[20];
1165         const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1166         struct pretty_print_context pctx = {0};
1167         struct strbuf author_ident = STRBUF_INIT;
1168         struct strbuf committer_ident = STRBUF_INIT;
1169
1170         commit = lookup_commit(sha1);
1171         if (!commit)
1172                 die("couldn't look up newly created commit");
1173         if (!commit || parse_commit(commit))
1174                 die("could not parse newly created commit");
1175
1176         strbuf_addstr(&format, "format:%h] %s");
1177
1178         format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1179         format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1180         if (strbuf_cmp(&author_ident, &committer_ident)) {
1181                 strbuf_addstr(&format, "\n Author: ");
1182                 strbuf_addbuf_percentquote(&format, &author_ident);
1183         }
1184         if (!user_ident_sufficiently_given()) {
1185                 strbuf_addstr(&format, "\n Committer: ");
1186                 strbuf_addbuf_percentquote(&format, &committer_ident);
1187                 if (advice_implicit_identity) {
1188                         strbuf_addch(&format, '\n');
1189                         strbuf_addstr(&format, implicit_ident_advice);
1190                 }
1191         }
1192         strbuf_release(&author_ident);
1193         strbuf_release(&committer_ident);
1194
1195         init_revisions(&rev, prefix);
1196         setup_revisions(0, NULL, &rev, NULL);
1197
1198         rev.diff = 1;
1199         rev.diffopt.output_format =
1200                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1201
1202         rev.verbose_header = 1;
1203         rev.show_root_diff = 1;
1204         get_commit_format(format.buf, &rev);
1205         rev.always_show_header = 0;
1206         rev.diffopt.detect_rename = 1;
1207         rev.diffopt.rename_limit = 100;
1208         rev.diffopt.break_opt = 0;
1209         diff_setup_done(&rev.diffopt);
1210
1211         printf("[%s%s ",
1212                 !prefixcmp(head, "refs/heads/") ?
1213                         head + 11 :
1214                         !strcmp(head, "HEAD") ?
1215                                 "detached HEAD" :
1216                                 head,
1217                 initial_commit ? " (root-commit)" : "");
1218
1219         if (!log_tree_commit(&rev, commit)) {
1220                 rev.always_show_header = 1;
1221                 rev.use_terminator = 1;
1222                 log_tree_commit(&rev, commit);
1223         }
1224
1225         strbuf_release(&format);
1226 }
1227
1228 static int git_commit_config(const char *k, const char *v, void *cb)
1229 {
1230         struct wt_status *s = cb;
1231
1232         if (!strcmp(k, "commit.template"))
1233                 return git_config_pathname(&template_file, k, v);
1234         if (!strcmp(k, "commit.status")) {
1235                 include_status = git_config_bool(k, v);
1236                 return 0;
1237         }
1238
1239         return git_status_config(k, v, s);
1240 }
1241
1242 static const char post_rewrite_hook[] = "hooks/post-rewrite";
1243
1244 static int run_rewrite_hook(const unsigned char *oldsha1,
1245                             const unsigned char *newsha1)
1246 {
1247         /* oldsha1 SP newsha1 LF NUL */
1248         static char buf[2*40 + 3];
1249         struct child_process proc;
1250         const char *argv[3];
1251         int code;
1252         size_t n;
1253
1254         if (access(git_path(post_rewrite_hook), X_OK) < 0)
1255                 return 0;
1256
1257         argv[0] = git_path(post_rewrite_hook);
1258         argv[1] = "amend";
1259         argv[2] = NULL;
1260
1261         memset(&proc, 0, sizeof(proc));
1262         proc.argv = argv;
1263         proc.in = -1;
1264         proc.stdout_to_stderr = 1;
1265
1266         code = start_command(&proc);
1267         if (code)
1268                 return code;
1269         n = snprintf(buf, sizeof(buf), "%s %s\n",
1270                      sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1271         write_in_full(proc.in, buf, n);
1272         close(proc.in);
1273         return finish_command(&proc);
1274 }
1275
1276 int cmd_commit(int argc, const char **argv, const char *prefix)
1277 {
1278         struct strbuf sb = STRBUF_INIT;
1279         const char *index_file, *reflog_msg;
1280         char *nl, *p;
1281         unsigned char commit_sha1[20];
1282         struct ref_lock *ref_lock;
1283         struct commit_list *parents = NULL, **pptr = &parents;
1284         struct stat statbuf;
1285         int allow_fast_forward = 1;
1286         struct wt_status s;
1287
1288         if (argc == 2 && !strcmp(argv[1], "-h"))
1289                 usage_with_options(builtin_commit_usage, builtin_commit_options);
1290
1291         wt_status_prepare(&s);
1292         git_config(git_commit_config, &s);
1293         in_merge = file_exists(git_path("MERGE_HEAD"));
1294         s.in_merge = in_merge;
1295
1296         if (s.use_color == -1)
1297                 s.use_color = git_use_color_default;
1298         argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1299                                           prefix, &s);
1300         if (dry_run) {
1301                 if (diff_use_color_default == -1)
1302                         diff_use_color_default = git_use_color_default;
1303                 return dry_run_commit(argc, argv, prefix, &s);
1304         }
1305         index_file = prepare_index(argc, argv, prefix, 0);
1306
1307         /* Set up everything for writing the commit object.  This includes
1308            running hooks, writing the trees, and interacting with the user.  */
1309         if (!prepare_to_commit(index_file, prefix, &s)) {
1310                 rollback_index_files();
1311                 return 1;
1312         }
1313
1314         /* Determine parents */
1315         reflog_msg = getenv("GIT_REFLOG_ACTION");
1316         if (initial_commit) {
1317                 if (!reflog_msg)
1318                         reflog_msg = "commit (initial)";
1319         } else if (amend) {
1320                 struct commit_list *c;
1321                 struct commit *commit;
1322
1323                 if (!reflog_msg)
1324                         reflog_msg = "commit (amend)";
1325                 commit = lookup_commit(head_sha1);
1326                 if (!commit || parse_commit(commit))
1327                         die("could not parse HEAD commit");
1328
1329                 for (c = commit->parents; c; c = c->next)
1330                         pptr = &commit_list_insert(c->item, pptr)->next;
1331         } else if (in_merge) {
1332                 struct strbuf m = STRBUF_INIT;
1333                 FILE *fp;
1334
1335                 if (!reflog_msg)
1336                         reflog_msg = "commit (merge)";
1337                 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1338                 fp = fopen(git_path("MERGE_HEAD"), "r");
1339                 if (fp == NULL)
1340                         die_errno("could not open '%s' for reading",
1341                                   git_path("MERGE_HEAD"));
1342                 while (strbuf_getline(&m, fp, '\n') != EOF) {
1343                         unsigned char sha1[20];
1344                         if (get_sha1_hex(m.buf, sha1) < 0)
1345                                 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1346                         pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1347                 }
1348                 fclose(fp);
1349                 strbuf_release(&m);
1350                 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1351                         if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1352                                 die_errno("could not read MERGE_MODE");
1353                         if (!strcmp(sb.buf, "no-ff"))
1354                                 allow_fast_forward = 0;
1355                 }
1356                 if (allow_fast_forward)
1357                         parents = reduce_heads(parents);
1358         } else {
1359                 if (!reflog_msg)
1360                         reflog_msg = "commit";
1361                 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1362         }
1363
1364         /* Finally, get the commit message */
1365         strbuf_reset(&sb);
1366         if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1367                 int saved_errno = errno;
1368                 rollback_index_files();
1369                 die("could not read commit message: %s", strerror(saved_errno));
1370         }
1371
1372         /* Truncate the message just before the diff, if any. */
1373         if (verbose) {
1374                 p = strstr(sb.buf, "\ndiff --git ");
1375                 if (p != NULL)
1376                         strbuf_setlen(&sb, p - sb.buf + 1);
1377         }
1378
1379         if (cleanup_mode != CLEANUP_NONE)
1380                 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1381         if (message_is_empty(&sb) && !allow_empty_message) {
1382                 rollback_index_files();
1383                 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1384                 exit(1);
1385         }
1386
1387         if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1388                         fmt_ident(author_name, author_email, author_date,
1389                                 IDENT_ERROR_ON_NO_NAME))) {
1390                 rollback_index_files();
1391                 die("failed to write commit object");
1392         }
1393
1394         ref_lock = lock_any_ref_for_update("HEAD",
1395                                            initial_commit ? NULL : head_sha1,
1396                                            0);
1397
1398         nl = strchr(sb.buf, '\n');
1399         if (nl)
1400                 strbuf_setlen(&sb, nl + 1 - sb.buf);
1401         else
1402                 strbuf_addch(&sb, '\n');
1403         strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1404         strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1405
1406         if (!ref_lock) {
1407                 rollback_index_files();
1408                 die("cannot lock HEAD ref");
1409         }
1410         if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1411                 rollback_index_files();
1412                 die("cannot update HEAD ref");
1413         }
1414
1415         unlink(git_path("MERGE_HEAD"));
1416         unlink(git_path("MERGE_MSG"));
1417         unlink(git_path("MERGE_MODE"));
1418         unlink(git_path("SQUASH_MSG"));
1419
1420         if (commit_index_files())
1421                 die ("Repository has been updated, but unable to write\n"
1422                      "new_index file. Check that disk is not full or quota is\n"
1423                      "not exceeded, and then \"git reset HEAD\" to recover.");
1424
1425         rerere(0);
1426         run_hook(get_index_file(), "post-commit", NULL);
1427         if (amend && !no_post_rewrite) {
1428                 struct notes_rewrite_cfg *cfg;
1429                 cfg = init_copy_notes_for_rewrite("amend");
1430                 if (cfg) {
1431                         copy_note_for_rewrite(cfg, head_sha1, commit_sha1);
1432                         finish_copy_notes_for_rewrite(cfg);
1433                 }
1434                 run_rewrite_hook(head_sha1, commit_sha1);
1435         }
1436         if (!quiet)
1437                 print_summary(prefix, commit_sha1);
1438
1439         return 0;
1440 }