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