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