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