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