4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
9 #include "cache-tree.h"
17 #include "wt-status.h"
18 #include "run-command.h"
23 #include "parse-options.h"
24 #include "string-list.h"
26 #include "unpack-trees.h"
28 #include "submodule.h"
29 #include "gpg-interface.h"
31 #include "sequencer.h"
32 #include "notes-utils.h"
36 static const char * const builtin_commit_usage[] = {
37 N_("git commit [options] [--] <pathspec>..."),
41 static const char * const builtin_status_usage[] = {
42 N_("git status [options] [--] <pathspec>..."),
46 static const char implicit_ident_advice[] =
47 N_("Your name and email address were configured automatically based\n"
48 "on your username and hostname. Please check that they are accurate.\n"
49 "You can suppress this message by setting them explicitly:\n"
51 " git config --global user.name \"Your Name\"\n"
52 " git config --global user.email you@example.com\n"
54 "After doing this, you may fix the identity used for this commit with:\n"
56 " git commit --amend --reset-author\n");
58 static const char empty_amend_advice[] =
59 N_("You asked to amend the most recent commit, but doing so would make\n"
60 "it empty. You can repeat your command with --allow-empty, or you can\n"
61 "remove the commit entirely with \"git reset HEAD^\".\n");
63 static const char empty_cherry_pick_advice[] =
64 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
65 "If you wish to commit it anyway, use:\n"
67 " git commit --allow-empty\n"
70 static const char empty_cherry_pick_advice_single[] =
71 N_("Otherwise, please use 'git reset'\n");
73 static const char empty_cherry_pick_advice_multi[] =
74 N_("If you wish to skip this commit, use:\n"
78 "Then \"git cherry-pick --continue\" will resume cherry-picking\n"
79 "the remaining commits.\n");
81 static const char *use_message_buffer;
82 static const char commit_editmsg[] = "COMMIT_EDITMSG";
83 static struct lock_file index_lock; /* real index */
84 static struct lock_file false_lock; /* used only for partial commits */
91 static const char *logfile, *force_author;
92 static const char *template_file;
94 * The _message variables are commit names from which to take
95 * the commit message and/or authorship.
97 static const char *author_message, *author_message_buffer;
98 static char *edit_message, *use_message;
99 static char *fixup_message, *squash_message;
100 static int all, also, interactive, patch_interactive, only, amend, signoff;
101 static int edit_flag = -1; /* unspecified */
102 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
103 static int no_post_rewrite, allow_empty_message;
104 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
105 static char *sign_commit;
108 * The default commit message cleanup mode will remove the lines
109 * beginning with # (shell comments) and leading and trailing
110 * whitespaces (empty lines or containing only whitespaces)
111 * if editor is used, and only the whitespaces if the message
112 * is specified explicitly.
120 static const char *cleanup_arg;
122 static enum commit_whence whence;
123 static int sequencer_in_use;
124 static int use_editor = 1, include_status = 1;
125 static int show_ignored_in_status, have_option_m;
126 static const char *only_include_assumed;
127 static struct strbuf message = STRBUF_INIT;
129 static enum status_format {
130 STATUS_FORMAT_NONE = 0,
133 STATUS_FORMAT_PORCELAIN,
135 STATUS_FORMAT_UNSPECIFIED
136 } status_format = STATUS_FORMAT_UNSPECIFIED;
138 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
140 struct strbuf *buf = opt->value;
143 strbuf_setlen(buf, 0);
147 strbuf_addch(buf, '\n');
148 strbuf_addstr(buf, arg);
149 strbuf_complete_line(buf);
154 static void determine_whence(struct wt_status *s)
156 if (file_exists(git_path("MERGE_HEAD")))
158 else if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
159 whence = FROM_CHERRY_PICK;
160 if (file_exists(git_path("sequencer")))
161 sequencer_in_use = 1;
164 whence = FROM_COMMIT;
169 static void status_init_config(struct wt_status *s, config_fn_t fn)
171 wt_status_prepare(s);
175 s->hints = advice_status_hints; /* must come after git_config() */
178 static void rollback_index_files(void)
180 switch (commit_style) {
182 break; /* nothing to do */
184 rollback_lock_file(&index_lock);
187 rollback_lock_file(&index_lock);
188 rollback_lock_file(&false_lock);
193 static int commit_index_files(void)
197 switch (commit_style) {
199 break; /* nothing to do */
201 err = commit_lock_file(&index_lock);
204 err = commit_lock_file(&index_lock);
205 rollback_lock_file(&false_lock);
213 * Take a union of paths in the index and the named tree (typically, "HEAD"),
214 * and return the paths that match the given pattern in list.
216 static int list_paths(struct string_list *list, const char *with_tree,
217 const char *prefix, const struct pathspec *pattern)
225 m = xcalloc(1, pattern->nr);
228 char *max_prefix = common_prefix(pattern);
229 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
233 for (i = 0; i < active_nr; i++) {
234 const struct cache_entry *ce = active_cache[i];
235 struct string_list_item *item;
237 if (ce->ce_flags & CE_UPDATE)
239 if (!ce_path_match(ce, pattern, m))
241 item = string_list_insert(list, ce->name);
242 if (ce_skip_worktree(ce))
243 item->util = item; /* better a valid pointer than a fake one */
246 return report_path_error(m, pattern, prefix);
249 static void add_remove_files(struct string_list *list)
252 for (i = 0; i < list->nr; i++) {
254 struct string_list_item *p = &(list->items[i]);
256 /* p->util is skip-worktree */
260 if (!lstat(p->string, &st)) {
261 if (add_to_cache(p->string, &st, 0))
262 die(_("updating files failed"));
264 remove_file_from_cache(p->string);
268 static void create_base_index(const struct commit *current_head)
271 struct unpack_trees_options opts;
279 memset(&opts, 0, sizeof(opts));
283 opts.src_index = &the_index;
284 opts.dst_index = &the_index;
286 opts.fn = oneway_merge;
287 tree = parse_tree_indirect(current_head->object.sha1);
289 die(_("failed to unpack HEAD tree object"));
291 init_tree_desc(&t, tree->buffer, tree->size);
292 if (unpack_trees(1, &t, &opts))
293 exit(128); /* We've already reported the error, finish dying */
296 static void refresh_cache_or_die(int refresh_flags)
299 * refresh_flags contains REFRESH_QUIET, so the only errors
300 * are for unmerged entries.
302 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
303 die_resolve_conflict("commit");
306 static char *prepare_index(int argc, const char **argv, const char *prefix,
307 const struct commit *current_head, int is_status)
309 struct string_list partial;
310 struct pathspec pathspec;
311 int refresh_flags = REFRESH_QUIET;
314 refresh_flags |= REFRESH_UNMERGED;
315 parse_pathspec(&pathspec, 0,
316 PATHSPEC_PREFER_FULL,
319 if (read_cache_preload(&pathspec) < 0)
320 die(_("index file corrupt"));
323 char *old_index_env = NULL;
324 hold_locked_index(&index_lock, 1);
326 refresh_cache_or_die(refresh_flags);
328 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
329 die(_("unable to create temporary index"));
331 old_index_env = getenv(INDEX_ENVIRONMENT);
332 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
334 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
335 die(_("interactive add failed"));
337 if (old_index_env && *old_index_env)
338 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
340 unsetenv(INDEX_ENVIRONMENT);
343 read_cache_from(index_lock.filename);
345 commit_style = COMMIT_NORMAL;
346 return index_lock.filename;
350 * Non partial, non as-is commit.
352 * (1) get the real index;
353 * (2) update the_index as necessary;
354 * (3) write the_index out to the real index (still locked);
355 * (4) return the name of the locked index file.
357 * The caller should run hooks on the locked real index, and
358 * (A) if all goes well, commit the real index;
359 * (B) on failure, rollback the real index.
361 if (all || (also && pathspec.nr)) {
362 hold_locked_index(&index_lock, 1);
363 add_files_to_cache(also ? prefix : NULL, &pathspec, 0);
364 refresh_cache_or_die(refresh_flags);
365 update_main_cache_tree(WRITE_TREE_SILENT);
366 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
367 die(_("unable to write new_index file"));
368 commit_style = COMMIT_NORMAL;
369 return index_lock.filename;
375 * (1) return the name of the real index file.
377 * The caller should run hooks on the real index,
378 * and create commit from the_index.
379 * We still need to refresh the index here.
381 if (!only && !pathspec.nr) {
382 hold_locked_index(&index_lock, 1);
383 refresh_cache_or_die(refresh_flags);
384 if (active_cache_changed) {
385 update_main_cache_tree(WRITE_TREE_SILENT);
386 if (write_locked_index(&the_index, &index_lock,
388 die(_("unable to write new_index file"));
390 rollback_lock_file(&index_lock);
392 commit_style = COMMIT_AS_IS;
393 return get_index_file();
399 * (0) find the set of affected paths;
400 * (1) get lock on the real index file;
401 * (2) update the_index with the given paths;
402 * (3) write the_index out to the real index (still locked);
403 * (4) get lock on the false index file;
404 * (5) reset the_index from HEAD;
405 * (6) update the_index the same way as (2);
406 * (7) write the_index out to the false index file;
407 * (8) return the name of the false index file (still locked);
409 * The caller should run hooks on the locked false index, and
410 * create commit from it. Then
411 * (A) if all goes well, commit the real index;
412 * (B) on failure, rollback the real index;
413 * In either case, rollback the false index.
415 commit_style = COMMIT_PARTIAL;
417 if (whence != FROM_COMMIT) {
418 if (whence == FROM_MERGE)
419 die(_("cannot do a partial commit during a merge."));
420 else if (whence == FROM_CHERRY_PICK)
421 die(_("cannot do a partial commit during a cherry-pick."));
424 string_list_init(&partial, 1);
425 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, &pathspec))
429 if (read_cache() < 0)
430 die(_("cannot read the index"));
432 hold_locked_index(&index_lock, 1);
433 add_remove_files(&partial);
434 refresh_cache(REFRESH_QUIET);
435 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
436 die(_("unable to write new_index file"));
438 hold_lock_file_for_update(&false_lock,
439 git_path("next-index-%"PRIuMAX,
440 (uintmax_t) getpid()),
443 create_base_index(current_head);
444 add_remove_files(&partial);
445 refresh_cache(REFRESH_QUIET);
447 if (write_locked_index(&the_index, &false_lock, CLOSE_LOCK))
448 die(_("unable to write temporary index file"));
451 read_cache_from(false_lock.filename);
453 return false_lock.filename;
456 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
459 unsigned char sha1[20];
461 if (s->relative_paths)
466 s->reference = "HEAD^1";
468 s->verbose = verbose;
469 s->index_file = index_file;
472 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
474 wt_status_collect(s);
476 switch (status_format) {
477 case STATUS_FORMAT_SHORT:
478 wt_shortstatus_print(s);
480 case STATUS_FORMAT_PORCELAIN:
481 wt_porcelain_print(s);
483 case STATUS_FORMAT_UNSPECIFIED:
484 die("BUG: finalize_deferred_config() should have been called");
486 case STATUS_FORMAT_NONE:
487 case STATUS_FORMAT_LONG:
492 return s->commitable;
495 static int is_a_merge(const struct commit *current_head)
497 return !!(current_head->parents && current_head->parents->next);
500 static void export_one(const char *var, const char *s, const char *e, int hack)
502 struct strbuf buf = STRBUF_INIT;
504 strbuf_addch(&buf, hack);
505 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
506 setenv(var, buf.buf, 1);
507 strbuf_release(&buf);
510 static int sane_ident_split(struct ident_split *person)
512 if (!person->name_begin || !person->name_end ||
513 person->name_begin == person->name_end)
514 return 0; /* no human readable name */
515 if (!person->mail_begin || !person->mail_end ||
516 person->mail_begin == person->mail_end)
517 return 0; /* no usable mail */
518 if (!person->date_begin || !person->date_end ||
519 !person->tz_begin || !person->tz_end)
524 static int parse_force_date(const char *in, char *out, int len)
531 if (parse_date(in, out, len) < 0) {
533 unsigned long t = approxidate_careful(in, &errors);
536 snprintf(out, len, "%lu", t);
542 static void determine_author_info(struct strbuf *author_ident)
544 char *name, *email, *date;
545 struct ident_split author;
548 name = getenv("GIT_AUTHOR_NAME");
549 email = getenv("GIT_AUTHOR_EMAIL");
550 date = getenv("GIT_AUTHOR_DATE");
552 if (author_message) {
553 const char *a, *lb, *rb, *eol;
556 a = strstr(author_message_buffer, "\nauthor ");
558 die(_("invalid commit: %s"), author_message);
560 lb = strchrnul(a + strlen("\nauthor "), '<');
561 rb = strchrnul(lb, '>');
562 eol = strchrnul(rb, '\n');
563 if (!*lb || !*rb || !*eol)
564 die(_("invalid commit: %s"), author_message);
566 if (lb == a + strlen("\nauthor "))
567 /* \nauthor <foo@example.com> */
568 name = xcalloc(1, 1);
570 name = xmemdupz(a + strlen("\nauthor "),
572 (a + strlen("\nauthor "))));
573 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
574 len = eol - (rb + strlen("> "));
575 date = xmalloc(len + 2);
577 memcpy(date + 1, rb + strlen("> "), len);
578 date[len + 1] = '\0';
582 const char *lb = strstr(force_author, " <");
583 const char *rb = strchr(force_author, '>');
586 die(_("malformed --author parameter"));
587 name = xstrndup(force_author, lb - force_author);
588 email = xstrndup(lb + 2, rb - (lb + 2));
592 if (parse_force_date(force_date, date_buf, sizeof(date_buf)))
593 die(_("invalid date format: %s"), force_date);
597 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
598 if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
599 sane_ident_split(&author)) {
600 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
601 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
602 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
606 static void split_ident_or_die(struct ident_split *id, const struct strbuf *buf)
608 if (split_ident_line(id, buf->buf, buf->len) ||
609 !sane_ident_split(id))
610 die(_("Malformed ident string: '%s'"), buf->buf);
613 static int author_date_is_interesting(void)
615 return author_message || force_date;
618 static void adjust_comment_line_char(const struct strbuf *sb)
620 char candidates[] = "#;@!$%^&|:";
624 comment_line_char = candidates[0];
625 if (!memchr(sb->buf, comment_line_char, sb->len))
629 candidate = strchr(candidates, *p);
632 for (p = sb->buf; *p; p++) {
633 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
634 candidate = strchr(candidates, p[1]);
640 for (p = candidates; *p == ' '; p++)
643 die(_("unable to select a comment character that is not used\n"
644 "in the current commit message"));
645 comment_line_char = *p;
648 static int prepare_to_commit(const char *index_file, const char *prefix,
649 struct commit *current_head,
651 struct strbuf *author_ident)
654 struct strbuf committer_ident = STRBUF_INIT;
656 struct strbuf sb = STRBUF_INIT;
657 const char *hook_arg1 = NULL;
658 const char *hook_arg2 = NULL;
659 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
660 int old_display_comment_prefix;
662 /* This checks and barfs if author is badly specified */
663 determine_author_info(author_ident);
665 if (!no_verify && run_commit_hook(use_editor, index_file, "pre-commit", NULL))
668 if (squash_message) {
670 * Insert the proper subject line before other commit
671 * message options add their content.
673 if (use_message && !strcmp(use_message, squash_message))
674 strbuf_addstr(&sb, "squash! ");
676 struct pretty_print_context ctx = {0};
678 c = lookup_commit_reference_by_name(squash_message);
680 die(_("could not lookup commit %s"), squash_message);
681 ctx.output_encoding = get_commit_output_encoding();
682 format_commit_message(c, "squash! %s\n\n", &sb,
688 strbuf_addbuf(&sb, &message);
689 hook_arg1 = "message";
690 } else if (logfile && !strcmp(logfile, "-")) {
692 fprintf(stderr, _("(reading log message from standard input)\n"));
693 if (strbuf_read(&sb, 0, 0) < 0)
694 die_errno(_("could not read log from standard input"));
695 hook_arg1 = "message";
696 } else if (logfile) {
697 if (strbuf_read_file(&sb, logfile, 0) < 0)
698 die_errno(_("could not read log file '%s'"),
700 hook_arg1 = "message";
701 } else if (use_message) {
703 buffer = strstr(use_message_buffer, "\n\n");
705 strbuf_addstr(&sb, buffer + 2);
706 hook_arg1 = "commit";
707 hook_arg2 = use_message;
708 } else if (fixup_message) {
709 struct pretty_print_context ctx = {0};
710 struct commit *commit;
711 commit = lookup_commit_reference_by_name(fixup_message);
713 die(_("could not lookup commit %s"), fixup_message);
714 ctx.output_encoding = get_commit_output_encoding();
715 format_commit_message(commit, "fixup! %s\n\n",
717 hook_arg1 = "message";
718 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
719 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
720 die_errno(_("could not read MERGE_MSG"));
722 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
723 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
724 die_errno(_("could not read SQUASH_MSG"));
725 hook_arg1 = "squash";
726 } else if (template_file) {
727 if (strbuf_read_file(&sb, template_file, 0) < 0)
728 die_errno(_("could not read '%s'"), template_file);
729 hook_arg1 = "template";
730 clean_message_contents = 0;
734 * The remaining cases don't modify the template message, but
735 * just set the argument(s) to the prepare-commit-msg hook.
737 else if (whence == FROM_MERGE)
739 else if (whence == FROM_CHERRY_PICK) {
740 hook_arg1 = "commit";
741 hook_arg2 = "CHERRY_PICK_HEAD";
744 if (squash_message) {
746 * If squash_commit was used for the commit subject,
747 * then we're possibly hijacking other commit log options.
748 * Reset the hook args to tell the real story.
750 hook_arg1 = "message";
754 s->fp = fopen(git_path(commit_editmsg), "w");
756 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
758 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
759 old_display_comment_prefix = s->display_comment_prefix;
760 s->display_comment_prefix = 1;
763 * Most hints are counter-productive when the commit has
768 if (clean_message_contents)
773 * See if we have a Conflicts: block at the end. If yes, count
774 * its size, so we can ignore it.
776 int ignore_footer = 0;
777 int i, eol, previous = 0;
780 for (i = 0; i < sb.len; i++) {
781 nl = memchr(sb.buf + i, '\n', sb.len - i);
786 if (starts_with(sb.buf + previous, "\nConflicts:\n")) {
787 ignore_footer = sb.len - previous;
795 append_signoff(&sb, ignore_footer, 0);
798 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
799 die_errno(_("could not write commit template"));
801 if (auto_comment_line_char)
802 adjust_comment_line_char(&sb);
805 /* This checks if committer ident is explicitly given */
806 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
807 if (use_editor && include_status) {
809 int saved_color_setting;
810 struct ident_split ci, ai;
812 if (whence != FROM_COMMIT) {
813 if (cleanup_mode == CLEANUP_SCISSORS)
814 wt_status_add_cut_line(s->fp);
815 status_printf_ln(s, GIT_COLOR_NORMAL,
818 "It looks like you may be committing a merge.\n"
819 "If this is not correct, please remove the file\n"
823 "It looks like you may be committing a cherry-pick.\n"
824 "If this is not correct, please remove the file\n"
827 git_path(whence == FROM_MERGE
829 : "CHERRY_PICK_HEAD"));
832 fprintf(s->fp, "\n");
833 if (cleanup_mode == CLEANUP_ALL)
834 status_printf(s, GIT_COLOR_NORMAL,
835 _("Please enter the commit message for your changes."
836 " Lines starting\nwith '%c' will be ignored, and an empty"
837 " message aborts the commit.\n"), comment_line_char);
838 else if (cleanup_mode == CLEANUP_SCISSORS && whence == FROM_COMMIT)
839 wt_status_add_cut_line(s->fp);
840 else /* CLEANUP_SPACE, that is. */
841 status_printf(s, GIT_COLOR_NORMAL,
842 _("Please enter the commit message for your changes."
844 "with '%c' will be kept; you may remove them"
845 " yourself if you want to.\n"
846 "An empty message aborts the commit.\n"), comment_line_char);
847 if (only_include_assumed)
848 status_printf_ln(s, GIT_COLOR_NORMAL,
849 "%s", only_include_assumed);
851 split_ident_or_die(&ai, author_ident);
852 split_ident_or_die(&ci, &committer_ident);
854 if (ident_cmp(&ai, &ci))
855 status_printf_ln(s, GIT_COLOR_NORMAL,
857 "Author: %.*s <%.*s>"),
858 ident_shown++ ? "" : "\n",
859 (int)(ai.name_end - ai.name_begin), ai.name_begin,
860 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
862 if (author_date_is_interesting())
863 status_printf_ln(s, GIT_COLOR_NORMAL,
866 ident_shown++ ? "" : "\n",
867 show_ident_date(&ai, DATE_NORMAL));
869 if (!committer_ident_sufficiently_given())
870 status_printf_ln(s, GIT_COLOR_NORMAL,
872 "Committer: %.*s <%.*s>"),
873 ident_shown++ ? "" : "\n",
874 (int)(ci.name_end - ci.name_begin), ci.name_begin,
875 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
878 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", "");
880 saved_color_setting = s->use_color;
882 commitable = run_status(s->fp, index_file, prefix, 1, s);
883 s->use_color = saved_color_setting;
885 unsigned char sha1[20];
886 const char *parent = "HEAD";
888 if (!active_nr && read_cache() < 0)
889 die(_("Cannot read index"));
894 if (get_sha1(parent, sha1))
895 commitable = !!active_nr;
898 * Unless the user did explicitly request a submodule
899 * ignore mode by passing a command line option we do
900 * not ignore any changed submodule SHA-1s when
901 * comparing index and parent, no matter what is
902 * configured. Otherwise we won't commit any
903 * submodules which were manually staged, which would
904 * be really confusing.
906 int diff_flags = DIFF_OPT_OVERRIDE_SUBMODULE_CONFIG;
907 if (ignore_submodule_arg &&
908 !strcmp(ignore_submodule_arg, "all"))
909 diff_flags |= DIFF_OPT_IGNORE_SUBMODULES;
910 commitable = index_differs_from(parent, diff_flags);
913 strbuf_release(&committer_ident);
918 * Reject an attempt to record a non-merge empty commit without
919 * explicit --allow-empty. In the cherry-pick case, it may be
920 * empty due to conflict resolution, which the user should okay.
922 if (!commitable && whence != FROM_MERGE && !allow_empty &&
923 !(amend && is_a_merge(current_head))) {
924 s->display_comment_prefix = old_display_comment_prefix;
925 run_status(stdout, index_file, prefix, 0, s);
927 fputs(_(empty_amend_advice), stderr);
928 else if (whence == FROM_CHERRY_PICK) {
929 fputs(_(empty_cherry_pick_advice), stderr);
930 if (!sequencer_in_use)
931 fputs(_(empty_cherry_pick_advice_single), stderr);
933 fputs(_(empty_cherry_pick_advice_multi), stderr);
939 * Re-read the index as pre-commit hook could have updated it,
940 * and write it out as a tree. We must do this before we invoke
941 * the editor and after we invoke run_status above.
944 read_cache_from(index_file);
945 if (update_main_cache_tree(0)) {
946 error(_("Error building trees"));
950 if (run_commit_hook(use_editor, index_file, "prepare-commit-msg",
951 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
955 char index[PATH_MAX];
956 const char *env[2] = { NULL };
958 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
959 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
961 _("Please supply the message using either -m or -F option.\n"));
967 run_commit_hook(use_editor, index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
974 static int rest_is_empty(struct strbuf *sb, int start)
979 /* Check if the rest is just whitespace and Signed-of-by's. */
980 for (i = start; i < sb->len; i++) {
981 nl = memchr(sb->buf + i, '\n', sb->len - i);
987 if (strlen(sign_off_header) <= eol - i &&
988 starts_with(sb->buf + i, sign_off_header)) {
993 if (!isspace(sb->buf[i++]))
1001 * Find out if the message in the strbuf contains only whitespace and
1002 * Signed-off-by lines.
1004 static int message_is_empty(struct strbuf *sb)
1006 if (cleanup_mode == CLEANUP_NONE && sb->len)
1008 return rest_is_empty(sb, 0);
1012 * See if the user edited the message in the editor or left what
1013 * was in the template intact
1015 static int template_untouched(struct strbuf *sb)
1017 struct strbuf tmpl = STRBUF_INIT;
1020 if (cleanup_mode == CLEANUP_NONE && sb->len)
1023 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1026 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
1027 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1029 strbuf_release(&tmpl);
1030 return rest_is_empty(sb, start - sb->buf);
1033 static const char *find_author_by_nickname(const char *name)
1035 struct rev_info revs;
1036 struct commit *commit;
1037 struct strbuf buf = STRBUF_INIT;
1038 struct string_list mailmap = STRING_LIST_INIT_NODUP;
1042 init_revisions(&revs, NULL);
1043 strbuf_addf(&buf, "--author=%s", name);
1048 setup_revisions(ac, av, &revs, NULL);
1049 revs.mailmap = &mailmap;
1050 read_mailmap(revs.mailmap, NULL);
1052 prepare_revision_walk(&revs);
1053 commit = get_revision(&revs);
1055 struct pretty_print_context ctx = {0};
1056 ctx.date_mode = DATE_NORMAL;
1057 strbuf_release(&buf);
1058 format_commit_message(commit, "%aN <%aE>", &buf, &ctx);
1059 clear_mailmap(&mailmap);
1060 return strbuf_detach(&buf, NULL);
1062 die(_("No existing author found with '%s'"), name);
1066 static void handle_untracked_files_arg(struct wt_status *s)
1068 if (!untracked_files_arg)
1069 ; /* default already initialized */
1070 else if (!strcmp(untracked_files_arg, "no"))
1071 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1072 else if (!strcmp(untracked_files_arg, "normal"))
1073 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1074 else if (!strcmp(untracked_files_arg, "all"))
1075 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1077 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1080 static const char *read_commit_message(const char *name)
1082 const char *out_enc;
1083 struct commit *commit;
1085 commit = lookup_commit_reference_by_name(name);
1087 die(_("could not lookup commit %s"), name);
1088 out_enc = get_commit_output_encoding();
1089 return logmsg_reencode(commit, NULL, out_enc);
1093 * Enumerate what needs to be propagated when --porcelain
1094 * is not in effect here.
1096 static struct status_deferred_config {
1097 enum status_format status_format;
1099 } status_deferred_config = {
1100 STATUS_FORMAT_UNSPECIFIED,
1101 -1 /* unspecified */
1104 static void finalize_deferred_config(struct wt_status *s)
1106 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1107 !s->null_termination);
1109 if (s->null_termination) {
1110 if (status_format == STATUS_FORMAT_NONE ||
1111 status_format == STATUS_FORMAT_UNSPECIFIED)
1112 status_format = STATUS_FORMAT_PORCELAIN;
1113 else if (status_format == STATUS_FORMAT_LONG)
1114 die(_("--long and -z are incompatible"));
1117 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1118 status_format = status_deferred_config.status_format;
1119 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1120 status_format = STATUS_FORMAT_NONE;
1122 if (use_deferred_config && s->show_branch < 0)
1123 s->show_branch = status_deferred_config.show_branch;
1124 if (s->show_branch < 0)
1128 static int parse_and_validate_options(int argc, const char *argv[],
1129 const struct option *options,
1130 const char * const usage[],
1132 struct commit *current_head,
1133 struct wt_status *s)
1137 argc = parse_options(argc, argv, prefix, options, usage, 0);
1138 finalize_deferred_config(s);
1140 if (force_author && !strchr(force_author, '>'))
1141 force_author = find_author_by_nickname(force_author);
1143 if (force_author && renew_authorship)
1144 die(_("Using both --reset-author and --author does not make sense"));
1146 if (logfile || have_option_m || use_message || fixup_message)
1149 use_editor = edit_flag;
1151 /* Sanity check options */
1152 if (amend && !current_head)
1153 die(_("You have nothing to amend."));
1154 if (amend && whence != FROM_COMMIT) {
1155 if (whence == FROM_MERGE)
1156 die(_("You are in the middle of a merge -- cannot amend."));
1157 else if (whence == FROM_CHERRY_PICK)
1158 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1160 if (fixup_message && squash_message)
1161 die(_("Options --squash and --fixup cannot be used together"));
1171 die(_("Only one of -c/-C/-F/--fixup can be used."));
1172 if (message.len && f > 0)
1173 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1174 if (f || message.len)
1175 template_file = NULL;
1177 use_message = edit_message;
1178 if (amend && !use_message && !fixup_message)
1179 use_message = "HEAD";
1180 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1181 die(_("--reset-author can be used only with -C, -c or --amend."));
1183 use_message_buffer = read_commit_message(use_message);
1184 if (!renew_authorship) {
1185 author_message = use_message;
1186 author_message_buffer = use_message_buffer;
1189 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1190 author_message = "CHERRY_PICK_HEAD";
1191 author_message_buffer = read_commit_message(author_message);
1194 if (patch_interactive)
1197 if (also + only + all + interactive > 1)
1198 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1199 if (argc == 0 && (also || (only && !amend)))
1200 die(_("No paths with --include/--only does not make sense."));
1201 if (argc == 0 && only && amend)
1202 only_include_assumed = _("Clever... amending the last one with dirty index.");
1203 if (argc > 0 && !also && !only)
1204 only_include_assumed = _("Explicit paths specified without -i or -o; assuming --only paths...");
1205 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1206 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1207 else if (!strcmp(cleanup_arg, "verbatim"))
1208 cleanup_mode = CLEANUP_NONE;
1209 else if (!strcmp(cleanup_arg, "whitespace"))
1210 cleanup_mode = CLEANUP_SPACE;
1211 else if (!strcmp(cleanup_arg, "strip"))
1212 cleanup_mode = CLEANUP_ALL;
1213 else if (!strcmp(cleanup_arg, "scissors"))
1214 cleanup_mode = use_editor ? CLEANUP_SCISSORS : CLEANUP_SPACE;
1216 die(_("Invalid cleanup mode %s"), cleanup_arg);
1218 handle_untracked_files_arg(s);
1220 if (all && argc > 0)
1221 die(_("Paths with -a does not make sense."));
1223 if (status_format != STATUS_FORMAT_NONE)
1229 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1230 const struct commit *current_head, struct wt_status *s)
1233 const char *index_file;
1235 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1236 commitable = run_status(stdout, index_file, prefix, 0, s);
1237 rollback_index_files();
1239 return commitable ? 0 : 1;
1242 static int parse_status_slot(const char *var, int offset)
1244 if (!strcasecmp(var+offset, "header"))
1245 return WT_STATUS_HEADER;
1246 if (!strcasecmp(var+offset, "branch"))
1247 return WT_STATUS_ONBRANCH;
1248 if (!strcasecmp(var+offset, "updated")
1249 || !strcasecmp(var+offset, "added"))
1250 return WT_STATUS_UPDATED;
1251 if (!strcasecmp(var+offset, "changed"))
1252 return WT_STATUS_CHANGED;
1253 if (!strcasecmp(var+offset, "untracked"))
1254 return WT_STATUS_UNTRACKED;
1255 if (!strcasecmp(var+offset, "nobranch"))
1256 return WT_STATUS_NOBRANCH;
1257 if (!strcasecmp(var+offset, "unmerged"))
1258 return WT_STATUS_UNMERGED;
1262 static int git_status_config(const char *k, const char *v, void *cb)
1264 struct wt_status *s = cb;
1266 if (starts_with(k, "column."))
1267 return git_column_config(k, v, "status", &s->colopts);
1268 if (!strcmp(k, "status.submodulesummary")) {
1270 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1271 if (is_bool && s->submodule_summary)
1272 s->submodule_summary = -1;
1275 if (!strcmp(k, "status.short")) {
1276 if (git_config_bool(k, v))
1277 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1279 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1282 if (!strcmp(k, "status.branch")) {
1283 status_deferred_config.show_branch = git_config_bool(k, v);
1286 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1287 s->use_color = git_config_colorbool(k, v);
1290 if (!strcmp(k, "status.displaycommentprefix")) {
1291 s->display_comment_prefix = git_config_bool(k, v);
1294 if (starts_with(k, "status.color.") || starts_with(k, "color.status.")) {
1295 int slot = parse_status_slot(k, 13);
1299 return config_error_nonbool(k);
1300 color_parse(v, k, s->color_palette[slot]);
1303 if (!strcmp(k, "status.relativepaths")) {
1304 s->relative_paths = git_config_bool(k, v);
1307 if (!strcmp(k, "status.showuntrackedfiles")) {
1309 return config_error_nonbool(k);
1310 else if (!strcmp(v, "no"))
1311 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1312 else if (!strcmp(v, "normal"))
1313 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1314 else if (!strcmp(v, "all"))
1315 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1317 return error(_("Invalid untracked files mode '%s'"), v);
1320 return git_diff_ui_config(k, v, NULL);
1323 int cmd_status(int argc, const char **argv, const char *prefix)
1325 static struct wt_status s;
1327 unsigned char sha1[20];
1328 static struct option builtin_status_options[] = {
1329 OPT__VERBOSE(&verbose, N_("be verbose")),
1330 OPT_SET_INT('s', "short", &status_format,
1331 N_("show status concisely"), STATUS_FORMAT_SHORT),
1332 OPT_BOOL('b', "branch", &s.show_branch,
1333 N_("show branch information")),
1334 OPT_SET_INT(0, "porcelain", &status_format,
1335 N_("machine-readable output"),
1336 STATUS_FORMAT_PORCELAIN),
1337 OPT_SET_INT(0, "long", &status_format,
1338 N_("show status in long format (default)"),
1339 STATUS_FORMAT_LONG),
1340 OPT_BOOL('z', "null", &s.null_termination,
1341 N_("terminate entries with NUL")),
1342 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1344 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1345 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1346 OPT_BOOL(0, "ignored", &show_ignored_in_status,
1347 N_("show ignored files")),
1348 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1349 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1350 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1351 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1355 if (argc == 2 && !strcmp(argv[1], "-h"))
1356 usage_with_options(builtin_status_usage, builtin_status_options);
1358 status_init_config(&s, git_status_config);
1359 argc = parse_options(argc, argv, prefix,
1360 builtin_status_options,
1361 builtin_status_usage, 0);
1362 finalize_colopts(&s.colopts, -1);
1363 finalize_deferred_config(&s);
1365 handle_untracked_files_arg(&s);
1366 if (show_ignored_in_status)
1367 s.show_ignored_files = 1;
1368 parse_pathspec(&s.pathspec, 0,
1369 PATHSPEC_PREFER_FULL,
1372 read_cache_preload(&s.pathspec);
1373 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, &s.pathspec, NULL, NULL);
1375 fd = hold_locked_index(&index_lock, 0);
1377 update_index_if_able(&the_index, &index_lock);
1379 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1380 s.ignore_submodule_arg = ignore_submodule_arg;
1381 wt_status_collect(&s);
1383 if (s.relative_paths)
1386 switch (status_format) {
1387 case STATUS_FORMAT_SHORT:
1388 wt_shortstatus_print(&s);
1390 case STATUS_FORMAT_PORCELAIN:
1391 wt_porcelain_print(&s);
1393 case STATUS_FORMAT_UNSPECIFIED:
1394 die("BUG: finalize_deferred_config() should have been called");
1396 case STATUS_FORMAT_NONE:
1397 case STATUS_FORMAT_LONG:
1398 s.verbose = verbose;
1399 s.ignore_submodule_arg = ignore_submodule_arg;
1400 wt_status_print(&s);
1406 static void print_summary(const char *prefix, const unsigned char *sha1,
1409 struct rev_info rev;
1410 struct commit *commit;
1411 struct strbuf format = STRBUF_INIT;
1412 unsigned char junk_sha1[20];
1414 struct pretty_print_context pctx = {0};
1415 struct strbuf author_ident = STRBUF_INIT;
1416 struct strbuf committer_ident = STRBUF_INIT;
1418 commit = lookup_commit(sha1);
1420 die(_("couldn't look up newly created commit"));
1421 if (parse_commit(commit))
1422 die(_("could not parse newly created commit"));
1424 strbuf_addstr(&format, "format:%h] %s");
1426 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1427 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1428 if (strbuf_cmp(&author_ident, &committer_ident)) {
1429 strbuf_addstr(&format, "\n Author: ");
1430 strbuf_addbuf_percentquote(&format, &author_ident);
1432 if (author_date_is_interesting()) {
1433 struct strbuf date = STRBUF_INIT;
1434 format_commit_message(commit, "%ad", &date, &pctx);
1435 strbuf_addstr(&format, "\n Date: ");
1436 strbuf_addbuf_percentquote(&format, &date);
1437 strbuf_release(&date);
1439 if (!committer_ident_sufficiently_given()) {
1440 strbuf_addstr(&format, "\n Committer: ");
1441 strbuf_addbuf_percentquote(&format, &committer_ident);
1442 if (advice_implicit_identity) {
1443 strbuf_addch(&format, '\n');
1444 strbuf_addstr(&format, _(implicit_ident_advice));
1447 strbuf_release(&author_ident);
1448 strbuf_release(&committer_ident);
1450 init_revisions(&rev, prefix);
1451 setup_revisions(0, NULL, &rev, NULL);
1454 rev.diffopt.output_format =
1455 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1457 rev.verbose_header = 1;
1458 rev.show_root_diff = 1;
1459 get_commit_format(format.buf, &rev);
1460 rev.always_show_header = 0;
1461 rev.diffopt.detect_rename = 1;
1462 rev.diffopt.break_opt = 0;
1463 diff_setup_done(&rev.diffopt);
1465 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1467 starts_with(head, "refs/heads/") ?
1469 !strcmp(head, "HEAD") ?
1470 _("detached HEAD") :
1472 initial_commit ? _(" (root-commit)") : "");
1474 if (!log_tree_commit(&rev, commit)) {
1475 rev.always_show_header = 1;
1476 rev.use_terminator = 1;
1477 log_tree_commit(&rev, commit);
1480 strbuf_release(&format);
1483 static int git_commit_config(const char *k, const char *v, void *cb)
1485 struct wt_status *s = cb;
1488 if (!strcmp(k, "commit.template"))
1489 return git_config_pathname(&template_file, k, v);
1490 if (!strcmp(k, "commit.status")) {
1491 include_status = git_config_bool(k, v);
1494 if (!strcmp(k, "commit.cleanup"))
1495 return git_config_string(&cleanup_arg, k, v);
1496 if (!strcmp(k, "commit.gpgsign")) {
1497 sign_commit = git_config_bool(k, v) ? "" : NULL;
1501 status = git_gpg_config(k, v, NULL);
1504 return git_status_config(k, v, s);
1507 int run_commit_hook(int editor_is_used, const char *index_file, const char *name, ...)
1509 const char *hook_env[3] = { NULL };
1510 char index[PATH_MAX];
1514 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
1515 hook_env[0] = index;
1518 * Let the hook know that no editor will be launched.
1520 if (!editor_is_used)
1521 hook_env[1] = "GIT_EDITOR=:";
1523 va_start(args, name);
1524 ret = run_hook_ve(hook_env, name, args);
1530 int cmd_commit(int argc, const char **argv, const char *prefix)
1532 static struct wt_status s;
1533 static struct option builtin_commit_options[] = {
1534 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1535 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1537 OPT_GROUP(N_("Commit message options")),
1538 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1539 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1540 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1541 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1542 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1543 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1544 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1545 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1546 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1547 OPT_BOOL('s', "signoff", &signoff, N_("add Signed-off-by:")),
1548 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1549 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1550 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1551 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1552 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1553 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1554 /* end commit message options */
1556 OPT_GROUP(N_("Commit contents options")),
1557 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1558 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1559 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1560 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1561 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1562 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1563 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1564 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1565 STATUS_FORMAT_SHORT),
1566 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1567 OPT_SET_INT(0, "porcelain", &status_format,
1568 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1569 OPT_SET_INT(0, "long", &status_format,
1570 N_("show status in long format (default)"),
1571 STATUS_FORMAT_LONG),
1572 OPT_BOOL('z', "null", &s.null_termination,
1573 N_("terminate entries with NUL")),
1574 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1575 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1576 { 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" },
1577 /* end commit contents options */
1579 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1580 N_("ok to record an empty change")),
1581 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1582 N_("ok to record a change with an empty message")),
1587 struct strbuf sb = STRBUF_INIT;
1588 struct strbuf author_ident = STRBUF_INIT;
1589 const char *index_file, *reflog_msg;
1591 unsigned char sha1[20];
1592 struct ref_lock *ref_lock;
1593 struct commit_list *parents = NULL, **pptr = &parents;
1594 struct stat statbuf;
1595 struct commit *current_head = NULL;
1596 struct commit_extra_header *extra = NULL;
1598 if (argc == 2 && !strcmp(argv[1], "-h"))
1599 usage_with_options(builtin_commit_usage, builtin_commit_options);
1601 status_init_config(&s, git_commit_config);
1602 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1605 if (get_sha1("HEAD", sha1))
1606 current_head = NULL;
1608 current_head = lookup_commit_or_die(sha1, "HEAD");
1609 if (parse_commit(current_head))
1610 die(_("could not parse HEAD commit"));
1612 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1613 builtin_commit_usage,
1614 prefix, current_head, &s);
1616 return dry_run_commit(argc, argv, prefix, current_head, &s);
1617 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1619 /* Set up everything for writing the commit object. This includes
1620 running hooks, writing the trees, and interacting with the user. */
1621 if (!prepare_to_commit(index_file, prefix,
1622 current_head, &s, &author_ident)) {
1623 rollback_index_files();
1627 /* Determine parents */
1628 reflog_msg = getenv("GIT_REFLOG_ACTION");
1629 if (!current_head) {
1631 reflog_msg = "commit (initial)";
1633 struct commit_list *c;
1636 reflog_msg = "commit (amend)";
1637 for (c = current_head->parents; c; c = c->next)
1638 pptr = &commit_list_insert(c->item, pptr)->next;
1639 } else if (whence == FROM_MERGE) {
1640 struct strbuf m = STRBUF_INIT;
1642 int allow_fast_forward = 1;
1643 int reverse_parents = 0;
1646 reflog_msg = "commit (merge)";
1647 pptr = &commit_list_insert(current_head, pptr)->next;
1648 fp = fopen(git_path("MERGE_HEAD"), "r");
1650 die_errno(_("could not open '%s' for reading"),
1651 git_path("MERGE_HEAD"));
1652 while (strbuf_getline(&m, fp, '\n') != EOF) {
1653 struct commit *parent;
1655 parent = get_merge_parent(m.buf);
1657 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1658 pptr = &commit_list_insert(parent, pptr)->next;
1662 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1663 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1664 die_errno(_("could not read MERGE_MODE"));
1665 if (strstr(sb.buf, "no-ff"))
1666 allow_fast_forward = 0;
1667 if (strstr(sb.buf, "reverse"))
1668 reverse_parents = 1;
1670 if (allow_fast_forward)
1671 parents = reduce_heads(parents);
1672 if (reverse_parents)
1673 parents = reverse_heads(parents);
1676 reflog_msg = (whence == FROM_CHERRY_PICK)
1677 ? "commit (cherry-pick)"
1679 pptr = &commit_list_insert(current_head, pptr)->next;
1682 /* Finally, get the commit message */
1684 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1685 int saved_errno = errno;
1686 rollback_index_files();
1687 die(_("could not read commit message: %s"), strerror(saved_errno));
1690 if (verbose || /* Truncate the message just before the diff, if any. */
1691 cleanup_mode == CLEANUP_SCISSORS)
1692 wt_status_truncate_message_at_cut_line(&sb);
1694 if (cleanup_mode != CLEANUP_NONE)
1695 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1696 if (template_untouched(&sb) && !allow_empty_message) {
1697 rollback_index_files();
1698 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1701 if (message_is_empty(&sb) && !allow_empty_message) {
1702 rollback_index_files();
1703 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1708 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1709 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1711 struct commit_extra_header **tail = &extra;
1712 append_merge_tag_headers(parents, &tail);
1715 if (commit_tree_extended(sb.buf, sb.len, active_cache_tree->sha1,
1716 parents, sha1, author_ident.buf, sign_commit, extra)) {
1717 rollback_index_files();
1718 die(_("failed to write commit object"));
1720 strbuf_release(&author_ident);
1721 free_commit_extra_headers(extra);
1723 ref_lock = lock_any_ref_for_update("HEAD",
1726 : current_head->object.sha1,
1729 rollback_index_files();
1730 die(_("cannot lock HEAD ref"));
1733 nl = strchr(sb.buf, '\n');
1735 strbuf_setlen(&sb, nl + 1 - sb.buf);
1737 strbuf_addch(&sb, '\n');
1738 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1739 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1741 if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1742 rollback_index_files();
1743 die(_("cannot update HEAD ref"));
1746 unlink(git_path("CHERRY_PICK_HEAD"));
1747 unlink(git_path("REVERT_HEAD"));
1748 unlink(git_path("MERGE_HEAD"));
1749 unlink(git_path("MERGE_MSG"));
1750 unlink(git_path("MERGE_MODE"));
1751 unlink(git_path("SQUASH_MSG"));
1753 if (commit_index_files())
1754 die (_("Repository has been updated, but unable to write\n"
1755 "new_index file. Check that disk is not full or quota is\n"
1756 "not exceeded, and then \"git reset HEAD\" to recover."));
1759 run_commit_hook(use_editor, get_index_file(), "post-commit", NULL);
1760 if (amend && !no_post_rewrite) {
1761 struct rewritten rewrite;
1762 memset(&rewrite, 0, sizeof(rewrite));
1763 add_rewritten(&rewrite, current_head->object.sha1, sha1);
1764 copy_rewrite_notes(&rewrite, "amend", "Notes added by 'git commit --amend'");
1765 run_rewrite_hook(&rewrite, "amend");
1768 print_summary(prefix, sha1, !current_head);