4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
10 #include "cache-tree.h"
18 #include "wt-status.h"
19 #include "run-command.h"
24 #include "parse-options.h"
25 #include "string-list.h"
27 #include "unpack-trees.h"
29 #include "submodule.h"
30 #include "gpg-interface.h"
32 #include "sequencer.h"
33 #include "notes-utils.h"
37 static const char * const builtin_commit_usage[] = {
38 N_("git commit [options] [--] <pathspec>..."),
42 static const char * const builtin_status_usage[] = {
43 N_("git status [options] [--] <pathspec>..."),
47 static const char implicit_ident_advice_noconfig[] =
48 N_("Your name and email address were configured automatically based\n"
49 "on your username and hostname. Please check that they are accurate.\n"
50 "You can suppress this message by setting them explicitly. Run the\n"
51 "following command and follow the instructions in your editor to edit\n"
52 "your configuration file:\n"
54 " git config --global --edit\n"
56 "After doing this, you may fix the identity used for this commit with:\n"
58 " git commit --amend --reset-author\n");
60 static const char implicit_ident_advice_config[] =
61 N_("Your name and email address were configured automatically based\n"
62 "on your username and hostname. Please check that they are accurate.\n"
63 "You can suppress this message by setting them explicitly:\n"
65 " git config --global user.name \"Your Name\"\n"
66 " git config --global user.email you@example.com\n"
68 "After doing this, you may fix the identity used for this commit with:\n"
70 " git commit --amend --reset-author\n");
72 static const char empty_amend_advice[] =
73 N_("You asked to amend the most recent commit, but doing so would make\n"
74 "it empty. You can repeat your command with --allow-empty, or you can\n"
75 "remove the commit entirely with \"git reset HEAD^\".\n");
77 static const char empty_cherry_pick_advice[] =
78 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
79 "If you wish to commit it anyway, use:\n"
81 " git commit --allow-empty\n"
84 static const char empty_cherry_pick_advice_single[] =
85 N_("Otherwise, please use 'git reset'\n");
87 static const char empty_cherry_pick_advice_multi[] =
88 N_("If you wish to skip this commit, use:\n"
92 "Then \"git cherry-pick --continue\" will resume cherry-picking\n"
93 "the remaining commits.\n");
95 static const char *use_message_buffer;
96 static const char commit_editmsg[] = "COMMIT_EDITMSG";
97 static struct lock_file index_lock; /* real index */
98 static struct lock_file false_lock; /* used only for partial commits */
105 static const char *logfile, *force_author;
106 static const char *template_file;
108 * The _message variables are commit names from which to take
109 * the commit message and/or authorship.
111 static const char *author_message, *author_message_buffer;
112 static char *edit_message, *use_message;
113 static char *fixup_message, *squash_message;
114 static int all, also, interactive, patch_interactive, only, amend, signoff;
115 static int edit_flag = -1; /* unspecified */
116 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
117 static int no_post_rewrite, allow_empty_message;
118 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
119 static char *sign_commit;
122 * The default commit message cleanup mode will remove the lines
123 * beginning with # (shell comments) and leading and trailing
124 * whitespaces (empty lines or containing only whitespaces)
125 * if editor is used, and only the whitespaces if the message
126 * is specified explicitly.
134 static const char *cleanup_arg;
136 static enum commit_whence whence;
137 static int sequencer_in_use;
138 static int use_editor = 1, include_status = 1;
139 static int show_ignored_in_status, have_option_m;
140 static const char *only_include_assumed;
141 static struct strbuf message = STRBUF_INIT;
143 static enum status_format {
144 STATUS_FORMAT_NONE = 0,
147 STATUS_FORMAT_PORCELAIN,
149 STATUS_FORMAT_UNSPECIFIED
150 } status_format = STATUS_FORMAT_UNSPECIFIED;
152 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
154 struct strbuf *buf = opt->value;
157 strbuf_setlen(buf, 0);
161 strbuf_addch(buf, '\n');
162 strbuf_addstr(buf, arg);
163 strbuf_complete_line(buf);
168 static void determine_whence(struct wt_status *s)
170 if (file_exists(git_path("MERGE_HEAD")))
172 else if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
173 whence = FROM_CHERRY_PICK;
174 if (file_exists(git_path("sequencer")))
175 sequencer_in_use = 1;
178 whence = FROM_COMMIT;
183 static void status_init_config(struct wt_status *s, config_fn_t fn)
185 wt_status_prepare(s);
189 s->hints = advice_status_hints; /* must come after git_config() */
192 static void rollback_index_files(void)
194 switch (commit_style) {
196 break; /* nothing to do */
198 rollback_lock_file(&index_lock);
201 rollback_lock_file(&index_lock);
202 rollback_lock_file(&false_lock);
207 static int commit_index_files(void)
211 switch (commit_style) {
213 break; /* nothing to do */
215 err = commit_lock_file(&index_lock);
218 err = commit_lock_file(&index_lock);
219 rollback_lock_file(&false_lock);
227 * Take a union of paths in the index and the named tree (typically, "HEAD"),
228 * and return the paths that match the given pattern in list.
230 static int list_paths(struct string_list *list, const char *with_tree,
231 const char *prefix, const struct pathspec *pattern)
239 m = xcalloc(1, pattern->nr);
242 char *max_prefix = common_prefix(pattern);
243 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
247 for (i = 0; i < active_nr; i++) {
248 const struct cache_entry *ce = active_cache[i];
249 struct string_list_item *item;
251 if (ce->ce_flags & CE_UPDATE)
253 if (!ce_path_match(ce, pattern, m))
255 item = string_list_insert(list, ce->name);
256 if (ce_skip_worktree(ce))
257 item->util = item; /* better a valid pointer than a fake one */
260 return report_path_error(m, pattern, prefix);
263 static void add_remove_files(struct string_list *list)
266 for (i = 0; i < list->nr; i++) {
268 struct string_list_item *p = &(list->items[i]);
270 /* p->util is skip-worktree */
274 if (!lstat(p->string, &st)) {
275 if (add_to_cache(p->string, &st, 0))
276 die(_("updating files failed"));
278 remove_file_from_cache(p->string);
282 static void create_base_index(const struct commit *current_head)
285 struct unpack_trees_options opts;
293 memset(&opts, 0, sizeof(opts));
297 opts.src_index = &the_index;
298 opts.dst_index = &the_index;
300 opts.fn = oneway_merge;
301 tree = parse_tree_indirect(current_head->object.sha1);
303 die(_("failed to unpack HEAD tree object"));
305 init_tree_desc(&t, tree->buffer, tree->size);
306 if (unpack_trees(1, &t, &opts))
307 exit(128); /* We've already reported the error, finish dying */
310 static void refresh_cache_or_die(int refresh_flags)
313 * refresh_flags contains REFRESH_QUIET, so the only errors
314 * are for unmerged entries.
316 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
317 die_resolve_conflict("commit");
320 static const char *prepare_index(int argc, const char **argv, const char *prefix,
321 const struct commit *current_head, int is_status)
323 struct string_list partial;
324 struct pathspec pathspec;
325 int refresh_flags = REFRESH_QUIET;
328 refresh_flags |= REFRESH_UNMERGED;
329 parse_pathspec(&pathspec, 0,
330 PATHSPEC_PREFER_FULL,
333 if (read_cache_preload(&pathspec) < 0)
334 die(_("index file corrupt"));
337 char *old_index_env = NULL;
338 hold_locked_index(&index_lock, 1);
340 refresh_cache_or_die(refresh_flags);
342 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
343 die(_("unable to create temporary index"));
345 old_index_env = getenv(INDEX_ENVIRONMENT);
346 setenv(INDEX_ENVIRONMENT, index_lock.filename.buf, 1);
348 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
349 die(_("interactive add failed"));
351 if (old_index_env && *old_index_env)
352 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
354 unsetenv(INDEX_ENVIRONMENT);
357 read_cache_from(index_lock.filename.buf);
358 if (update_main_cache_tree(WRITE_TREE_SILENT) == 0) {
359 if (reopen_lock_file(&index_lock) < 0)
360 die(_("unable to write index file"));
361 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
362 die(_("unable to update temporary index"));
364 warning(_("Failed to update main cache tree"));
366 commit_style = COMMIT_NORMAL;
367 return index_lock.filename.buf;
371 * Non partial, non as-is commit.
373 * (1) get the real index;
374 * (2) update the_index as necessary;
375 * (3) write the_index out to the real index (still locked);
376 * (4) return the name of the locked index file.
378 * The caller should run hooks on the locked real index, and
379 * (A) if all goes well, commit the real index;
380 * (B) on failure, rollback the real index.
382 if (all || (also && pathspec.nr)) {
383 hold_locked_index(&index_lock, 1);
384 add_files_to_cache(also ? prefix : NULL, &pathspec, 0);
385 refresh_cache_or_die(refresh_flags);
386 update_main_cache_tree(WRITE_TREE_SILENT);
387 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
388 die(_("unable to write new_index file"));
389 commit_style = COMMIT_NORMAL;
390 return index_lock.filename.buf;
396 * (1) return the name of the real index file.
398 * The caller should run hooks on the real index,
399 * and create commit from the_index.
400 * We still need to refresh the index here.
402 if (!only && !pathspec.nr) {
403 hold_locked_index(&index_lock, 1);
404 refresh_cache_or_die(refresh_flags);
405 if (active_cache_changed
406 || !cache_tree_fully_valid(active_cache_tree)) {
407 update_main_cache_tree(WRITE_TREE_SILENT);
408 active_cache_changed = 1;
410 if (active_cache_changed) {
411 if (write_locked_index(&the_index, &index_lock,
413 die(_("unable to write new_index file"));
415 rollback_lock_file(&index_lock);
417 commit_style = COMMIT_AS_IS;
418 return get_index_file();
424 * (0) find the set of affected paths;
425 * (1) get lock on the real index file;
426 * (2) update the_index with the given paths;
427 * (3) write the_index out to the real index (still locked);
428 * (4) get lock on the false index file;
429 * (5) reset the_index from HEAD;
430 * (6) update the_index the same way as (2);
431 * (7) write the_index out to the false index file;
432 * (8) return the name of the false index file (still locked);
434 * The caller should run hooks on the locked false index, and
435 * create commit from it. Then
436 * (A) if all goes well, commit the real index;
437 * (B) on failure, rollback the real index;
438 * In either case, rollback the false index.
440 commit_style = COMMIT_PARTIAL;
442 if (whence != FROM_COMMIT) {
443 if (whence == FROM_MERGE)
444 die(_("cannot do a partial commit during a merge."));
445 else if (whence == FROM_CHERRY_PICK)
446 die(_("cannot do a partial commit during a cherry-pick."));
449 string_list_init(&partial, 1);
450 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, &pathspec))
454 if (read_cache() < 0)
455 die(_("cannot read the index"));
457 hold_locked_index(&index_lock, 1);
458 add_remove_files(&partial);
459 refresh_cache(REFRESH_QUIET);
460 update_main_cache_tree(WRITE_TREE_SILENT);
461 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
462 die(_("unable to write new_index file"));
464 hold_lock_file_for_update(&false_lock,
465 git_path("next-index-%"PRIuMAX,
466 (uintmax_t) getpid()),
469 create_base_index(current_head);
470 add_remove_files(&partial);
471 refresh_cache(REFRESH_QUIET);
473 if (write_locked_index(&the_index, &false_lock, CLOSE_LOCK))
474 die(_("unable to write temporary index file"));
477 read_cache_from(false_lock.filename.buf);
479 return false_lock.filename.buf;
482 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
485 unsigned char sha1[20];
487 if (s->relative_paths)
492 s->reference = "HEAD^1";
494 s->verbose = verbose;
495 s->index_file = index_file;
498 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
500 wt_status_collect(s);
502 switch (status_format) {
503 case STATUS_FORMAT_SHORT:
504 wt_shortstatus_print(s);
506 case STATUS_FORMAT_PORCELAIN:
507 wt_porcelain_print(s);
509 case STATUS_FORMAT_UNSPECIFIED:
510 die("BUG: finalize_deferred_config() should have been called");
512 case STATUS_FORMAT_NONE:
513 case STATUS_FORMAT_LONG:
518 return s->commitable;
521 static int is_a_merge(const struct commit *current_head)
523 return !!(current_head->parents && current_head->parents->next);
526 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
528 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
529 die("BUG: unable to parse our own ident: %s", buf->buf);
532 static void export_one(const char *var, const char *s, const char *e, int hack)
534 struct strbuf buf = STRBUF_INIT;
536 strbuf_addch(&buf, hack);
537 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
538 setenv(var, buf.buf, 1);
539 strbuf_release(&buf);
542 static int parse_force_date(const char *in, struct strbuf *out)
544 strbuf_addch(out, '@');
546 if (parse_date(in, out) < 0) {
548 unsigned long t = approxidate_careful(in, &errors);
551 strbuf_addf(out, "%lu", t);
557 static void set_ident_var(char **buf, char *val)
563 static char *envdup(const char *var)
565 const char *val = getenv(var);
566 return val ? xstrdup(val) : NULL;
569 static void determine_author_info(struct strbuf *author_ident)
571 char *name, *email, *date;
572 struct ident_split author;
574 name = envdup("GIT_AUTHOR_NAME");
575 email = envdup("GIT_AUTHOR_EMAIL");
576 date = envdup("GIT_AUTHOR_DATE");
578 if (author_message) {
579 struct ident_split ident;
583 a = find_commit_header(author_message_buffer, "author", &len);
585 die(_("commit '%s' lacks author header"), author_message);
586 if (split_ident_line(&ident, a, len) < 0)
587 die(_("commit '%s' has malformed author line"), author_message);
589 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
590 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
592 if (ident.date_begin) {
593 struct strbuf date_buf = STRBUF_INIT;
594 strbuf_addch(&date_buf, '@');
595 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
596 strbuf_addch(&date_buf, ' ');
597 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
598 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
603 struct ident_split ident;
605 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
606 die(_("malformed --author parameter"));
607 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
608 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
612 struct strbuf date_buf = STRBUF_INIT;
613 if (parse_force_date(force_date, &date_buf))
614 die(_("invalid date format: %s"), force_date);
615 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
618 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
619 assert_split_ident(&author, author_ident);
620 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
621 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
622 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
628 static int author_date_is_interesting(void)
630 return author_message || force_date;
633 static void adjust_comment_line_char(const struct strbuf *sb)
635 char candidates[] = "#;@!$%^&|:";
639 comment_line_char = candidates[0];
640 if (!memchr(sb->buf, comment_line_char, sb->len))
644 candidate = strchr(candidates, *p);
647 for (p = sb->buf; *p; p++) {
648 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
649 candidate = strchr(candidates, p[1]);
655 for (p = candidates; *p == ' '; p++)
658 die(_("unable to select a comment character that is not used\n"
659 "in the current commit message"));
660 comment_line_char = *p;
663 static int prepare_to_commit(const char *index_file, const char *prefix,
664 struct commit *current_head,
666 struct strbuf *author_ident)
669 struct strbuf committer_ident = STRBUF_INIT;
671 struct strbuf sb = STRBUF_INIT;
672 const char *hook_arg1 = NULL;
673 const char *hook_arg2 = NULL;
674 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
675 int old_display_comment_prefix;
677 /* This checks and barfs if author is badly specified */
678 determine_author_info(author_ident);
680 if (!no_verify && run_commit_hook(use_editor, index_file, "pre-commit", NULL))
683 if (squash_message) {
685 * Insert the proper subject line before other commit
686 * message options add their content.
688 if (use_message && !strcmp(use_message, squash_message))
689 strbuf_addstr(&sb, "squash! ");
691 struct pretty_print_context ctx = {0};
693 c = lookup_commit_reference_by_name(squash_message);
695 die(_("could not lookup commit %s"), squash_message);
696 ctx.output_encoding = get_commit_output_encoding();
697 format_commit_message(c, "squash! %s\n\n", &sb,
703 strbuf_addbuf(&sb, &message);
704 hook_arg1 = "message";
705 } else if (logfile && !strcmp(logfile, "-")) {
707 fprintf(stderr, _("(reading log message from standard input)\n"));
708 if (strbuf_read(&sb, 0, 0) < 0)
709 die_errno(_("could not read log from standard input"));
710 hook_arg1 = "message";
711 } else if (logfile) {
712 if (strbuf_read_file(&sb, logfile, 0) < 0)
713 die_errno(_("could not read log file '%s'"),
715 hook_arg1 = "message";
716 } else if (use_message) {
718 buffer = strstr(use_message_buffer, "\n\n");
720 strbuf_addstr(&sb, buffer + 2);
721 hook_arg1 = "commit";
722 hook_arg2 = use_message;
723 } else if (fixup_message) {
724 struct pretty_print_context ctx = {0};
725 struct commit *commit;
726 commit = lookup_commit_reference_by_name(fixup_message);
728 die(_("could not lookup commit %s"), fixup_message);
729 ctx.output_encoding = get_commit_output_encoding();
730 format_commit_message(commit, "fixup! %s\n\n",
732 hook_arg1 = "message";
733 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
734 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
735 die_errno(_("could not read MERGE_MSG"));
737 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
738 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
739 die_errno(_("could not read SQUASH_MSG"));
740 hook_arg1 = "squash";
741 } else if (template_file) {
742 if (strbuf_read_file(&sb, template_file, 0) < 0)
743 die_errno(_("could not read '%s'"), template_file);
744 hook_arg1 = "template";
745 clean_message_contents = 0;
749 * The remaining cases don't modify the template message, but
750 * just set the argument(s) to the prepare-commit-msg hook.
752 else if (whence == FROM_MERGE)
754 else if (whence == FROM_CHERRY_PICK) {
755 hook_arg1 = "commit";
756 hook_arg2 = "CHERRY_PICK_HEAD";
759 if (squash_message) {
761 * If squash_commit was used for the commit subject,
762 * then we're possibly hijacking other commit log options.
763 * Reset the hook args to tell the real story.
765 hook_arg1 = "message";
769 s->fp = fopen(git_path(commit_editmsg), "w");
771 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
773 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
774 old_display_comment_prefix = s->display_comment_prefix;
775 s->display_comment_prefix = 1;
778 * Most hints are counter-productive when the commit has
783 if (clean_message_contents)
787 append_signoff(&sb, ignore_non_trailer(&sb), 0);
789 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
790 die_errno(_("could not write commit template"));
792 if (auto_comment_line_char)
793 adjust_comment_line_char(&sb);
796 /* This checks if committer ident is explicitly given */
797 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
798 if (use_editor && include_status) {
800 int saved_color_setting;
801 struct ident_split ci, ai;
803 if (whence != FROM_COMMIT) {
804 if (cleanup_mode == CLEANUP_SCISSORS)
805 wt_status_add_cut_line(s->fp);
806 status_printf_ln(s, GIT_COLOR_NORMAL,
809 "It looks like you may be committing a merge.\n"
810 "If this is not correct, please remove the file\n"
814 "It looks like you may be committing a cherry-pick.\n"
815 "If this is not correct, please remove the file\n"
818 git_path(whence == FROM_MERGE
820 : "CHERRY_PICK_HEAD"));
823 fprintf(s->fp, "\n");
824 if (cleanup_mode == CLEANUP_ALL)
825 status_printf(s, GIT_COLOR_NORMAL,
826 _("Please enter the commit message for your changes."
827 " Lines starting\nwith '%c' will be ignored, and an empty"
828 " message aborts the commit.\n"), comment_line_char);
829 else if (cleanup_mode == CLEANUP_SCISSORS && whence == FROM_COMMIT)
830 wt_status_add_cut_line(s->fp);
831 else /* CLEANUP_SPACE, that is. */
832 status_printf(s, GIT_COLOR_NORMAL,
833 _("Please enter the commit message for your changes."
835 "with '%c' will be kept; you may remove them"
836 " yourself if you want to.\n"
837 "An empty message aborts the commit.\n"), comment_line_char);
838 if (only_include_assumed)
839 status_printf_ln(s, GIT_COLOR_NORMAL,
840 "%s", only_include_assumed);
843 * These should never fail because they come from our own
844 * fmt_ident. They may fail the sane_ident test, but we know
845 * that the name and mail pointers will at least be valid,
846 * which is enough for our tests and printing here.
848 assert_split_ident(&ai, author_ident);
849 assert_split_ident(&ci, &committer_ident);
851 if (ident_cmp(&ai, &ci))
852 status_printf_ln(s, GIT_COLOR_NORMAL,
854 "Author: %.*s <%.*s>"),
855 ident_shown++ ? "" : "\n",
856 (int)(ai.name_end - ai.name_begin), ai.name_begin,
857 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
859 if (author_date_is_interesting())
860 status_printf_ln(s, GIT_COLOR_NORMAL,
863 ident_shown++ ? "" : "\n",
864 show_ident_date(&ai, DATE_NORMAL));
866 if (!committer_ident_sufficiently_given())
867 status_printf_ln(s, GIT_COLOR_NORMAL,
869 "Committer: %.*s <%.*s>"),
870 ident_shown++ ? "" : "\n",
871 (int)(ci.name_end - ci.name_begin), ci.name_begin,
872 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
875 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", "");
877 saved_color_setting = s->use_color;
879 commitable = run_status(s->fp, index_file, prefix, 1, s);
880 s->use_color = saved_color_setting;
882 unsigned char sha1[20];
883 const char *parent = "HEAD";
885 if (!active_nr && read_cache() < 0)
886 die(_("Cannot read index"));
891 if (get_sha1(parent, sha1))
892 commitable = !!active_nr;
895 * Unless the user did explicitly request a submodule
896 * ignore mode by passing a command line option we do
897 * not ignore any changed submodule SHA-1s when
898 * comparing index and parent, no matter what is
899 * configured. Otherwise we won't commit any
900 * submodules which were manually staged, which would
901 * be really confusing.
903 int diff_flags = DIFF_OPT_OVERRIDE_SUBMODULE_CONFIG;
904 if (ignore_submodule_arg &&
905 !strcmp(ignore_submodule_arg, "all"))
906 diff_flags |= DIFF_OPT_IGNORE_SUBMODULES;
907 commitable = index_differs_from(parent, diff_flags);
910 strbuf_release(&committer_ident);
915 * Reject an attempt to record a non-merge empty commit without
916 * explicit --allow-empty. In the cherry-pick case, it may be
917 * empty due to conflict resolution, which the user should okay.
919 if (!commitable && whence != FROM_MERGE && !allow_empty &&
920 !(amend && is_a_merge(current_head))) {
921 s->display_comment_prefix = old_display_comment_prefix;
922 run_status(stdout, index_file, prefix, 0, s);
924 fputs(_(empty_amend_advice), stderr);
925 else if (whence == FROM_CHERRY_PICK) {
926 fputs(_(empty_cherry_pick_advice), stderr);
927 if (!sequencer_in_use)
928 fputs(_(empty_cherry_pick_advice_single), stderr);
930 fputs(_(empty_cherry_pick_advice_multi), stderr);
936 * Re-read the index as pre-commit hook could have updated it,
937 * and write it out as a tree. We must do this before we invoke
938 * the editor and after we invoke run_status above.
941 read_cache_from(index_file);
942 if (update_main_cache_tree(0)) {
943 error(_("Error building trees"));
947 if (run_commit_hook(use_editor, index_file, "prepare-commit-msg",
948 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
952 char index[PATH_MAX];
953 const char *env[2] = { NULL };
955 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
956 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
958 _("Please supply the message using either -m or -F option.\n"));
964 run_commit_hook(use_editor, index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
971 static int rest_is_empty(struct strbuf *sb, int start)
976 /* Check if the rest is just whitespace and Signed-of-by's. */
977 for (i = start; i < sb->len; i++) {
978 nl = memchr(sb->buf + i, '\n', sb->len - i);
984 if (strlen(sign_off_header) <= eol - i &&
985 starts_with(sb->buf + i, sign_off_header)) {
990 if (!isspace(sb->buf[i++]))
998 * Find out if the message in the strbuf contains only whitespace and
999 * Signed-off-by lines.
1001 static int message_is_empty(struct strbuf *sb)
1003 if (cleanup_mode == CLEANUP_NONE && sb->len)
1005 return rest_is_empty(sb, 0);
1009 * See if the user edited the message in the editor or left what
1010 * was in the template intact
1012 static int template_untouched(struct strbuf *sb)
1014 struct strbuf tmpl = STRBUF_INIT;
1017 if (cleanup_mode == CLEANUP_NONE && sb->len)
1020 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1023 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
1024 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1026 strbuf_release(&tmpl);
1027 return rest_is_empty(sb, start - sb->buf);
1030 static const char *find_author_by_nickname(const char *name)
1032 struct rev_info revs;
1033 struct commit *commit;
1034 struct strbuf buf = STRBUF_INIT;
1035 struct string_list mailmap = STRING_LIST_INIT_NODUP;
1039 init_revisions(&revs, NULL);
1040 strbuf_addf(&buf, "--author=%s", name);
1045 setup_revisions(ac, av, &revs, NULL);
1046 revs.mailmap = &mailmap;
1047 read_mailmap(revs.mailmap, NULL);
1049 if (prepare_revision_walk(&revs))
1050 die(_("revision walk setup failed"));
1051 commit = get_revision(&revs);
1053 struct pretty_print_context ctx = {0};
1054 ctx.date_mode = DATE_NORMAL;
1055 strbuf_release(&buf);
1056 format_commit_message(commit, "%aN <%aE>", &buf, &ctx);
1057 clear_mailmap(&mailmap);
1058 return strbuf_detach(&buf, NULL);
1060 die(_("No existing author found with '%s'"), name);
1064 static void handle_untracked_files_arg(struct wt_status *s)
1066 if (!untracked_files_arg)
1067 ; /* default already initialized */
1068 else if (!strcmp(untracked_files_arg, "no"))
1069 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1070 else if (!strcmp(untracked_files_arg, "normal"))
1071 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1072 else if (!strcmp(untracked_files_arg, "all"))
1073 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1075 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1078 static const char *read_commit_message(const char *name)
1080 const char *out_enc;
1081 struct commit *commit;
1083 commit = lookup_commit_reference_by_name(name);
1085 die(_("could not lookup commit %s"), name);
1086 out_enc = get_commit_output_encoding();
1087 return logmsg_reencode(commit, NULL, out_enc);
1091 * Enumerate what needs to be propagated when --porcelain
1092 * is not in effect here.
1094 static struct status_deferred_config {
1095 enum status_format status_format;
1097 } status_deferred_config = {
1098 STATUS_FORMAT_UNSPECIFIED,
1099 -1 /* unspecified */
1102 static void finalize_deferred_config(struct wt_status *s)
1104 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1105 !s->null_termination);
1107 if (s->null_termination) {
1108 if (status_format == STATUS_FORMAT_NONE ||
1109 status_format == STATUS_FORMAT_UNSPECIFIED)
1110 status_format = STATUS_FORMAT_PORCELAIN;
1111 else if (status_format == STATUS_FORMAT_LONG)
1112 die(_("--long and -z are incompatible"));
1115 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1116 status_format = status_deferred_config.status_format;
1117 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1118 status_format = STATUS_FORMAT_NONE;
1120 if (use_deferred_config && s->show_branch < 0)
1121 s->show_branch = status_deferred_config.show_branch;
1122 if (s->show_branch < 0)
1126 static int parse_and_validate_options(int argc, const char *argv[],
1127 const struct option *options,
1128 const char * const usage[],
1130 struct commit *current_head,
1131 struct wt_status *s)
1135 argc = parse_options(argc, argv, prefix, options, usage, 0);
1136 finalize_deferred_config(s);
1138 if (force_author && !strchr(force_author, '>'))
1139 force_author = find_author_by_nickname(force_author);
1141 if (force_author && renew_authorship)
1142 die(_("Using both --reset-author and --author does not make sense"));
1144 if (logfile || have_option_m || use_message || fixup_message)
1147 use_editor = edit_flag;
1149 /* Sanity check options */
1150 if (amend && !current_head)
1151 die(_("You have nothing to amend."));
1152 if (amend && whence != FROM_COMMIT) {
1153 if (whence == FROM_MERGE)
1154 die(_("You are in the middle of a merge -- cannot amend."));
1155 else if (whence == FROM_CHERRY_PICK)
1156 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1158 if (fixup_message && squash_message)
1159 die(_("Options --squash and --fixup cannot be used together"));
1169 die(_("Only one of -c/-C/-F/--fixup can be used."));
1170 if (message.len && f > 0)
1171 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1172 if (f || message.len)
1173 template_file = NULL;
1175 use_message = edit_message;
1176 if (amend && !use_message && !fixup_message)
1177 use_message = "HEAD";
1178 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1179 die(_("--reset-author can be used only with -C, -c or --amend."));
1181 use_message_buffer = read_commit_message(use_message);
1182 if (!renew_authorship) {
1183 author_message = use_message;
1184 author_message_buffer = use_message_buffer;
1187 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1188 author_message = "CHERRY_PICK_HEAD";
1189 author_message_buffer = read_commit_message(author_message);
1192 if (patch_interactive)
1195 if (also + only + all + interactive > 1)
1196 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1197 if (argc == 0 && (also || (only && !amend)))
1198 die(_("No paths with --include/--only does not make sense."));
1199 if (argc == 0 && only && amend)
1200 only_include_assumed = _("Clever... amending the last one with dirty index.");
1201 if (argc > 0 && !also && !only)
1202 only_include_assumed = _("Explicit paths specified without -i or -o; assuming --only paths...");
1203 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1204 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1205 else if (!strcmp(cleanup_arg, "verbatim"))
1206 cleanup_mode = CLEANUP_NONE;
1207 else if (!strcmp(cleanup_arg, "whitespace"))
1208 cleanup_mode = CLEANUP_SPACE;
1209 else if (!strcmp(cleanup_arg, "strip"))
1210 cleanup_mode = CLEANUP_ALL;
1211 else if (!strcmp(cleanup_arg, "scissors"))
1212 cleanup_mode = use_editor ? CLEANUP_SCISSORS : CLEANUP_SPACE;
1214 die(_("Invalid cleanup mode %s"), cleanup_arg);
1216 handle_untracked_files_arg(s);
1218 if (all && argc > 0)
1219 die(_("Paths with -a does not make sense."));
1221 if (status_format != STATUS_FORMAT_NONE)
1227 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1228 const struct commit *current_head, struct wt_status *s)
1231 const char *index_file;
1233 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1234 commitable = run_status(stdout, index_file, prefix, 0, s);
1235 rollback_index_files();
1237 return commitable ? 0 : 1;
1240 static int parse_status_slot(const char *slot)
1242 if (!strcasecmp(slot, "header"))
1243 return WT_STATUS_HEADER;
1244 if (!strcasecmp(slot, "branch"))
1245 return WT_STATUS_ONBRANCH;
1246 if (!strcasecmp(slot, "updated") || !strcasecmp(slot, "added"))
1247 return WT_STATUS_UPDATED;
1248 if (!strcasecmp(slot, "changed"))
1249 return WT_STATUS_CHANGED;
1250 if (!strcasecmp(slot, "untracked"))
1251 return WT_STATUS_UNTRACKED;
1252 if (!strcasecmp(slot, "nobranch"))
1253 return WT_STATUS_NOBRANCH;
1254 if (!strcasecmp(slot, "unmerged"))
1255 return WT_STATUS_UNMERGED;
1259 static int git_status_config(const char *k, const char *v, void *cb)
1261 struct wt_status *s = cb;
1262 const char *slot_name;
1264 if (starts_with(k, "column."))
1265 return git_column_config(k, v, "status", &s->colopts);
1266 if (!strcmp(k, "status.submodulesummary")) {
1268 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1269 if (is_bool && s->submodule_summary)
1270 s->submodule_summary = -1;
1273 if (!strcmp(k, "status.short")) {
1274 if (git_config_bool(k, v))
1275 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1277 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1280 if (!strcmp(k, "status.branch")) {
1281 status_deferred_config.show_branch = git_config_bool(k, v);
1284 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1285 s->use_color = git_config_colorbool(k, v);
1288 if (!strcmp(k, "status.displaycommentprefix")) {
1289 s->display_comment_prefix = git_config_bool(k, v);
1292 if (skip_prefix(k, "status.color.", &slot_name) ||
1293 skip_prefix(k, "color.status.", &slot_name)) {
1294 int slot = parse_status_slot(slot_name);
1298 return config_error_nonbool(k);
1299 return color_parse(v, s->color_palette[slot]);
1301 if (!strcmp(k, "status.relativepaths")) {
1302 s->relative_paths = git_config_bool(k, v);
1305 if (!strcmp(k, "status.showuntrackedfiles")) {
1307 return config_error_nonbool(k);
1308 else if (!strcmp(v, "no"))
1309 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1310 else if (!strcmp(v, "normal"))
1311 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1312 else if (!strcmp(v, "all"))
1313 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1315 return error(_("Invalid untracked files mode '%s'"), v);
1318 return git_diff_ui_config(k, v, NULL);
1321 int cmd_status(int argc, const char **argv, const char *prefix)
1323 static struct wt_status s;
1325 unsigned char sha1[20];
1326 static struct option builtin_status_options[] = {
1327 OPT__VERBOSE(&verbose, N_("be verbose")),
1328 OPT_SET_INT('s', "short", &status_format,
1329 N_("show status concisely"), STATUS_FORMAT_SHORT),
1330 OPT_BOOL('b', "branch", &s.show_branch,
1331 N_("show branch information")),
1332 OPT_SET_INT(0, "porcelain", &status_format,
1333 N_("machine-readable output"),
1334 STATUS_FORMAT_PORCELAIN),
1335 OPT_SET_INT(0, "long", &status_format,
1336 N_("show status in long format (default)"),
1337 STATUS_FORMAT_LONG),
1338 OPT_BOOL('z', "null", &s.null_termination,
1339 N_("terminate entries with NUL")),
1340 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1342 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1343 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1344 OPT_BOOL(0, "ignored", &show_ignored_in_status,
1345 N_("show ignored files")),
1346 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1347 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1348 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1349 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1353 if (argc == 2 && !strcmp(argv[1], "-h"))
1354 usage_with_options(builtin_status_usage, builtin_status_options);
1356 status_init_config(&s, git_status_config);
1357 argc = parse_options(argc, argv, prefix,
1358 builtin_status_options,
1359 builtin_status_usage, 0);
1360 finalize_colopts(&s.colopts, -1);
1361 finalize_deferred_config(&s);
1363 handle_untracked_files_arg(&s);
1364 if (show_ignored_in_status)
1365 s.show_ignored_files = 1;
1366 parse_pathspec(&s.pathspec, 0,
1367 PATHSPEC_PREFER_FULL,
1370 read_cache_preload(&s.pathspec);
1371 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, &s.pathspec, NULL, NULL);
1373 fd = hold_locked_index(&index_lock, 0);
1375 update_index_if_able(&the_index, &index_lock);
1377 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1378 s.ignore_submodule_arg = ignore_submodule_arg;
1379 wt_status_collect(&s);
1381 if (s.relative_paths)
1384 switch (status_format) {
1385 case STATUS_FORMAT_SHORT:
1386 wt_shortstatus_print(&s);
1388 case STATUS_FORMAT_PORCELAIN:
1389 wt_porcelain_print(&s);
1391 case STATUS_FORMAT_UNSPECIFIED:
1392 die("BUG: finalize_deferred_config() should have been called");
1394 case STATUS_FORMAT_NONE:
1395 case STATUS_FORMAT_LONG:
1396 s.verbose = verbose;
1397 s.ignore_submodule_arg = ignore_submodule_arg;
1398 wt_status_print(&s);
1404 static const char *implicit_ident_advice(void)
1406 char *user_config = NULL;
1407 char *xdg_config = NULL;
1410 home_config_paths(&user_config, &xdg_config, "config");
1411 config_exists = file_exists(user_config) || file_exists(xdg_config);
1416 return _(implicit_ident_advice_config);
1418 return _(implicit_ident_advice_noconfig);
1422 static void print_summary(const char *prefix, const unsigned char *sha1,
1425 struct rev_info rev;
1426 struct commit *commit;
1427 struct strbuf format = STRBUF_INIT;
1428 unsigned char junk_sha1[20];
1430 struct pretty_print_context pctx = {0};
1431 struct strbuf author_ident = STRBUF_INIT;
1432 struct strbuf committer_ident = STRBUF_INIT;
1434 commit = lookup_commit(sha1);
1436 die(_("couldn't look up newly created commit"));
1437 if (parse_commit(commit))
1438 die(_("could not parse newly created commit"));
1440 strbuf_addstr(&format, "format:%h] %s");
1442 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1443 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1444 if (strbuf_cmp(&author_ident, &committer_ident)) {
1445 strbuf_addstr(&format, "\n Author: ");
1446 strbuf_addbuf_percentquote(&format, &author_ident);
1448 if (author_date_is_interesting()) {
1449 struct strbuf date = STRBUF_INIT;
1450 format_commit_message(commit, "%ad", &date, &pctx);
1451 strbuf_addstr(&format, "\n Date: ");
1452 strbuf_addbuf_percentquote(&format, &date);
1453 strbuf_release(&date);
1455 if (!committer_ident_sufficiently_given()) {
1456 strbuf_addstr(&format, "\n Committer: ");
1457 strbuf_addbuf_percentquote(&format, &committer_ident);
1458 if (advice_implicit_identity) {
1459 strbuf_addch(&format, '\n');
1460 strbuf_addstr(&format, implicit_ident_advice());
1463 strbuf_release(&author_ident);
1464 strbuf_release(&committer_ident);
1466 init_revisions(&rev, prefix);
1467 setup_revisions(0, NULL, &rev, NULL);
1470 rev.diffopt.output_format =
1471 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1473 rev.verbose_header = 1;
1474 rev.show_root_diff = 1;
1475 get_commit_format(format.buf, &rev);
1476 rev.always_show_header = 0;
1477 rev.diffopt.detect_rename = 1;
1478 rev.diffopt.break_opt = 0;
1479 diff_setup_done(&rev.diffopt);
1481 head = resolve_ref_unsafe("HEAD", 0, junk_sha1, NULL);
1482 if (!strcmp(head, "HEAD"))
1483 head = _("detached HEAD");
1485 skip_prefix(head, "refs/heads/", &head);
1486 printf("[%s%s ", head, initial_commit ? _(" (root-commit)") : "");
1488 if (!log_tree_commit(&rev, commit)) {
1489 rev.always_show_header = 1;
1490 rev.use_terminator = 1;
1491 log_tree_commit(&rev, commit);
1494 strbuf_release(&format);
1497 static int git_commit_config(const char *k, const char *v, void *cb)
1499 struct wt_status *s = cb;
1502 if (!strcmp(k, "commit.template"))
1503 return git_config_pathname(&template_file, k, v);
1504 if (!strcmp(k, "commit.status")) {
1505 include_status = git_config_bool(k, v);
1508 if (!strcmp(k, "commit.cleanup"))
1509 return git_config_string(&cleanup_arg, k, v);
1510 if (!strcmp(k, "commit.gpgsign")) {
1511 sign_commit = git_config_bool(k, v) ? "" : NULL;
1515 status = git_gpg_config(k, v, NULL);
1518 return git_status_config(k, v, s);
1521 int run_commit_hook(int editor_is_used, const char *index_file, const char *name, ...)
1523 const char *hook_env[3] = { NULL };
1524 char index[PATH_MAX];
1528 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
1529 hook_env[0] = index;
1532 * Let the hook know that no editor will be launched.
1534 if (!editor_is_used)
1535 hook_env[1] = "GIT_EDITOR=:";
1537 va_start(args, name);
1538 ret = run_hook_ve(hook_env, name, args);
1544 int cmd_commit(int argc, const char **argv, const char *prefix)
1546 static struct wt_status s;
1547 static struct option builtin_commit_options[] = {
1548 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1549 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1551 OPT_GROUP(N_("Commit message options")),
1552 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1553 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1554 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1555 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1556 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1557 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1558 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1559 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1560 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1561 OPT_BOOL('s', "signoff", &signoff, N_("add Signed-off-by:")),
1562 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1563 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1564 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1565 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1566 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1567 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1568 /* end commit message options */
1570 OPT_GROUP(N_("Commit contents options")),
1571 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1572 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1573 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1574 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1575 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1576 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1577 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1578 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1579 STATUS_FORMAT_SHORT),
1580 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1581 OPT_SET_INT(0, "porcelain", &status_format,
1582 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1583 OPT_SET_INT(0, "long", &status_format,
1584 N_("show status in long format (default)"),
1585 STATUS_FORMAT_LONG),
1586 OPT_BOOL('z', "null", &s.null_termination,
1587 N_("terminate entries with NUL")),
1588 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1589 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1590 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, N_("mode"), N_("show untracked files, optional modes: all, normal, no. (Default: all)"), PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1591 /* end commit contents options */
1593 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1594 N_("ok to record an empty change")),
1595 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1596 N_("ok to record a change with an empty message")),
1601 struct strbuf sb = STRBUF_INIT;
1602 struct strbuf author_ident = STRBUF_INIT;
1603 const char *index_file, *reflog_msg;
1605 unsigned char sha1[20];
1606 struct commit_list *parents = NULL, **pptr = &parents;
1607 struct stat statbuf;
1608 struct commit *current_head = NULL;
1609 struct commit_extra_header *extra = NULL;
1610 struct ref_transaction *transaction;
1611 struct strbuf err = STRBUF_INIT;
1613 if (argc == 2 && !strcmp(argv[1], "-h"))
1614 usage_with_options(builtin_commit_usage, builtin_commit_options);
1616 status_init_config(&s, git_commit_config);
1617 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1620 if (get_sha1("HEAD", sha1))
1621 current_head = NULL;
1623 current_head = lookup_commit_or_die(sha1, "HEAD");
1624 if (parse_commit(current_head))
1625 die(_("could not parse HEAD commit"));
1627 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1628 builtin_commit_usage,
1629 prefix, current_head, &s);
1631 return dry_run_commit(argc, argv, prefix, current_head, &s);
1632 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1634 /* Set up everything for writing the commit object. This includes
1635 running hooks, writing the trees, and interacting with the user. */
1636 if (!prepare_to_commit(index_file, prefix,
1637 current_head, &s, &author_ident)) {
1638 rollback_index_files();
1642 /* Determine parents */
1643 reflog_msg = getenv("GIT_REFLOG_ACTION");
1644 if (!current_head) {
1646 reflog_msg = "commit (initial)";
1648 struct commit_list *c;
1651 reflog_msg = "commit (amend)";
1652 for (c = current_head->parents; c; c = c->next)
1653 pptr = &commit_list_insert(c->item, pptr)->next;
1654 } else if (whence == FROM_MERGE) {
1655 struct strbuf m = STRBUF_INIT;
1657 int allow_fast_forward = 1;
1658 int reverse_parents = 0;
1661 reflog_msg = "commit (merge)";
1662 pptr = &commit_list_insert(current_head, pptr)->next;
1663 fp = fopen(git_path("MERGE_HEAD"), "r");
1665 die_errno(_("could not open '%s' for reading"),
1666 git_path("MERGE_HEAD"));
1667 while (strbuf_getline(&m, fp, '\n') != EOF) {
1668 struct commit *parent;
1670 parent = get_merge_parent(m.buf);
1672 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1673 pptr = &commit_list_insert(parent, pptr)->next;
1677 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1678 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1679 die_errno(_("could not read MERGE_MODE"));
1680 if (strstr(sb.buf, "no-ff"))
1681 allow_fast_forward = 0;
1682 if (strstr(sb.buf, "reverse"))
1683 reverse_parents = 1;
1685 if (allow_fast_forward)
1686 parents = reduce_heads(parents);
1687 if (reverse_parents)
1688 parents = reverse_heads(parents);
1691 reflog_msg = (whence == FROM_CHERRY_PICK)
1692 ? "commit (cherry-pick)"
1694 pptr = &commit_list_insert(current_head, pptr)->next;
1697 /* Finally, get the commit message */
1699 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1700 int saved_errno = errno;
1701 rollback_index_files();
1702 die(_("could not read commit message: %s"), strerror(saved_errno));
1705 if (verbose || /* Truncate the message just before the diff, if any. */
1706 cleanup_mode == CLEANUP_SCISSORS)
1707 wt_status_truncate_message_at_cut_line(&sb);
1709 if (cleanup_mode != CLEANUP_NONE)
1710 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1711 if (template_untouched(&sb) && !allow_empty_message) {
1712 rollback_index_files();
1713 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1716 if (message_is_empty(&sb) && !allow_empty_message) {
1717 rollback_index_files();
1718 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1723 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1724 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1726 struct commit_extra_header **tail = &extra;
1727 append_merge_tag_headers(parents, &tail);
1730 if (commit_tree_extended(sb.buf, sb.len, active_cache_tree->sha1,
1731 parents, sha1, author_ident.buf, sign_commit, extra)) {
1732 rollback_index_files();
1733 die(_("failed to write commit object"));
1735 strbuf_release(&author_ident);
1736 free_commit_extra_headers(extra);
1738 nl = strchr(sb.buf, '\n');
1740 strbuf_setlen(&sb, nl + 1 - sb.buf);
1742 strbuf_addch(&sb, '\n');
1743 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1744 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1746 transaction = ref_transaction_begin(&err);
1748 ref_transaction_update(transaction, "HEAD", sha1,
1750 ? current_head->object.sha1 : NULL,
1751 0, !!current_head, sb.buf, &err) ||
1752 ref_transaction_commit(transaction, &err)) {
1753 rollback_index_files();
1756 ref_transaction_free(transaction);
1758 unlink(git_path("CHERRY_PICK_HEAD"));
1759 unlink(git_path("REVERT_HEAD"));
1760 unlink(git_path("MERGE_HEAD"));
1761 unlink(git_path("MERGE_MSG"));
1762 unlink(git_path("MERGE_MODE"));
1763 unlink(git_path("SQUASH_MSG"));
1765 if (commit_index_files())
1766 die (_("Repository has been updated, but unable to write\n"
1767 "new_index file. Check that disk is not full and quota is\n"
1768 "not exceeded, and then \"git reset HEAD\" to recover."));
1771 run_commit_hook(use_editor, get_index_file(), "post-commit", NULL);
1772 if (amend && !no_post_rewrite) {
1773 struct rewritten rewrite;
1774 memset(&rewrite, 0, sizeof(rewrite));
1775 add_rewritten(&rewrite, current_head->object.sha1, sha1);
1776 copy_rewrite_notes(&rewrite, "amend", "Notes added by 'git commit --amend'");
1777 run_rewrite_hook(&rewrite, "amend");
1780 print_summary(prefix, sha1, !current_head);
1782 strbuf_release(&err);