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