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