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