Merge tag 'v2.2.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 export_one(const char *var, const char *s, const char *e, int hack)
527 {
528         struct strbuf buf = STRBUF_INIT;
529         if (hack)
530                 strbuf_addch(&buf, hack);
531         strbuf_addf(&buf, "%.*s", (int)(e - s), s);
532         setenv(var, buf.buf, 1);
533         strbuf_release(&buf);
534 }
535
536 static int sane_ident_split(struct ident_split *person)
537 {
538         if (!person->name_begin || !person->name_end ||
539             person->name_begin == person->name_end)
540                 return 0; /* no human readable name */
541         if (!person->mail_begin || !person->mail_end ||
542             person->mail_begin == person->mail_end)
543                 return 0; /* no usable mail */
544         if (!person->date_begin || !person->date_end ||
545             !person->tz_begin || !person->tz_end)
546                 return 0;
547         return 1;
548 }
549
550 static int parse_force_date(const char *in, struct strbuf *out)
551 {
552         strbuf_addch(out, '@');
553
554         if (parse_date(in, out) < 0) {
555                 int errors = 0;
556                 unsigned long t = approxidate_careful(in, &errors);
557                 if (errors)
558                         return -1;
559                 strbuf_addf(out, "%lu", t);
560         }
561
562         return 0;
563 }
564
565 static void set_ident_var(char **buf, char *val)
566 {
567         free(*buf);
568         *buf = val;
569 }
570
571 static char *envdup(const char *var)
572 {
573         const char *val = getenv(var);
574         return val ? xstrdup(val) : NULL;
575 }
576
577 static void determine_author_info(struct strbuf *author_ident)
578 {
579         char *name, *email, *date;
580         struct ident_split author;
581
582         name = envdup("GIT_AUTHOR_NAME");
583         email = envdup("GIT_AUTHOR_EMAIL");
584         date = envdup("GIT_AUTHOR_DATE");
585
586         if (author_message) {
587                 struct ident_split ident;
588                 size_t len;
589                 const char *a;
590
591                 a = find_commit_header(author_message_buffer, "author", &len);
592                 if (!a)
593                         die(_("commit '%s' lacks author header"), author_message);
594                 if (split_ident_line(&ident, a, len) < 0)
595                         die(_("commit '%s' has malformed author line"), author_message);
596
597                 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
598                 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
599
600                 if (ident.date_begin) {
601                         struct strbuf date_buf = STRBUF_INIT;
602                         strbuf_addch(&date_buf, '@');
603                         strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
604                         strbuf_addch(&date_buf, ' ');
605                         strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
606                         set_ident_var(&date, strbuf_detach(&date_buf, NULL));
607                 }
608         }
609
610         if (force_author) {
611                 struct ident_split ident;
612
613                 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
614                         die(_("malformed --author parameter"));
615                 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
616                 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
617         }
618
619         if (force_date) {
620                 struct strbuf date_buf = STRBUF_INIT;
621                 if (parse_force_date(force_date, &date_buf))
622                         die(_("invalid date format: %s"), force_date);
623                 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
624         }
625
626         strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
627         if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
628             sane_ident_split(&author)) {
629                 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
630                 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
631                 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
632         }
633
634         free(name);
635         free(email);
636         free(date);
637 }
638
639 static void split_ident_or_die(struct ident_split *id, const struct strbuf *buf)
640 {
641         if (split_ident_line(id, buf->buf, buf->len) ||
642             !sane_ident_split(id))
643                 die(_("Malformed ident string: '%s'"), buf->buf);
644 }
645
646 static int author_date_is_interesting(void)
647 {
648         return author_message || force_date;
649 }
650
651 static void adjust_comment_line_char(const struct strbuf *sb)
652 {
653         char candidates[] = "#;@!$%^&|:";
654         char *candidate;
655         const char *p;
656
657         comment_line_char = candidates[0];
658         if (!memchr(sb->buf, comment_line_char, sb->len))
659                 return;
660
661         p = sb->buf;
662         candidate = strchr(candidates, *p);
663         if (candidate)
664                 *candidate = ' ';
665         for (p = sb->buf; *p; p++) {
666                 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
667                         candidate = strchr(candidates, p[1]);
668                         if (candidate)
669                                 *candidate = ' ';
670                 }
671         }
672
673         for (p = candidates; *p == ' '; p++)
674                 ;
675         if (!*p)
676                 die(_("unable to select a comment character that is not used\n"
677                       "in the current commit message"));
678         comment_line_char = *p;
679 }
680
681 static int prepare_to_commit(const char *index_file, const char *prefix,
682                              struct commit *current_head,
683                              struct wt_status *s,
684                              struct strbuf *author_ident)
685 {
686         struct stat statbuf;
687         struct strbuf committer_ident = STRBUF_INIT;
688         int commitable;
689         struct strbuf sb = STRBUF_INIT;
690         const char *hook_arg1 = NULL;
691         const char *hook_arg2 = NULL;
692         int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
693         int old_display_comment_prefix;
694
695         /* This checks and barfs if author is badly specified */
696         determine_author_info(author_ident);
697
698         if (!no_verify && run_commit_hook(use_editor, index_file, "pre-commit", NULL))
699                 return 0;
700
701         if (squash_message) {
702                 /*
703                  * Insert the proper subject line before other commit
704                  * message options add their content.
705                  */
706                 if (use_message && !strcmp(use_message, squash_message))
707                         strbuf_addstr(&sb, "squash! ");
708                 else {
709                         struct pretty_print_context ctx = {0};
710                         struct commit *c;
711                         c = lookup_commit_reference_by_name(squash_message);
712                         if (!c)
713                                 die(_("could not lookup commit %s"), squash_message);
714                         ctx.output_encoding = get_commit_output_encoding();
715                         format_commit_message(c, "squash! %s\n\n", &sb,
716                                               &ctx);
717                 }
718         }
719
720         if (message.len) {
721                 strbuf_addbuf(&sb, &message);
722                 hook_arg1 = "message";
723         } else if (logfile && !strcmp(logfile, "-")) {
724                 if (isatty(0))
725                         fprintf(stderr, _("(reading log message from standard input)\n"));
726                 if (strbuf_read(&sb, 0, 0) < 0)
727                         die_errno(_("could not read log from standard input"));
728                 hook_arg1 = "message";
729         } else if (logfile) {
730                 if (strbuf_read_file(&sb, logfile, 0) < 0)
731                         die_errno(_("could not read log file '%s'"),
732                                   logfile);
733                 hook_arg1 = "message";
734         } else if (use_message) {
735                 char *buffer;
736                 buffer = strstr(use_message_buffer, "\n\n");
737                 if (buffer)
738                         strbuf_addstr(&sb, buffer + 2);
739                 hook_arg1 = "commit";
740                 hook_arg2 = use_message;
741         } else if (fixup_message) {
742                 struct pretty_print_context ctx = {0};
743                 struct commit *commit;
744                 commit = lookup_commit_reference_by_name(fixup_message);
745                 if (!commit)
746                         die(_("could not lookup commit %s"), fixup_message);
747                 ctx.output_encoding = get_commit_output_encoding();
748                 format_commit_message(commit, "fixup! %s\n\n",
749                                       &sb, &ctx);
750                 hook_arg1 = "message";
751         } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
752                 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
753                         die_errno(_("could not read MERGE_MSG"));
754                 hook_arg1 = "merge";
755         } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
756                 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
757                         die_errno(_("could not read SQUASH_MSG"));
758                 hook_arg1 = "squash";
759         } else if (template_file) {
760                 if (strbuf_read_file(&sb, template_file, 0) < 0)
761                         die_errno(_("could not read '%s'"), template_file);
762                 hook_arg1 = "template";
763                 clean_message_contents = 0;
764         }
765
766         /*
767          * The remaining cases don't modify the template message, but
768          * just set the argument(s) to the prepare-commit-msg hook.
769          */
770         else if (whence == FROM_MERGE)
771                 hook_arg1 = "merge";
772         else if (whence == FROM_CHERRY_PICK) {
773                 hook_arg1 = "commit";
774                 hook_arg2 = "CHERRY_PICK_HEAD";
775         }
776
777         if (squash_message) {
778                 /*
779                  * If squash_commit was used for the commit subject,
780                  * then we're possibly hijacking other commit log options.
781                  * Reset the hook args to tell the real story.
782                  */
783                 hook_arg1 = "message";
784                 hook_arg2 = "";
785         }
786
787         s->fp = fopen(git_path(commit_editmsg), "w");
788         if (s->fp == NULL)
789                 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
790
791         /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
792         old_display_comment_prefix = s->display_comment_prefix;
793         s->display_comment_prefix = 1;
794
795         /*
796          * Most hints are counter-productive when the commit has
797          * already started.
798          */
799         s->hints = 0;
800
801         if (clean_message_contents)
802                 stripspace(&sb, 0);
803
804         if (signoff) {
805                 /*
806                  * See if we have a Conflicts: block at the end. If yes, count
807                  * its size, so we can ignore it.
808                  */
809                 int ignore_footer = 0;
810                 int i, eol, previous = 0;
811                 const char *nl;
812
813                 for (i = 0; i < sb.len; i++) {
814                         nl = memchr(sb.buf + i, '\n', sb.len - i);
815                         if (nl)
816                                 eol = nl - sb.buf;
817                         else
818                                 eol = sb.len;
819                         if (starts_with(sb.buf + previous, "\nConflicts:\n")) {
820                                 ignore_footer = sb.len - previous;
821                                 break;
822                         }
823                         while (i < eol)
824                                 i++;
825                         previous = eol;
826                 }
827
828                 append_signoff(&sb, ignore_footer, 0);
829         }
830
831         if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
832                 die_errno(_("could not write commit template"));
833
834         if (auto_comment_line_char)
835                 adjust_comment_line_char(&sb);
836         strbuf_release(&sb);
837
838         /* This checks if committer ident is explicitly given */
839         strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
840         if (use_editor && include_status) {
841                 int ident_shown = 0;
842                 int saved_color_setting;
843                 struct ident_split ci, ai;
844
845                 if (whence != FROM_COMMIT) {
846                         if (cleanup_mode == CLEANUP_SCISSORS)
847                                 wt_status_add_cut_line(s->fp);
848                         status_printf_ln(s, GIT_COLOR_NORMAL,
849                             whence == FROM_MERGE
850                                 ? _("\n"
851                                         "It looks like you may be committing a merge.\n"
852                                         "If this is not correct, please remove the file\n"
853                                         "       %s\n"
854                                         "and try again.\n")
855                                 : _("\n"
856                                         "It looks like you may be committing a cherry-pick.\n"
857                                         "If this is not correct, please remove the file\n"
858                                         "       %s\n"
859                                         "and try again.\n"),
860                                 git_path(whence == FROM_MERGE
861                                          ? "MERGE_HEAD"
862                                          : "CHERRY_PICK_HEAD"));
863                 }
864
865                 fprintf(s->fp, "\n");
866                 if (cleanup_mode == CLEANUP_ALL)
867                         status_printf(s, GIT_COLOR_NORMAL,
868                                 _("Please enter the commit message for your changes."
869                                   " Lines starting\nwith '%c' will be ignored, and an empty"
870                                   " message aborts the commit.\n"), comment_line_char);
871                 else if (cleanup_mode == CLEANUP_SCISSORS && whence == FROM_COMMIT)
872                         wt_status_add_cut_line(s->fp);
873                 else /* CLEANUP_SPACE, that is. */
874                         status_printf(s, GIT_COLOR_NORMAL,
875                                 _("Please enter the commit message for your changes."
876                                   " Lines starting\n"
877                                   "with '%c' will be kept; you may remove them"
878                                   " yourself if you want to.\n"
879                                   "An empty message aborts the commit.\n"), comment_line_char);
880                 if (only_include_assumed)
881                         status_printf_ln(s, GIT_COLOR_NORMAL,
882                                         "%s", only_include_assumed);
883
884                 split_ident_or_die(&ai, author_ident);
885                 split_ident_or_die(&ci, &committer_ident);
886
887                 if (ident_cmp(&ai, &ci))
888                         status_printf_ln(s, GIT_COLOR_NORMAL,
889                                 _("%s"
890                                 "Author:    %.*s <%.*s>"),
891                                 ident_shown++ ? "" : "\n",
892                                 (int)(ai.name_end - ai.name_begin), ai.name_begin,
893                                 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
894
895                 if (author_date_is_interesting())
896                         status_printf_ln(s, GIT_COLOR_NORMAL,
897                                 _("%s"
898                                 "Date:      %s"),
899                                 ident_shown++ ? "" : "\n",
900                                 show_ident_date(&ai, DATE_NORMAL));
901
902                 if (!committer_ident_sufficiently_given())
903                         status_printf_ln(s, GIT_COLOR_NORMAL,
904                                 _("%s"
905                                 "Committer: %.*s <%.*s>"),
906                                 ident_shown++ ? "" : "\n",
907                                 (int)(ci.name_end - ci.name_begin), ci.name_begin,
908                                 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
909
910                 if (ident_shown)
911                         status_printf_ln(s, GIT_COLOR_NORMAL, "%s", "");
912
913                 saved_color_setting = s->use_color;
914                 s->use_color = 0;
915                 commitable = run_status(s->fp, index_file, prefix, 1, s);
916                 s->use_color = saved_color_setting;
917         } else {
918                 unsigned char sha1[20];
919                 const char *parent = "HEAD";
920
921                 if (!active_nr && read_cache() < 0)
922                         die(_("Cannot read index"));
923
924                 if (amend)
925                         parent = "HEAD^1";
926
927                 if (get_sha1(parent, sha1))
928                         commitable = !!active_nr;
929                 else {
930                         /*
931                          * Unless the user did explicitly request a submodule
932                          * ignore mode by passing a command line option we do
933                          * not ignore any changed submodule SHA-1s when
934                          * comparing index and parent, no matter what is
935                          * configured. Otherwise we won't commit any
936                          * submodules which were manually staged, which would
937                          * be really confusing.
938                          */
939                         int diff_flags = DIFF_OPT_OVERRIDE_SUBMODULE_CONFIG;
940                         if (ignore_submodule_arg &&
941                             !strcmp(ignore_submodule_arg, "all"))
942                                 diff_flags |= DIFF_OPT_IGNORE_SUBMODULES;
943                         commitable = index_differs_from(parent, diff_flags);
944                 }
945         }
946         strbuf_release(&committer_ident);
947
948         fclose(s->fp);
949
950         /*
951          * Reject an attempt to record a non-merge empty commit without
952          * explicit --allow-empty. In the cherry-pick case, it may be
953          * empty due to conflict resolution, which the user should okay.
954          */
955         if (!commitable && whence != FROM_MERGE && !allow_empty &&
956             !(amend && is_a_merge(current_head))) {
957                 s->display_comment_prefix = old_display_comment_prefix;
958                 run_status(stdout, index_file, prefix, 0, s);
959                 if (amend)
960                         fputs(_(empty_amend_advice), stderr);
961                 else if (whence == FROM_CHERRY_PICK) {
962                         fputs(_(empty_cherry_pick_advice), stderr);
963                         if (!sequencer_in_use)
964                                 fputs(_(empty_cherry_pick_advice_single), stderr);
965                         else
966                                 fputs(_(empty_cherry_pick_advice_multi), stderr);
967                 }
968                 return 0;
969         }
970
971         /*
972          * Re-read the index as pre-commit hook could have updated it,
973          * and write it out as a tree.  We must do this before we invoke
974          * the editor and after we invoke run_status above.
975          */
976         discard_cache();
977         read_cache_from(index_file);
978         if (update_main_cache_tree(0)) {
979                 error(_("Error building trees"));
980                 return 0;
981         }
982
983         if (run_commit_hook(use_editor, index_file, "prepare-commit-msg",
984                             git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
985                 return 0;
986
987         if (use_editor) {
988                 char index[PATH_MAX];
989                 const char *env[2] = { NULL };
990                 env[0] =  index;
991                 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
992                 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
993                         fprintf(stderr,
994                         _("Please supply the message using either -m or -F option.\n"));
995                         exit(1);
996                 }
997         }
998
999         if (!no_verify &&
1000             run_commit_hook(use_editor, index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
1001                 return 0;
1002         }
1003
1004         return 1;
1005 }
1006
1007 static int rest_is_empty(struct strbuf *sb, int start)
1008 {
1009         int i, eol;
1010         const char *nl;
1011
1012         /* Check if the rest is just whitespace and Signed-of-by's. */
1013         for (i = start; i < sb->len; i++) {
1014                 nl = memchr(sb->buf + i, '\n', sb->len - i);
1015                 if (nl)
1016                         eol = nl - sb->buf;
1017                 else
1018                         eol = sb->len;
1019
1020                 if (strlen(sign_off_header) <= eol - i &&
1021                     starts_with(sb->buf + i, sign_off_header)) {
1022                         i = eol;
1023                         continue;
1024                 }
1025                 while (i < eol)
1026                         if (!isspace(sb->buf[i++]))
1027                                 return 0;
1028         }
1029
1030         return 1;
1031 }
1032
1033 /*
1034  * Find out if the message in the strbuf contains only whitespace and
1035  * Signed-off-by lines.
1036  */
1037 static int message_is_empty(struct strbuf *sb)
1038 {
1039         if (cleanup_mode == CLEANUP_NONE && sb->len)
1040                 return 0;
1041         return rest_is_empty(sb, 0);
1042 }
1043
1044 /*
1045  * See if the user edited the message in the editor or left what
1046  * was in the template intact
1047  */
1048 static int template_untouched(struct strbuf *sb)
1049 {
1050         struct strbuf tmpl = STRBUF_INIT;
1051         const char *start;
1052
1053         if (cleanup_mode == CLEANUP_NONE && sb->len)
1054                 return 0;
1055
1056         if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1057                 return 0;
1058
1059         stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
1060         if (!skip_prefix(sb->buf, tmpl.buf, &start))
1061                 start = sb->buf;
1062         strbuf_release(&tmpl);
1063         return rest_is_empty(sb, start - sb->buf);
1064 }
1065
1066 static const char *find_author_by_nickname(const char *name)
1067 {
1068         struct rev_info revs;
1069         struct commit *commit;
1070         struct strbuf buf = STRBUF_INIT;
1071         struct string_list mailmap = STRING_LIST_INIT_NODUP;
1072         const char *av[20];
1073         int ac = 0;
1074
1075         init_revisions(&revs, NULL);
1076         strbuf_addf(&buf, "--author=%s", name);
1077         av[++ac] = "--all";
1078         av[++ac] = "-i";
1079         av[++ac] = buf.buf;
1080         av[++ac] = NULL;
1081         setup_revisions(ac, av, &revs, NULL);
1082         revs.mailmap = &mailmap;
1083         read_mailmap(revs.mailmap, NULL);
1084
1085         if (prepare_revision_walk(&revs))
1086                 die(_("revision walk setup failed"));
1087         commit = get_revision(&revs);
1088         if (commit) {
1089                 struct pretty_print_context ctx = {0};
1090                 ctx.date_mode = DATE_NORMAL;
1091                 strbuf_release(&buf);
1092                 format_commit_message(commit, "%aN <%aE>", &buf, &ctx);
1093                 clear_mailmap(&mailmap);
1094                 return strbuf_detach(&buf, NULL);
1095         }
1096         die(_("No existing author found with '%s'"), name);
1097 }
1098
1099
1100 static void handle_untracked_files_arg(struct wt_status *s)
1101 {
1102         if (!untracked_files_arg)
1103                 ; /* default already initialized */
1104         else if (!strcmp(untracked_files_arg, "no"))
1105                 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1106         else if (!strcmp(untracked_files_arg, "normal"))
1107                 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1108         else if (!strcmp(untracked_files_arg, "all"))
1109                 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1110         else
1111                 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1112 }
1113
1114 static const char *read_commit_message(const char *name)
1115 {
1116         const char *out_enc;
1117         struct commit *commit;
1118
1119         commit = lookup_commit_reference_by_name(name);
1120         if (!commit)
1121                 die(_("could not lookup commit %s"), name);
1122         out_enc = get_commit_output_encoding();
1123         return logmsg_reencode(commit, NULL, out_enc);
1124 }
1125
1126 /*
1127  * Enumerate what needs to be propagated when --porcelain
1128  * is not in effect here.
1129  */
1130 static struct status_deferred_config {
1131         enum status_format status_format;
1132         int show_branch;
1133 } status_deferred_config = {
1134         STATUS_FORMAT_UNSPECIFIED,
1135         -1 /* unspecified */
1136 };
1137
1138 static void finalize_deferred_config(struct wt_status *s)
1139 {
1140         int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
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 static int parse_and_validate_options(int argc, const char *argv[],
1163                                       const struct option *options,
1164                                       const char * const usage[],
1165                                       const char *prefix,
1166                                       struct commit *current_head,
1167                                       struct wt_status *s)
1168 {
1169         int f = 0;
1170
1171         argc = parse_options(argc, argv, prefix, options, usage, 0);
1172         finalize_deferred_config(s);
1173
1174         if (force_author && !strchr(force_author, '>'))
1175                 force_author = find_author_by_nickname(force_author);
1176
1177         if (force_author && renew_authorship)
1178                 die(_("Using both --reset-author and --author does not make sense"));
1179
1180         if (logfile || have_option_m || use_message || fixup_message)
1181                 use_editor = 0;
1182         if (0 <= edit_flag)
1183                 use_editor = edit_flag;
1184
1185         /* Sanity check options */
1186         if (amend && !current_head)
1187                 die(_("You have nothing to amend."));
1188         if (amend && whence != FROM_COMMIT) {
1189                 if (whence == FROM_MERGE)
1190                         die(_("You are in the middle of a merge -- cannot amend."));
1191                 else if (whence == FROM_CHERRY_PICK)
1192                         die(_("You are in the middle of a cherry-pick -- cannot amend."));
1193         }
1194         if (fixup_message && squash_message)
1195                 die(_("Options --squash and --fixup cannot be used together"));
1196         if (use_message)
1197                 f++;
1198         if (edit_message)
1199                 f++;
1200         if (fixup_message)
1201                 f++;
1202         if (logfile)
1203                 f++;
1204         if (f > 1)
1205                 die(_("Only one of -c/-C/-F/--fixup can be used."));
1206         if (message.len && f > 0)
1207                 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1208         if (f || message.len)
1209                 template_file = NULL;
1210         if (edit_message)
1211                 use_message = edit_message;
1212         if (amend && !use_message && !fixup_message)
1213                 use_message = "HEAD";
1214         if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1215                 die(_("--reset-author can be used only with -C, -c or --amend."));
1216         if (use_message) {
1217                 use_message_buffer = read_commit_message(use_message);
1218                 if (!renew_authorship) {
1219                         author_message = use_message;
1220                         author_message_buffer = use_message_buffer;
1221                 }
1222         }
1223         if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1224                 author_message = "CHERRY_PICK_HEAD";
1225                 author_message_buffer = read_commit_message(author_message);
1226         }
1227
1228         if (patch_interactive)
1229                 interactive = 1;
1230
1231         if (also + only + all + interactive > 1)
1232                 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1233         if (argc == 0 && (also || (only && !amend)))
1234                 die(_("No paths with --include/--only does not make sense."));
1235         if (argc == 0 && only && amend)
1236                 only_include_assumed = _("Clever... amending the last one with dirty index.");
1237         if (argc > 0 && !also && !only)
1238                 only_include_assumed = _("Explicit paths specified without -i or -o; assuming --only paths...");
1239         if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1240                 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1241         else if (!strcmp(cleanup_arg, "verbatim"))
1242                 cleanup_mode = CLEANUP_NONE;
1243         else if (!strcmp(cleanup_arg, "whitespace"))
1244                 cleanup_mode = CLEANUP_SPACE;
1245         else if (!strcmp(cleanup_arg, "strip"))
1246                 cleanup_mode = CLEANUP_ALL;
1247         else if (!strcmp(cleanup_arg, "scissors"))
1248                 cleanup_mode = use_editor ? CLEANUP_SCISSORS : CLEANUP_SPACE;
1249         else
1250                 die(_("Invalid cleanup mode %s"), cleanup_arg);
1251
1252         handle_untracked_files_arg(s);
1253
1254         if (all && argc > 0)
1255                 die(_("Paths with -a does not make sense."));
1256
1257         if (status_format != STATUS_FORMAT_NONE)
1258                 dry_run = 1;
1259
1260         return argc;
1261 }
1262
1263 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1264                           const struct commit *current_head, struct wt_status *s)
1265 {
1266         int commitable;
1267         const char *index_file;
1268
1269         index_file = prepare_index(argc, argv, prefix, current_head, 1);
1270         commitable = run_status(stdout, index_file, prefix, 0, s);
1271         rollback_index_files();
1272
1273         return commitable ? 0 : 1;
1274 }
1275
1276 static int parse_status_slot(const char *slot)
1277 {
1278         if (!strcasecmp(slot, "header"))
1279                 return WT_STATUS_HEADER;
1280         if (!strcasecmp(slot, "branch"))
1281                 return WT_STATUS_ONBRANCH;
1282         if (!strcasecmp(slot, "updated") || !strcasecmp(slot, "added"))
1283                 return WT_STATUS_UPDATED;
1284         if (!strcasecmp(slot, "changed"))
1285                 return WT_STATUS_CHANGED;
1286         if (!strcasecmp(slot, "untracked"))
1287                 return WT_STATUS_UNTRACKED;
1288         if (!strcasecmp(slot, "nobranch"))
1289                 return WT_STATUS_NOBRANCH;
1290         if (!strcasecmp(slot, "unmerged"))
1291                 return WT_STATUS_UNMERGED;
1292         return -1;
1293 }
1294
1295 static int git_status_config(const char *k, const char *v, void *cb)
1296 {
1297         struct wt_status *s = cb;
1298         const char *slot_name;
1299
1300         if (starts_with(k, "column."))
1301                 return git_column_config(k, v, "status", &s->colopts);
1302         if (!strcmp(k, "status.submodulesummary")) {
1303                 int is_bool;
1304                 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1305                 if (is_bool && s->submodule_summary)
1306                         s->submodule_summary = -1;
1307                 return 0;
1308         }
1309         if (!strcmp(k, "status.short")) {
1310                 if (git_config_bool(k, v))
1311                         status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1312                 else
1313                         status_deferred_config.status_format = STATUS_FORMAT_NONE;
1314                 return 0;
1315         }
1316         if (!strcmp(k, "status.branch")) {
1317                 status_deferred_config.show_branch = git_config_bool(k, v);
1318                 return 0;
1319         }
1320         if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1321                 s->use_color = git_config_colorbool(k, v);
1322                 return 0;
1323         }
1324         if (!strcmp(k, "status.displaycommentprefix")) {
1325                 s->display_comment_prefix = git_config_bool(k, v);
1326                 return 0;
1327         }
1328         if (skip_prefix(k, "status.color.", &slot_name) ||
1329             skip_prefix(k, "color.status.", &slot_name)) {
1330                 int slot = parse_status_slot(slot_name);
1331                 if (slot < 0)
1332                         return 0;
1333                 if (!v)
1334                         return config_error_nonbool(k);
1335                 return color_parse(v, s->color_palette[slot]);
1336         }
1337         if (!strcmp(k, "status.relativepaths")) {
1338                 s->relative_paths = git_config_bool(k, v);
1339                 return 0;
1340         }
1341         if (!strcmp(k, "status.showuntrackedfiles")) {
1342                 if (!v)
1343                         return config_error_nonbool(k);
1344                 else if (!strcmp(v, "no"))
1345                         s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1346                 else if (!strcmp(v, "normal"))
1347                         s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1348                 else if (!strcmp(v, "all"))
1349                         s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1350                 else
1351                         return error(_("Invalid untracked files mode '%s'"), v);
1352                 return 0;
1353         }
1354         return git_diff_ui_config(k, v, NULL);
1355 }
1356
1357 int cmd_status(int argc, const char **argv, const char *prefix)
1358 {
1359         static struct wt_status s;
1360         int fd;
1361         unsigned char sha1[20];
1362         static struct option builtin_status_options[] = {
1363                 OPT__VERBOSE(&verbose, N_("be verbose")),
1364                 OPT_SET_INT('s', "short", &status_format,
1365                             N_("show status concisely"), STATUS_FORMAT_SHORT),
1366                 OPT_BOOL('b', "branch", &s.show_branch,
1367                          N_("show branch information")),
1368                 OPT_SET_INT(0, "porcelain", &status_format,
1369                             N_("machine-readable output"),
1370                             STATUS_FORMAT_PORCELAIN),
1371                 OPT_SET_INT(0, "long", &status_format,
1372                             N_("show status in long format (default)"),
1373                             STATUS_FORMAT_LONG),
1374                 OPT_BOOL('z', "null", &s.null_termination,
1375                          N_("terminate entries with NUL")),
1376                 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1377                   N_("mode"),
1378                   N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1379                   PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1380                 OPT_BOOL(0, "ignored", &show_ignored_in_status,
1381                          N_("show ignored files")),
1382                 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1383                   N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1384                   PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1385                 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1386                 OPT_END(),
1387         };
1388
1389         if (argc == 2 && !strcmp(argv[1], "-h"))
1390                 usage_with_options(builtin_status_usage, builtin_status_options);
1391
1392         status_init_config(&s, git_status_config);
1393         argc = parse_options(argc, argv, prefix,
1394                              builtin_status_options,
1395                              builtin_status_usage, 0);
1396         finalize_colopts(&s.colopts, -1);
1397         finalize_deferred_config(&s);
1398
1399         handle_untracked_files_arg(&s);
1400         if (show_ignored_in_status)
1401                 s.show_ignored_files = 1;
1402         parse_pathspec(&s.pathspec, 0,
1403                        PATHSPEC_PREFER_FULL,
1404                        prefix, argv);
1405
1406         read_cache_preload(&s.pathspec);
1407         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, &s.pathspec, NULL, NULL);
1408
1409         fd = hold_locked_index(&index_lock, 0);
1410         if (0 <= fd)
1411                 update_index_if_able(&the_index, &index_lock);
1412
1413         s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1414         s.ignore_submodule_arg = ignore_submodule_arg;
1415         wt_status_collect(&s);
1416
1417         if (s.relative_paths)
1418                 s.prefix = prefix;
1419
1420         switch (status_format) {
1421         case STATUS_FORMAT_SHORT:
1422                 wt_shortstatus_print(&s);
1423                 break;
1424         case STATUS_FORMAT_PORCELAIN:
1425                 wt_porcelain_print(&s);
1426                 break;
1427         case STATUS_FORMAT_UNSPECIFIED:
1428                 die("BUG: finalize_deferred_config() should have been called");
1429                 break;
1430         case STATUS_FORMAT_NONE:
1431         case STATUS_FORMAT_LONG:
1432                 s.verbose = verbose;
1433                 s.ignore_submodule_arg = ignore_submodule_arg;
1434                 wt_status_print(&s);
1435                 break;
1436         }
1437         return 0;
1438 }
1439
1440 static const char *implicit_ident_advice(void)
1441 {
1442         char *user_config = NULL;
1443         char *xdg_config = NULL;
1444         int config_exists;
1445
1446         home_config_paths(&user_config, &xdg_config, "config");
1447         config_exists = file_exists(user_config) || file_exists(xdg_config);
1448         free(user_config);
1449         free(xdg_config);
1450
1451         if (config_exists)
1452                 return _(implicit_ident_advice_config);
1453         else
1454                 return _(implicit_ident_advice_noconfig);
1455
1456 }
1457
1458 static void print_summary(const char *prefix, const unsigned char *sha1,
1459                           int initial_commit)
1460 {
1461         struct rev_info rev;
1462         struct commit *commit;
1463         struct strbuf format = STRBUF_INIT;
1464         unsigned char junk_sha1[20];
1465         const char *head;
1466         struct pretty_print_context pctx = {0};
1467         struct strbuf author_ident = STRBUF_INIT;
1468         struct strbuf committer_ident = STRBUF_INIT;
1469
1470         commit = lookup_commit(sha1);
1471         if (!commit)
1472                 die(_("couldn't look up newly created commit"));
1473         if (parse_commit(commit))
1474                 die(_("could not parse newly created commit"));
1475
1476         strbuf_addstr(&format, "format:%h] %s");
1477
1478         format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1479         format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1480         if (strbuf_cmp(&author_ident, &committer_ident)) {
1481                 strbuf_addstr(&format, "\n Author: ");
1482                 strbuf_addbuf_percentquote(&format, &author_ident);
1483         }
1484         if (author_date_is_interesting()) {
1485                 struct strbuf date = STRBUF_INIT;
1486                 format_commit_message(commit, "%ad", &date, &pctx);
1487                 strbuf_addstr(&format, "\n Date: ");
1488                 strbuf_addbuf_percentquote(&format, &date);
1489                 strbuf_release(&date);
1490         }
1491         if (!committer_ident_sufficiently_given()) {
1492                 strbuf_addstr(&format, "\n Committer: ");
1493                 strbuf_addbuf_percentquote(&format, &committer_ident);
1494                 if (advice_implicit_identity) {
1495                         strbuf_addch(&format, '\n');
1496                         strbuf_addstr(&format, implicit_ident_advice());
1497                 }
1498         }
1499         strbuf_release(&author_ident);
1500         strbuf_release(&committer_ident);
1501
1502         init_revisions(&rev, prefix);
1503         setup_revisions(0, NULL, &rev, NULL);
1504
1505         rev.diff = 1;
1506         rev.diffopt.output_format =
1507                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1508
1509         rev.verbose_header = 1;
1510         rev.show_root_diff = 1;
1511         get_commit_format(format.buf, &rev);
1512         rev.always_show_header = 0;
1513         rev.diffopt.detect_rename = 1;
1514         rev.diffopt.break_opt = 0;
1515         diff_setup_done(&rev.diffopt);
1516
1517         head = resolve_ref_unsafe("HEAD", 0, junk_sha1, NULL);
1518         if (!strcmp(head, "HEAD"))
1519                 head = _("detached HEAD");
1520         else
1521                 skip_prefix(head, "refs/heads/", &head);
1522         printf("[%s%s ", head, initial_commit ? _(" (root-commit)") : "");
1523
1524         if (!log_tree_commit(&rev, commit)) {
1525                 rev.always_show_header = 1;
1526                 rev.use_terminator = 1;
1527                 log_tree_commit(&rev, commit);
1528         }
1529
1530         strbuf_release(&format);
1531 }
1532
1533 static int git_commit_config(const char *k, const char *v, void *cb)
1534 {
1535         struct wt_status *s = cb;
1536         int status;
1537
1538         if (!strcmp(k, "commit.template"))
1539                 return git_config_pathname(&template_file, k, v);
1540         if (!strcmp(k, "commit.status")) {
1541                 include_status = git_config_bool(k, v);
1542                 return 0;
1543         }
1544         if (!strcmp(k, "commit.cleanup"))
1545                 return git_config_string(&cleanup_arg, k, v);
1546         if (!strcmp(k, "commit.gpgsign")) {
1547                 sign_commit = git_config_bool(k, v) ? "" : NULL;
1548                 return 0;
1549         }
1550
1551         status = git_gpg_config(k, v, NULL);
1552         if (status)
1553                 return status;
1554         return git_status_config(k, v, s);
1555 }
1556
1557 int run_commit_hook(int editor_is_used, const char *index_file, const char *name, ...)
1558 {
1559         const char *hook_env[3] =  { NULL };
1560         char index[PATH_MAX];
1561         va_list args;
1562         int ret;
1563
1564         snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
1565         hook_env[0] = index;
1566
1567         /*
1568          * Let the hook know that no editor will be launched.
1569          */
1570         if (!editor_is_used)
1571                 hook_env[1] = "GIT_EDITOR=:";
1572
1573         va_start(args, name);
1574         ret = run_hook_ve(hook_env, name, args);
1575         va_end(args);
1576
1577         return ret;
1578 }
1579
1580 int cmd_commit(int argc, const char **argv, const char *prefix)
1581 {
1582         static struct wt_status s;
1583         static struct option builtin_commit_options[] = {
1584                 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1585                 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1586
1587                 OPT_GROUP(N_("Commit message options")),
1588                 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1589                 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1590                 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1591                 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1592                 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1593                 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1594                 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1595                 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1596                 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1597                 OPT_BOOL('s', "signoff", &signoff, N_("add Signed-off-by:")),
1598                 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1599                 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1600                 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1601                 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1602                 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1603                   N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1604                 /* end commit message options */
1605
1606                 OPT_GROUP(N_("Commit contents options")),
1607                 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1608                 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1609                 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1610                 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1611                 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1612                 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1613                 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1614                 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1615                             STATUS_FORMAT_SHORT),
1616                 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1617                 OPT_SET_INT(0, "porcelain", &status_format,
1618                             N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1619                 OPT_SET_INT(0, "long", &status_format,
1620                             N_("show status in long format (default)"),
1621                             STATUS_FORMAT_LONG),
1622                 OPT_BOOL('z', "null", &s.null_termination,
1623                          N_("terminate entries with NUL")),
1624                 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1625                 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1626                 { 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" },
1627                 /* end commit contents options */
1628
1629                 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1630                                 N_("ok to record an empty change")),
1631                 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1632                                 N_("ok to record a change with an empty message")),
1633
1634                 OPT_END()
1635         };
1636
1637         struct strbuf sb = STRBUF_INIT;
1638         struct strbuf author_ident = STRBUF_INIT;
1639         const char *index_file, *reflog_msg;
1640         char *nl;
1641         unsigned char sha1[20];
1642         struct commit_list *parents = NULL, **pptr = &parents;
1643         struct stat statbuf;
1644         struct commit *current_head = NULL;
1645         struct commit_extra_header *extra = NULL;
1646         struct ref_transaction *transaction;
1647         struct strbuf err = STRBUF_INIT;
1648
1649         if (argc == 2 && !strcmp(argv[1], "-h"))
1650                 usage_with_options(builtin_commit_usage, builtin_commit_options);
1651
1652         status_init_config(&s, git_commit_config);
1653         status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1654         s.colopts = 0;
1655
1656         if (get_sha1("HEAD", sha1))
1657                 current_head = NULL;
1658         else {
1659                 current_head = lookup_commit_or_die(sha1, "HEAD");
1660                 if (parse_commit(current_head))
1661                         die(_("could not parse HEAD commit"));
1662         }
1663         argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1664                                           builtin_commit_usage,
1665                                           prefix, current_head, &s);
1666         if (dry_run)
1667                 return dry_run_commit(argc, argv, prefix, current_head, &s);
1668         index_file = prepare_index(argc, argv, prefix, current_head, 0);
1669
1670         /* Set up everything for writing the commit object.  This includes
1671            running hooks, writing the trees, and interacting with the user.  */
1672         if (!prepare_to_commit(index_file, prefix,
1673                                current_head, &s, &author_ident)) {
1674                 rollback_index_files();
1675                 return 1;
1676         }
1677
1678         /* Determine parents */
1679         reflog_msg = getenv("GIT_REFLOG_ACTION");
1680         if (!current_head) {
1681                 if (!reflog_msg)
1682                         reflog_msg = "commit (initial)";
1683         } else if (amend) {
1684                 struct commit_list *c;
1685
1686                 if (!reflog_msg)
1687                         reflog_msg = "commit (amend)";
1688                 for (c = current_head->parents; c; c = c->next)
1689                         pptr = &commit_list_insert(c->item, pptr)->next;
1690         } else if (whence == FROM_MERGE) {
1691                 struct strbuf m = STRBUF_INIT;
1692                 FILE *fp;
1693                 int allow_fast_forward = 1;
1694                 int reverse_parents = 0;
1695
1696                 if (!reflog_msg)
1697                         reflog_msg = "commit (merge)";
1698                 pptr = &commit_list_insert(current_head, pptr)->next;
1699                 fp = fopen(git_path("MERGE_HEAD"), "r");
1700                 if (fp == NULL)
1701                         die_errno(_("could not open '%s' for reading"),
1702                                   git_path("MERGE_HEAD"));
1703                 while (strbuf_getline(&m, fp, '\n') != EOF) {
1704                         struct commit *parent;
1705
1706                         parent = get_merge_parent(m.buf);
1707                         if (!parent)
1708                                 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1709                         pptr = &commit_list_insert(parent, pptr)->next;
1710                 }
1711                 fclose(fp);
1712                 strbuf_release(&m);
1713                 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1714                         if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1715                                 die_errno(_("could not read MERGE_MODE"));
1716                         if (strstr(sb.buf, "no-ff"))
1717                                 allow_fast_forward = 0;
1718                         if (strstr(sb.buf, "reverse"))
1719                                 reverse_parents = 1;
1720                 }
1721                 if (allow_fast_forward)
1722                         parents = reduce_heads(parents);
1723                 if (reverse_parents)
1724                         parents = reverse_heads(parents);
1725         } else {
1726                 if (!reflog_msg)
1727                         reflog_msg = (whence == FROM_CHERRY_PICK)
1728                                         ? "commit (cherry-pick)"
1729                                         : "commit";
1730                 pptr = &commit_list_insert(current_head, pptr)->next;
1731         }
1732
1733         /* Finally, get the commit message */
1734         strbuf_reset(&sb);
1735         if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1736                 int saved_errno = errno;
1737                 rollback_index_files();
1738                 die(_("could not read commit message: %s"), strerror(saved_errno));
1739         }
1740
1741         if (verbose || /* Truncate the message just before the diff, if any. */
1742             cleanup_mode == CLEANUP_SCISSORS)
1743                 wt_status_truncate_message_at_cut_line(&sb);
1744
1745         if (cleanup_mode != CLEANUP_NONE)
1746                 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1747         if (template_untouched(&sb) && !allow_empty_message) {
1748                 rollback_index_files();
1749                 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1750                 exit(1);
1751         }
1752         if (message_is_empty(&sb) && !allow_empty_message) {
1753                 rollback_index_files();
1754                 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1755                 exit(1);
1756         }
1757
1758         if (amend) {
1759                 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1760                 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1761         } else {
1762                 struct commit_extra_header **tail = &extra;
1763                 append_merge_tag_headers(parents, &tail);
1764         }
1765
1766         if (commit_tree_extended(sb.buf, sb.len, active_cache_tree->sha1,
1767                          parents, sha1, author_ident.buf, sign_commit, extra)) {
1768                 rollback_index_files();
1769                 die(_("failed to write commit object"));
1770         }
1771         strbuf_release(&author_ident);
1772         free_commit_extra_headers(extra);
1773
1774         nl = strchr(sb.buf, '\n');
1775         if (nl)
1776                 strbuf_setlen(&sb, nl + 1 - sb.buf);
1777         else
1778                 strbuf_addch(&sb, '\n');
1779         strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1780         strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1781
1782         transaction = ref_transaction_begin(&err);
1783         if (!transaction ||
1784             ref_transaction_update(transaction, "HEAD", sha1,
1785                                    current_head
1786                                    ? current_head->object.sha1 : NULL,
1787                                    0, !!current_head, sb.buf, &err) ||
1788             ref_transaction_commit(transaction, &err)) {
1789                 rollback_index_files();
1790                 die("%s", err.buf);
1791         }
1792         ref_transaction_free(transaction);
1793
1794         unlink(git_path("CHERRY_PICK_HEAD"));
1795         unlink(git_path("REVERT_HEAD"));
1796         unlink(git_path("MERGE_HEAD"));
1797         unlink(git_path("MERGE_MSG"));
1798         unlink(git_path("MERGE_MODE"));
1799         unlink(git_path("SQUASH_MSG"));
1800
1801         if (commit_index_files())
1802                 die (_("Repository has been updated, but unable to write\n"
1803                      "new_index file. Check that disk is not full and quota is\n"
1804                      "not exceeded, and then \"git reset HEAD\" to recover."));
1805
1806         rerere(0);
1807         run_commit_hook(use_editor, get_index_file(), "post-commit", NULL);
1808         if (amend && !no_post_rewrite) {
1809                 struct rewritten rewrite;
1810                 memset(&rewrite, 0, sizeof(rewrite));
1811                 add_rewritten(&rewrite, current_head->object.sha1, sha1);
1812                 copy_rewrite_notes(&rewrite, "amend", "Notes added by 'git commit --amend'");
1813                 run_rewrite_hook(&rewrite, "amend");
1814         }
1815         if (!quiet)
1816                 print_summary(prefix, sha1, !current_head);
1817
1818         strbuf_release(&err);
1819         return 0;
1820 }