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"
30 static const char * const builtin_commit_usage[] = {
31 "git commit [options] [--] <filepattern>...",
35 static const char * const builtin_status_usage[] = {
36 "git status [options] [--] <filepattern>...",
40 static const char implicit_ident_advice[] =
41 N_("Your name and email address were configured automatically based\n"
42 "on your username and hostname. Please check that they are accurate.\n"
43 "You can suppress this message by setting them explicitly:\n"
45 " git config --global user.name \"Your Name\"\n"
46 " git config --global user.email you@example.com\n"
48 "After doing this, you may fix the identity used for this commit with:\n"
50 " git commit --amend --reset-author\n");
52 static const char empty_amend_advice[] =
53 N_("You asked to amend the most recent commit, but doing so would make\n"
54 "it empty. You can repeat your command with --allow-empty, or you can\n"
55 "remove the commit entirely with \"git reset HEAD^\".\n");
57 static const char empty_cherry_pick_advice[] =
58 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
59 "If you wish to commit it anyway, use:\n"
61 " git commit --allow-empty\n"
63 "Otherwise, please use 'git reset'\n");
65 static unsigned char head_sha1[20];
67 static const char *use_message_buffer;
68 static const char commit_editmsg[] = "COMMIT_EDITMSG";
69 static struct lock_file index_lock; /* real index */
70 static struct lock_file false_lock; /* used only for partial commits */
77 static const char *logfile, *force_author;
78 static const char *template_file;
80 * The _message variables are commit names from which to take
81 * the commit message and/or authorship.
83 static const char *author_message, *author_message_buffer;
84 static char *edit_message, *use_message;
85 static char *fixup_message, *squash_message;
86 static int all, edit_flag, also, interactive, only, amend, signoff;
87 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
88 static int no_post_rewrite, allow_empty_message;
89 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
91 * The default commit message cleanup mode will remove the lines
92 * beginning with # (shell comments) and leading and trailing
93 * whitespaces (empty lines or containing only whitespaces)
94 * if editor is used, and only the whitespaces if the message
95 * is specified explicitly.
102 static char *cleanup_arg;
104 static enum commit_whence whence;
105 static int use_editor = 1, initial_commit, include_status = 1;
106 static int show_ignored_in_status;
107 static const char *only_include_assumed;
108 static struct strbuf message;
110 static int null_termination;
114 STATUS_FORMAT_PORCELAIN
115 } status_format = STATUS_FORMAT_LONG;
116 static int status_show_branch;
118 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
120 struct strbuf *buf = opt->value;
122 strbuf_setlen(buf, 0);
124 strbuf_addstr(buf, arg);
125 strbuf_addstr(buf, "\n\n");
130 static struct option builtin_commit_options[] = {
131 OPT__QUIET(&quiet, "suppress summary after successful commit"),
132 OPT__VERBOSE(&verbose, "show diff in commit message template"),
134 OPT_GROUP("Commit message options"),
135 OPT_FILENAME('F', "file", &logfile, "read message from file"),
136 OPT_STRING(0, "author", &force_author, "author", "override author for commit"),
137 OPT_STRING(0, "date", &force_date, "date", "override date for commit"),
138 OPT_CALLBACK('m', "message", &message, "message", "commit message", opt_parse_m),
139 OPT_STRING('c', "reedit-message", &edit_message, "commit", "reuse and edit message from specified commit"),
140 OPT_STRING('C', "reuse-message", &use_message, "commit", "reuse message from specified commit"),
141 OPT_STRING(0, "fixup", &fixup_message, "commit", "use autosquash formatted message to fixup specified commit"),
142 OPT_STRING(0, "squash", &squash_message, "commit", "use autosquash formatted message to squash specified commit"),
143 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
144 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
145 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
146 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
147 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
148 OPT_BOOLEAN(0, "status", &include_status, "include status in commit message template"),
149 /* end commit message options */
151 OPT_GROUP("Commit contents options"),
152 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
153 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
154 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
155 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
156 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
157 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
158 OPT_SET_INT(0, "short", &status_format, "show status concisely",
159 STATUS_FORMAT_SHORT),
160 OPT_BOOLEAN(0, "branch", &status_show_branch, "show branch information"),
161 OPT_SET_INT(0, "porcelain", &status_format,
162 "machine-readable output", STATUS_FORMAT_PORCELAIN),
163 OPT_BOOLEAN('z', "null", &null_termination,
164 "terminate entries with NUL"),
165 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
166 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, "bypass post-rewrite hook"),
167 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, "mode", "show untracked files, optional modes: all, normal, no. (Default: all)", PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
168 /* end commit contents options */
170 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
171 "ok to record an empty change",
172 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
173 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
174 "ok to record a change with an empty message",
175 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
180 static void determine_whence(struct wt_status *s)
182 if (file_exists(git_path("MERGE_HEAD")))
184 else if (file_exists(git_path("CHERRY_PICK_HEAD")))
185 whence = FROM_CHERRY_PICK;
187 whence = FROM_COMMIT;
192 static const char *whence_s(void)
202 case FROM_CHERRY_PICK:
210 static void rollback_index_files(void)
212 switch (commit_style) {
214 break; /* nothing to do */
216 rollback_lock_file(&index_lock);
219 rollback_lock_file(&index_lock);
220 rollback_lock_file(&false_lock);
225 static int commit_index_files(void)
229 switch (commit_style) {
231 break; /* nothing to do */
233 err = commit_lock_file(&index_lock);
236 err = commit_lock_file(&index_lock);
237 rollback_lock_file(&false_lock);
245 * Take a union of paths in the index and the named tree (typically, "HEAD"),
246 * and return the paths that match the given pattern in list.
248 static int list_paths(struct string_list *list, const char *with_tree,
249 const char *prefix, const char **pattern)
254 for (i = 0; pattern[i]; i++)
259 overlay_tree_on_cache(with_tree, prefix);
261 for (i = 0; i < active_nr; i++) {
262 struct cache_entry *ce = active_cache[i];
263 struct string_list_item *item;
265 if (ce->ce_flags & CE_UPDATE)
267 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
269 item = string_list_insert(list, ce->name);
270 if (ce_skip_worktree(ce))
271 item->util = item; /* better a valid pointer than a fake one */
274 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
277 static void add_remove_files(struct string_list *list)
280 for (i = 0; i < list->nr; i++) {
282 struct string_list_item *p = &(list->items[i]);
284 /* p->util is skip-worktree */
288 if (!lstat(p->string, &st)) {
289 if (add_to_cache(p->string, &st, 0))
290 die(_("updating files failed"));
292 remove_file_from_cache(p->string);
296 static void create_base_index(void)
299 struct unpack_trees_options opts;
302 if (initial_commit) {
307 memset(&opts, 0, sizeof(opts));
311 opts.src_index = &the_index;
312 opts.dst_index = &the_index;
314 opts.fn = oneway_merge;
315 tree = parse_tree_indirect(head_sha1);
317 die(_("failed to unpack HEAD tree object"));
319 init_tree_desc(&t, tree->buffer, tree->size);
320 if (unpack_trees(1, &t, &opts))
321 exit(128); /* We've already reported the error, finish dying */
324 static void refresh_cache_or_die(int refresh_flags)
327 * refresh_flags contains REFRESH_QUIET, so the only errors
328 * are for unmerged entries.
330 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
331 die_resolve_conflict("commit");
334 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
337 struct string_list partial;
338 const char **pathspec = NULL;
339 char *old_index_env = NULL;
340 int refresh_flags = REFRESH_QUIET;
343 refresh_flags |= REFRESH_UNMERGED;
346 pathspec = get_pathspec(prefix, argv);
348 if (read_cache_preload(pathspec) < 0)
349 die(_("index file corrupt"));
352 fd = hold_locked_index(&index_lock, 1);
354 refresh_cache_or_die(refresh_flags);
356 if (write_cache(fd, active_cache, active_nr) ||
357 close_lock_file(&index_lock))
358 die(_("unable to create temporary index"));
360 old_index_env = getenv(INDEX_ENVIRONMENT);
361 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
363 if (interactive_add(argc, argv, prefix) != 0)
364 die(_("interactive add failed"));
366 if (old_index_env && *old_index_env)
367 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
369 unsetenv(INDEX_ENVIRONMENT);
372 read_cache_from(index_lock.filename);
374 commit_style = COMMIT_NORMAL;
375 return index_lock.filename;
379 * Non partial, non as-is commit.
381 * (1) get the real index;
382 * (2) update the_index as necessary;
383 * (3) write the_index out to the real index (still locked);
384 * (4) return the name of the locked index file.
386 * The caller should run hooks on the locked real index, and
387 * (A) if all goes well, commit the real index;
388 * (B) on failure, rollback the real index.
390 if (all || (also && pathspec && *pathspec)) {
391 fd = hold_locked_index(&index_lock, 1);
392 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
393 refresh_cache_or_die(refresh_flags);
394 if (write_cache(fd, active_cache, active_nr) ||
395 close_lock_file(&index_lock))
396 die(_("unable to write new_index file"));
397 commit_style = COMMIT_NORMAL;
398 return index_lock.filename;
404 * (1) return the name of the real index file.
406 * The caller should run hooks on the real index,
407 * and create commit from the_index.
408 * We still need to refresh the index here.
410 if (!pathspec || !*pathspec) {
411 fd = hold_locked_index(&index_lock, 1);
412 refresh_cache_or_die(refresh_flags);
413 if (active_cache_changed) {
414 if (write_cache(fd, active_cache, active_nr) ||
415 commit_locked_index(&index_lock))
416 die(_("unable to write new_index file"));
418 rollback_lock_file(&index_lock);
420 commit_style = COMMIT_AS_IS;
421 return get_index_file();
427 * (0) find the set of affected paths;
428 * (1) get lock on the real index file;
429 * (2) update the_index with the given paths;
430 * (3) write the_index out to the real index (still locked);
431 * (4) get lock on the false index file;
432 * (5) reset the_index from HEAD;
433 * (6) update the_index the same way as (2);
434 * (7) write the_index out to the false index file;
435 * (8) return the name of the false index file (still locked);
437 * The caller should run hooks on the locked false index, and
438 * create commit from it. Then
439 * (A) if all goes well, commit the real index;
440 * (B) on failure, rollback the real index;
441 * In either case, rollback the false index.
443 commit_style = COMMIT_PARTIAL;
445 if (whence != FROM_COMMIT)
446 die(_("cannot do a partial commit during a %s."), whence_s());
448 memset(&partial, 0, sizeof(partial));
449 partial.strdup_strings = 1;
450 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
454 if (read_cache() < 0)
455 die(_("cannot read the index"));
457 fd = hold_locked_index(&index_lock, 1);
458 add_remove_files(&partial);
459 refresh_cache(REFRESH_QUIET);
460 if (write_cache(fd, active_cache, active_nr) ||
461 close_lock_file(&index_lock))
462 die(_("unable to write new_index file"));
464 fd = hold_lock_file_for_update(&false_lock,
465 git_path("next-index-%"PRIuMAX,
466 (uintmax_t) getpid()),
470 add_remove_files(&partial);
471 refresh_cache(REFRESH_QUIET);
473 if (write_cache(fd, active_cache, active_nr) ||
474 close_lock_file(&false_lock))
475 die(_("unable to write temporary index file"));
478 read_cache_from(false_lock.filename);
480 return false_lock.filename;
483 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
486 unsigned char sha1[20];
488 if (s->relative_paths)
493 s->reference = "HEAD^1";
495 s->verbose = verbose;
496 s->index_file = index_file;
499 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
501 wt_status_collect(s);
503 switch (status_format) {
504 case STATUS_FORMAT_SHORT:
505 wt_shortstatus_print(s, null_termination, status_show_branch);
507 case STATUS_FORMAT_PORCELAIN:
508 wt_porcelain_print(s, null_termination);
510 case STATUS_FORMAT_LONG:
515 return s->commitable;
518 static int is_a_merge(const unsigned char *sha1)
520 struct commit *commit = lookup_commit(sha1);
521 if (!commit || parse_commit(commit))
522 die(_("could not parse HEAD commit"));
523 return !!(commit->parents && commit->parents->next);
526 static const char sign_off_header[] = "Signed-off-by: ";
528 static void determine_author_info(struct strbuf *author_ident)
530 char *name, *email, *date;
532 name = getenv("GIT_AUTHOR_NAME");
533 email = getenv("GIT_AUTHOR_EMAIL");
534 date = getenv("GIT_AUTHOR_DATE");
536 if (author_message) {
537 const char *a, *lb, *rb, *eol;
539 a = strstr(author_message_buffer, "\nauthor ");
541 die(_("invalid commit: %s"), author_message);
543 lb = strchrnul(a + strlen("\nauthor "), '<');
544 rb = strchrnul(lb, '>');
545 eol = strchrnul(rb, '\n');
546 if (!*lb || !*rb || !*eol)
547 die(_("invalid commit: %s"), author_message);
549 if (lb == a + strlen("\nauthor "))
550 /* \nauthor <foo@example.com> */
551 name = xcalloc(1, 1);
553 name = xmemdupz(a + strlen("\nauthor "),
555 (a + strlen("\nauthor "))));
556 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
557 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
561 const char *lb = strstr(force_author, " <");
562 const char *rb = strchr(force_author, '>');
565 die(_("malformed --author parameter"));
566 name = xstrndup(force_author, lb - force_author);
567 email = xstrndup(lb + 2, rb - (lb + 2));
572 strbuf_addstr(author_ident, fmt_ident(name, email, date,
573 IDENT_ERROR_ON_NO_NAME));
576 static int ends_rfc2822_footer(struct strbuf *sb)
583 const char *buf = sb->buf;
585 for (i = len - 1; i > 0; i--) {
586 if (hit && buf[i] == '\n')
588 hit = (buf[i] == '\n');
591 while (i < len - 1 && buf[i] == '\n')
594 for (; i < len; i = k) {
595 for (k = i; k < len && buf[k] != '\n'; k++)
599 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
604 for (j = 0; i + j < len; j++) {
617 static char *cut_ident_timestamp_part(char *string)
619 char *ket = strrchr(string, '>');
620 if (!ket || ket[1] != ' ')
621 die(_("Malformed ident string: '%s'"), string);
626 static int prepare_to_commit(const char *index_file, const char *prefix,
628 struct strbuf *author_ident)
631 struct strbuf committer_ident = STRBUF_INIT;
632 int commitable, saved_color_setting;
633 struct strbuf sb = STRBUF_INIT;
635 const char *hook_arg1 = NULL;
636 const char *hook_arg2 = NULL;
639 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
642 if (squash_message) {
644 * Insert the proper subject line before other commit
645 * message options add their content.
647 if (use_message && !strcmp(use_message, squash_message))
648 strbuf_addstr(&sb, "squash! ");
650 struct pretty_print_context ctx = {0};
652 c = lookup_commit_reference_by_name(squash_message);
654 die(_("could not lookup commit %s"), squash_message);
655 ctx.output_encoding = get_commit_output_encoding();
656 format_commit_message(c, "squash! %s\n\n", &sb,
662 strbuf_addbuf(&sb, &message);
663 hook_arg1 = "message";
664 } else if (logfile && !strcmp(logfile, "-")) {
666 fprintf(stderr, _("(reading log message from standard input)\n"));
667 if (strbuf_read(&sb, 0, 0) < 0)
668 die_errno(_("could not read log from standard input"));
669 hook_arg1 = "message";
670 } else if (logfile) {
671 if (strbuf_read_file(&sb, logfile, 0) < 0)
672 die_errno(_("could not read log file '%s'"),
674 hook_arg1 = "message";
675 } else if (use_message) {
676 buffer = strstr(use_message_buffer, "\n\n");
677 if (!buffer || buffer[2] == '\0')
678 die(_("commit has empty message"));
679 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
680 hook_arg1 = "commit";
681 hook_arg2 = use_message;
682 } else if (fixup_message) {
683 struct pretty_print_context ctx = {0};
684 struct commit *commit;
685 commit = lookup_commit_reference_by_name(fixup_message);
687 die(_("could not lookup commit %s"), fixup_message);
688 ctx.output_encoding = get_commit_output_encoding();
689 format_commit_message(commit, "fixup! %s\n\n",
691 hook_arg1 = "message";
692 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
693 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
694 die_errno(_("could not read MERGE_MSG"));
696 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
697 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
698 die_errno(_("could not read SQUASH_MSG"));
699 hook_arg1 = "squash";
700 } else if (template_file) {
701 if (strbuf_read_file(&sb, template_file, 0) < 0)
702 die_errno(_("could not read '%s'"), template_file);
703 hook_arg1 = "template";
707 * The remaining cases don't modify the template message, but
708 * just set the argument(s) to the prepare-commit-msg hook.
710 else if (whence == FROM_MERGE)
712 else if (whence == FROM_CHERRY_PICK) {
713 hook_arg1 = "commit";
714 hook_arg2 = "CHERRY_PICK_HEAD";
717 if (squash_message) {
719 * If squash_commit was used for the commit subject,
720 * then we're possibly hijacking other commit log options.
721 * Reset the hook args to tell the real story.
723 hook_arg1 = "message";
727 s->fp = fopen(git_path(commit_editmsg), "w");
729 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
731 if (cleanup_mode != CLEANUP_NONE)
735 struct strbuf sob = STRBUF_INIT;
738 strbuf_addstr(&sob, sign_off_header);
739 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
740 getenv("GIT_COMMITTER_EMAIL")));
741 strbuf_addch(&sob, '\n');
742 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
744 if (prefixcmp(sb.buf + i, sob.buf)) {
745 if (!i || !ends_rfc2822_footer(&sb))
746 strbuf_addch(&sb, '\n');
747 strbuf_addbuf(&sb, &sob);
749 strbuf_release(&sob);
752 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
753 die_errno(_("could not write commit template"));
757 /* This checks and barfs if author is badly specified */
758 determine_author_info(author_ident);
760 /* This checks if committer ident is explicitly given */
761 strbuf_addstr(&committer_ident, git_committer_info(0));
762 if (use_editor && include_status) {
763 char *ai_tmp, *ci_tmp;
764 if (whence != FROM_COMMIT)
765 status_printf_ln(s, GIT_COLOR_NORMAL,
767 "It looks like you may be committing a %s.\n"
768 "If this is not correct, please remove the file\n"
773 git_path(whence == FROM_MERGE
775 : "CHERRY_PICK_HEAD"));
777 fprintf(s->fp, "\n");
778 status_printf(s, GIT_COLOR_NORMAL,
779 _("Please enter the commit message for your changes."));
780 if (cleanup_mode == CLEANUP_ALL)
781 status_printf_more(s, GIT_COLOR_NORMAL,
782 _(" Lines starting\n"
783 "with '#' will be ignored, and an empty"
784 " message aborts the commit.\n"));
785 else /* CLEANUP_SPACE, that is. */
786 status_printf_more(s, GIT_COLOR_NORMAL,
787 _(" Lines starting\n"
788 "with '#' will be kept; you may remove them"
789 " yourself if you want to.\n"
790 "An empty message aborts the commit.\n"));
791 if (only_include_assumed)
792 status_printf_ln(s, GIT_COLOR_NORMAL,
793 "%s", only_include_assumed);
795 ai_tmp = cut_ident_timestamp_part(author_ident->buf);
796 ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
797 if (strcmp(author_ident->buf, committer_ident.buf))
798 status_printf_ln(s, GIT_COLOR_NORMAL,
801 ident_shown++ ? "" : "\n",
804 if (!user_ident_sufficiently_given())
805 status_printf_ln(s, GIT_COLOR_NORMAL,
808 ident_shown++ ? "" : "\n",
809 committer_ident.buf);
812 status_printf_ln(s, GIT_COLOR_NORMAL, "");
814 saved_color_setting = s->use_color;
816 commitable = run_status(s->fp, index_file, prefix, 1, s);
817 s->use_color = saved_color_setting;
822 unsigned char sha1[20];
823 const char *parent = "HEAD";
825 if (!active_nr && read_cache() < 0)
826 die(_("Cannot read index"));
831 if (get_sha1(parent, sha1))
832 commitable = !!active_nr;
834 commitable = index_differs_from(parent, 0);
836 strbuf_release(&committer_ident);
841 * Reject an attempt to record a non-merge empty commit without
842 * explicit --allow-empty. In the cherry-pick case, it may be
843 * empty due to conflict resolution, which the user should okay.
845 if (!commitable && whence != FROM_MERGE && !allow_empty &&
846 !(amend && is_a_merge(head_sha1))) {
847 run_status(stdout, index_file, prefix, 0, s);
849 fputs(_(empty_amend_advice), stderr);
850 else if (whence == FROM_CHERRY_PICK)
851 fputs(_(empty_cherry_pick_advice), stderr);
856 * Re-read the index as pre-commit hook could have updated it,
857 * and write it out as a tree. We must do this before we invoke
858 * the editor and after we invoke run_status above.
861 read_cache_from(index_file);
862 if (!active_cache_tree)
863 active_cache_tree = cache_tree();
864 if (cache_tree_update(active_cache_tree,
865 active_cache, active_nr, 0, 0) < 0) {
866 error(_("Error building trees"));
870 if (run_hook(index_file, "prepare-commit-msg",
871 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
875 char index[PATH_MAX];
876 const char *env[2] = { NULL };
878 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
879 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
881 _("Please supply the message using either -m or -F option.\n"));
887 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
895 * Find out if the message in the strbuf contains only whitespace and
896 * Signed-off-by lines.
898 static int message_is_empty(struct strbuf *sb)
900 struct strbuf tmpl = STRBUF_INIT;
902 int eol, i, start = 0;
904 if (cleanup_mode == CLEANUP_NONE && sb->len)
907 /* See if the template is just a prefix of the message. */
908 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
909 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
910 if (start + tmpl.len <= sb->len &&
911 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
914 strbuf_release(&tmpl);
916 /* Check if the rest is just whitespace and Signed-of-by's. */
917 for (i = start; i < sb->len; i++) {
918 nl = memchr(sb->buf + i, '\n', sb->len - i);
924 if (strlen(sign_off_header) <= eol - i &&
925 !prefixcmp(sb->buf + i, sign_off_header)) {
930 if (!isspace(sb->buf[i++]))
937 static const char *find_author_by_nickname(const char *name)
939 struct rev_info revs;
940 struct commit *commit;
941 struct strbuf buf = STRBUF_INIT;
945 init_revisions(&revs, NULL);
946 strbuf_addf(&buf, "--author=%s", name);
951 setup_revisions(ac, av, &revs, NULL);
952 prepare_revision_walk(&revs);
953 commit = get_revision(&revs);
955 struct pretty_print_context ctx = {0};
956 ctx.date_mode = DATE_NORMAL;
957 strbuf_release(&buf);
958 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
959 return strbuf_detach(&buf, NULL);
961 die(_("No existing author found with '%s'"), name);
965 static void handle_untracked_files_arg(struct wt_status *s)
967 if (!untracked_files_arg)
968 ; /* default already initialized */
969 else if (!strcmp(untracked_files_arg, "no"))
970 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
971 else if (!strcmp(untracked_files_arg, "normal"))
972 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
973 else if (!strcmp(untracked_files_arg, "all"))
974 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
976 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
979 static const char *read_commit_message(const char *name)
981 const char *out_enc, *out;
982 struct commit *commit;
984 commit = lookup_commit_reference_by_name(name);
986 die(_("could not lookup commit %s"), name);
987 out_enc = get_commit_output_encoding();
988 out = logmsg_reencode(commit, out_enc);
991 * If we failed to reencode the buffer, just copy it
992 * byte for byte so the user can try to fix it up.
993 * This also handles the case where input and output
994 * encodings are identical.
997 out = xstrdup(commit->buffer);
1001 static int parse_and_validate_options(int argc, const char *argv[],
1002 const char * const usage[],
1004 struct wt_status *s)
1008 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
1011 if (force_author && !strchr(force_author, '>'))
1012 force_author = find_author_by_nickname(force_author);
1014 if (force_author && renew_authorship)
1015 die(_("Using both --reset-author and --author does not make sense"));
1017 if (logfile || message.len || use_message || fixup_message)
1022 setenv("GIT_EDITOR", ":", 1);
1024 if (get_sha1("HEAD", head_sha1))
1027 /* Sanity check options */
1028 if (amend && initial_commit)
1029 die(_("You have nothing to amend."));
1030 if (amend && whence != FROM_COMMIT)
1031 die(_("You are in the middle of a %s -- cannot amend."), whence_s());
1032 if (fixup_message && squash_message)
1033 die(_("Options --squash and --fixup cannot be used together"));
1043 die(_("Only one of -c/-C/-F/--fixup can be used."));
1044 if (message.len && f > 0)
1045 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1047 use_message = edit_message;
1048 if (amend && !use_message && !fixup_message)
1049 use_message = "HEAD";
1050 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1051 die(_("--reset-author can be used only with -C, -c or --amend."));
1053 use_message_buffer = read_commit_message(use_message);
1054 if (!renew_authorship) {
1055 author_message = use_message;
1056 author_message_buffer = use_message_buffer;
1059 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1060 author_message = "CHERRY_PICK_HEAD";
1061 author_message_buffer = read_commit_message(author_message);
1064 if (!!also + !!only + !!all + !!interactive > 1)
1065 die(_("Only one of --include/--only/--all/--interactive can be used."));
1066 if (argc == 0 && (also || (only && !amend)))
1067 die(_("No paths with --include/--only does not make sense."));
1068 if (argc == 0 && only && amend)
1069 only_include_assumed = _("Clever... amending the last one with dirty index.");
1070 if (argc > 0 && !also && !only)
1071 only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1072 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1073 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1074 else if (!strcmp(cleanup_arg, "verbatim"))
1075 cleanup_mode = CLEANUP_NONE;
1076 else if (!strcmp(cleanup_arg, "whitespace"))
1077 cleanup_mode = CLEANUP_SPACE;
1078 else if (!strcmp(cleanup_arg, "strip"))
1079 cleanup_mode = CLEANUP_ALL;
1081 die(_("Invalid cleanup mode %s"), cleanup_arg);
1083 handle_untracked_files_arg(s);
1085 if (all && argc > 0)
1086 die(_("Paths with -a does not make sense."));
1087 else if (interactive && argc > 0)
1088 die(_("Paths with --interactive does not make sense."));
1090 if (null_termination && status_format == STATUS_FORMAT_LONG)
1091 status_format = STATUS_FORMAT_PORCELAIN;
1092 if (status_format != STATUS_FORMAT_LONG)
1098 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1099 struct wt_status *s)
1102 const char *index_file;
1104 index_file = prepare_index(argc, argv, prefix, 1);
1105 commitable = run_status(stdout, index_file, prefix, 0, s);
1106 rollback_index_files();
1108 return commitable ? 0 : 1;
1111 static int parse_status_slot(const char *var, int offset)
1113 if (!strcasecmp(var+offset, "header"))
1114 return WT_STATUS_HEADER;
1115 if (!strcasecmp(var+offset, "branch"))
1116 return WT_STATUS_ONBRANCH;
1117 if (!strcasecmp(var+offset, "updated")
1118 || !strcasecmp(var+offset, "added"))
1119 return WT_STATUS_UPDATED;
1120 if (!strcasecmp(var+offset, "changed"))
1121 return WT_STATUS_CHANGED;
1122 if (!strcasecmp(var+offset, "untracked"))
1123 return WT_STATUS_UNTRACKED;
1124 if (!strcasecmp(var+offset, "nobranch"))
1125 return WT_STATUS_NOBRANCH;
1126 if (!strcasecmp(var+offset, "unmerged"))
1127 return WT_STATUS_UNMERGED;
1131 static int git_status_config(const char *k, const char *v, void *cb)
1133 struct wt_status *s = cb;
1135 if (!strcmp(k, "status.submodulesummary")) {
1137 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1138 if (is_bool && s->submodule_summary)
1139 s->submodule_summary = -1;
1142 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1143 s->use_color = git_config_colorbool(k, v, -1);
1146 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1147 int slot = parse_status_slot(k, 13);
1151 return config_error_nonbool(k);
1152 color_parse(v, k, s->color_palette[slot]);
1155 if (!strcmp(k, "status.relativepaths")) {
1156 s->relative_paths = git_config_bool(k, v);
1159 if (!strcmp(k, "status.showuntrackedfiles")) {
1161 return config_error_nonbool(k);
1162 else if (!strcmp(v, "no"))
1163 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1164 else if (!strcmp(v, "normal"))
1165 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1166 else if (!strcmp(v, "all"))
1167 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1169 return error(_("Invalid untracked files mode '%s'"), v);
1172 return git_diff_ui_config(k, v, NULL);
1175 int cmd_status(int argc, const char **argv, const char *prefix)
1179 unsigned char sha1[20];
1180 static struct option builtin_status_options[] = {
1181 OPT__VERBOSE(&verbose, "be verbose"),
1182 OPT_SET_INT('s', "short", &status_format,
1183 "show status concisely", STATUS_FORMAT_SHORT),
1184 OPT_BOOLEAN('b', "branch", &status_show_branch,
1185 "show branch information"),
1186 OPT_SET_INT(0, "porcelain", &status_format,
1187 "machine-readable output",
1188 STATUS_FORMAT_PORCELAIN),
1189 OPT_BOOLEAN('z', "null", &null_termination,
1190 "terminate entries with NUL"),
1191 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1193 "show untracked files, optional modes: all, normal, no. (Default: all)",
1194 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1195 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1196 "show ignored files"),
1197 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, "when",
1198 "ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)",
1199 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1203 if (argc == 2 && !strcmp(argv[1], "-h"))
1204 usage_with_options(builtin_status_usage, builtin_status_options);
1206 if (null_termination && status_format == STATUS_FORMAT_LONG)
1207 status_format = STATUS_FORMAT_PORCELAIN;
1209 wt_status_prepare(&s);
1210 gitmodules_config();
1211 git_config(git_status_config, &s);
1212 determine_whence(&s);
1213 argc = parse_options(argc, argv, prefix,
1214 builtin_status_options,
1215 builtin_status_usage, 0);
1216 handle_untracked_files_arg(&s);
1217 if (show_ignored_in_status)
1218 s.show_ignored_files = 1;
1220 s.pathspec = get_pathspec(prefix, argv);
1222 read_cache_preload(s.pathspec);
1223 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1225 fd = hold_locked_index(&index_lock, 0);
1227 update_index_if_able(&the_index, &index_lock);
1229 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1230 s.ignore_submodule_arg = ignore_submodule_arg;
1231 wt_status_collect(&s);
1233 if (s.relative_paths)
1235 if (s.use_color == -1)
1236 s.use_color = git_use_color_default;
1237 if (diff_use_color_default == -1)
1238 diff_use_color_default = git_use_color_default;
1240 switch (status_format) {
1241 case STATUS_FORMAT_SHORT:
1242 wt_shortstatus_print(&s, null_termination, status_show_branch);
1244 case STATUS_FORMAT_PORCELAIN:
1245 wt_porcelain_print(&s, null_termination);
1247 case STATUS_FORMAT_LONG:
1248 s.verbose = verbose;
1249 s.ignore_submodule_arg = ignore_submodule_arg;
1250 wt_status_print(&s);
1256 static void print_summary(const char *prefix, const unsigned char *sha1)
1258 struct rev_info rev;
1259 struct commit *commit;
1260 struct strbuf format = STRBUF_INIT;
1261 unsigned char junk_sha1[20];
1262 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1263 struct pretty_print_context pctx = {0};
1264 struct strbuf author_ident = STRBUF_INIT;
1265 struct strbuf committer_ident = STRBUF_INIT;
1267 commit = lookup_commit(sha1);
1269 die(_("couldn't look up newly created commit"));
1270 if (!commit || parse_commit(commit))
1271 die(_("could not parse newly created commit"));
1273 strbuf_addstr(&format, "format:%h] %s");
1275 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1276 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1277 if (strbuf_cmp(&author_ident, &committer_ident)) {
1278 strbuf_addstr(&format, "\n Author: ");
1279 strbuf_addbuf_percentquote(&format, &author_ident);
1281 if (!user_ident_sufficiently_given()) {
1282 strbuf_addstr(&format, "\n Committer: ");
1283 strbuf_addbuf_percentquote(&format, &committer_ident);
1284 if (advice_implicit_identity) {
1285 strbuf_addch(&format, '\n');
1286 strbuf_addstr(&format, _(implicit_ident_advice));
1289 strbuf_release(&author_ident);
1290 strbuf_release(&committer_ident);
1292 init_revisions(&rev, prefix);
1293 setup_revisions(0, NULL, &rev, NULL);
1296 rev.diffopt.output_format =
1297 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1299 rev.verbose_header = 1;
1300 rev.show_root_diff = 1;
1301 get_commit_format(format.buf, &rev);
1302 rev.always_show_header = 0;
1303 rev.diffopt.detect_rename = 1;
1304 rev.diffopt.break_opt = 0;
1305 diff_setup_done(&rev.diffopt);
1308 !prefixcmp(head, "refs/heads/") ?
1310 !strcmp(head, "HEAD") ?
1311 _("detached HEAD") :
1313 initial_commit ? _(" (root-commit)") : "");
1315 if (!log_tree_commit(&rev, commit)) {
1316 rev.always_show_header = 1;
1317 rev.use_terminator = 1;
1318 log_tree_commit(&rev, commit);
1321 strbuf_release(&format);
1324 static int git_commit_config(const char *k, const char *v, void *cb)
1326 struct wt_status *s = cb;
1328 if (!strcmp(k, "commit.template"))
1329 return git_config_pathname(&template_file, k, v);
1330 if (!strcmp(k, "commit.status")) {
1331 include_status = git_config_bool(k, v);
1335 return git_status_config(k, v, s);
1338 static const char post_rewrite_hook[] = "hooks/post-rewrite";
1340 static int run_rewrite_hook(const unsigned char *oldsha1,
1341 const unsigned char *newsha1)
1343 /* oldsha1 SP newsha1 LF NUL */
1344 static char buf[2*40 + 3];
1345 struct child_process proc;
1346 const char *argv[3];
1350 if (access(git_path(post_rewrite_hook), X_OK) < 0)
1353 argv[0] = git_path(post_rewrite_hook);
1357 memset(&proc, 0, sizeof(proc));
1360 proc.stdout_to_stderr = 1;
1362 code = start_command(&proc);
1365 n = snprintf(buf, sizeof(buf), "%s %s\n",
1366 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1367 write_in_full(proc.in, buf, n);
1369 return finish_command(&proc);
1372 int cmd_commit(int argc, const char **argv, const char *prefix)
1374 struct strbuf sb = STRBUF_INIT;
1375 struct strbuf author_ident = STRBUF_INIT;
1376 const char *index_file, *reflog_msg;
1378 unsigned char commit_sha1[20];
1379 struct ref_lock *ref_lock;
1380 struct commit_list *parents = NULL, **pptr = &parents;
1381 struct stat statbuf;
1382 int allow_fast_forward = 1;
1385 if (argc == 2 && !strcmp(argv[1], "-h"))
1386 usage_with_options(builtin_commit_usage, builtin_commit_options);
1388 wt_status_prepare(&s);
1389 git_config(git_commit_config, &s);
1390 determine_whence(&s);
1392 if (s.use_color == -1)
1393 s.use_color = git_use_color_default;
1394 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1397 if (diff_use_color_default == -1)
1398 diff_use_color_default = git_use_color_default;
1399 return dry_run_commit(argc, argv, prefix, &s);
1401 index_file = prepare_index(argc, argv, prefix, 0);
1403 /* Set up everything for writing the commit object. This includes
1404 running hooks, writing the trees, and interacting with the user. */
1405 if (!prepare_to_commit(index_file, prefix, &s, &author_ident)) {
1406 rollback_index_files();
1410 /* Determine parents */
1411 reflog_msg = getenv("GIT_REFLOG_ACTION");
1412 if (initial_commit) {
1414 reflog_msg = "commit (initial)";
1416 struct commit_list *c;
1417 struct commit *commit;
1420 reflog_msg = "commit (amend)";
1421 commit = lookup_commit(head_sha1);
1422 if (!commit || parse_commit(commit))
1423 die(_("could not parse HEAD commit"));
1425 for (c = commit->parents; c; c = c->next)
1426 pptr = &commit_list_insert(c->item, pptr)->next;
1427 } else if (whence == FROM_MERGE) {
1428 struct strbuf m = STRBUF_INIT;
1432 reflog_msg = "commit (merge)";
1433 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1434 fp = fopen(git_path("MERGE_HEAD"), "r");
1436 die_errno(_("could not open '%s' for reading"),
1437 git_path("MERGE_HEAD"));
1438 while (strbuf_getline(&m, fp, '\n') != EOF) {
1439 unsigned char sha1[20];
1440 if (get_sha1_hex(m.buf, sha1) < 0)
1441 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1442 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1446 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1447 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1448 die_errno(_("could not read MERGE_MODE"));
1449 if (!strcmp(sb.buf, "no-ff"))
1450 allow_fast_forward = 0;
1452 if (allow_fast_forward)
1453 parents = reduce_heads(parents);
1456 reflog_msg = (whence == FROM_CHERRY_PICK)
1457 ? "commit (cherry-pick)"
1459 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1462 /* Finally, get the commit message */
1464 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1465 int saved_errno = errno;
1466 rollback_index_files();
1467 die(_("could not read commit message: %s"), strerror(saved_errno));
1470 /* Truncate the message just before the diff, if any. */
1472 p = strstr(sb.buf, "\ndiff --git ");
1474 strbuf_setlen(&sb, p - sb.buf + 1);
1477 if (cleanup_mode != CLEANUP_NONE)
1478 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1479 if (message_is_empty(&sb) && !allow_empty_message) {
1480 rollback_index_files();
1481 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1485 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1486 author_ident.buf)) {
1487 rollback_index_files();
1488 die(_("failed to write commit object"));
1490 strbuf_release(&author_ident);
1492 ref_lock = lock_any_ref_for_update("HEAD",
1493 initial_commit ? NULL : head_sha1,
1496 nl = strchr(sb.buf, '\n');
1498 strbuf_setlen(&sb, nl + 1 - sb.buf);
1500 strbuf_addch(&sb, '\n');
1501 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1502 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1505 rollback_index_files();
1506 die(_("cannot lock HEAD ref"));
1508 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1509 rollback_index_files();
1510 die(_("cannot update HEAD ref"));
1513 unlink(git_path("CHERRY_PICK_HEAD"));
1514 unlink(git_path("MERGE_HEAD"));
1515 unlink(git_path("MERGE_MSG"));
1516 unlink(git_path("MERGE_MODE"));
1517 unlink(git_path("SQUASH_MSG"));
1519 if (commit_index_files())
1520 die (_("Repository has been updated, but unable to write\n"
1521 "new_index file. Check that disk is not full or quota is\n"
1522 "not exceeded, and then \"git reset HEAD\" to recover."));
1525 run_hook(get_index_file(), "post-commit", NULL);
1526 if (amend && !no_post_rewrite) {
1527 struct notes_rewrite_cfg *cfg;
1528 cfg = init_copy_notes_for_rewrite("amend");
1530 copy_note_for_rewrite(cfg, head_sha1, commit_sha1);
1531 finish_copy_notes_for_rewrite(cfg);
1533 run_rewrite_hook(head_sha1, commit_sha1);
1536 print_summary(prefix, commit_sha1);