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