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