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