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 static const char * const builtin_commit_usage[] = {
32 "git commit [options] [--] <filepattern>...",
36 static const char * const builtin_status_usage[] = {
37 "git status [options] [--] <filepattern>...",
41 static const char implicit_ident_advice[] =
42 N_("Your name and email address were configured automatically based\n"
43 "on your username and hostname. Please check that they are accurate.\n"
44 "You can suppress this message by setting them explicitly:\n"
46 " git config --global user.name \"Your Name\"\n"
47 " git config --global user.email you@example.com\n"
49 "After doing this, you may fix the identity used for this commit with:\n"
51 " git commit --amend --reset-author\n");
53 static const char empty_amend_advice[] =
54 N_("You asked to amend the most recent commit, but doing so would make\n"
55 "it empty. You can repeat your command with --allow-empty, or you can\n"
56 "remove the commit entirely with \"git reset HEAD^\".\n");
58 static const char empty_cherry_pick_advice[] =
59 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
60 "If you wish to commit it anyway, use:\n"
62 " git commit --allow-empty\n"
64 "Otherwise, please use 'git reset'\n");
66 static const char *use_message_buffer;
67 static const char commit_editmsg[] = "COMMIT_EDITMSG";
68 static struct lock_file index_lock; /* real index */
69 static struct lock_file false_lock; /* used only for partial commits */
76 static const char *logfile, *force_author;
77 static const char *template_file;
79 * The _message variables are commit names from which to take
80 * the commit message and/or authorship.
82 static const char *author_message, *author_message_buffer;
83 static char *edit_message, *use_message;
84 static char *fixup_message, *squash_message;
85 static int all, also, interactive, patch_interactive, only, amend, signoff;
86 static int edit_flag = -1; /* unspecified */
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;
90 static char *sign_commit;
93 * The default commit message cleanup mode will remove the lines
94 * beginning with # (shell comments) and leading and trailing
95 * whitespaces (empty lines or containing only whitespaces)
96 * if editor is used, and only the whitespaces if the message
97 * is specified explicitly.
104 static char *cleanup_arg;
106 static enum commit_whence whence;
107 static int use_editor = 1, include_status = 1;
108 static int show_ignored_in_status;
109 static const char *only_include_assumed;
110 static struct strbuf message = STRBUF_INIT;
112 static int null_termination;
116 STATUS_FORMAT_PORCELAIN
117 } status_format = STATUS_FORMAT_LONG;
118 static int status_show_branch;
120 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
122 struct strbuf *buf = opt->value;
124 strbuf_setlen(buf, 0);
126 strbuf_addstr(buf, arg);
127 strbuf_addstr(buf, "\n\n");
132 static struct option builtin_commit_options[] = {
133 OPT__QUIET(&quiet, "suppress summary after successful commit"),
134 OPT__VERBOSE(&verbose, "show diff in commit message template"),
136 OPT_GROUP("Commit message options"),
137 OPT_FILENAME('F', "file", &logfile, "read message from file"),
138 OPT_STRING(0, "author", &force_author, "author", "override author for commit"),
139 OPT_STRING(0, "date", &force_date, "date", "override date for commit"),
140 OPT_CALLBACK('m', "message", &message, "message", "commit message", opt_parse_m),
141 OPT_STRING('c', "reedit-message", &edit_message, "commit", "reuse and edit message from specified commit"),
142 OPT_STRING('C', "reuse-message", &use_message, "commit", "reuse message from specified commit"),
143 OPT_STRING(0, "fixup", &fixup_message, "commit", "use autosquash formatted message to fixup specified commit"),
144 OPT_STRING(0, "squash", &squash_message, "commit", "use autosquash formatted message to squash specified commit"),
145 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C/-c/--amend)"),
146 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
147 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
148 OPT_BOOL('e', "edit", &edit_flag, "force edit of commit"),
149 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
150 OPT_BOOLEAN(0, "status", &include_status, "include status in commit message template"),
151 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, "key id",
152 "GPG sign commit", PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
153 /* end commit message options */
155 OPT_GROUP("Commit contents options"),
156 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
157 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
158 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
159 OPT_BOOLEAN('p', "patch", &patch_interactive, "interactively add changes"),
160 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
161 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
162 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
163 OPT_SET_INT(0, "short", &status_format, "show status concisely",
164 STATUS_FORMAT_SHORT),
165 OPT_BOOLEAN(0, "branch", &status_show_branch, "show branch information"),
166 OPT_SET_INT(0, "porcelain", &status_format,
167 "machine-readable output", STATUS_FORMAT_PORCELAIN),
168 OPT_BOOLEAN('z', "null", &null_termination,
169 "terminate entries with NUL"),
170 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
171 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, "bypass post-rewrite hook"),
172 { 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" },
173 /* end commit contents options */
175 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
176 "ok to record an empty change",
177 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
178 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
179 "ok to record a change with an empty message",
180 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
185 static void determine_whence(struct wt_status *s)
187 if (file_exists(git_path("MERGE_HEAD")))
189 else if (file_exists(git_path("CHERRY_PICK_HEAD")))
190 whence = FROM_CHERRY_PICK;
192 whence = FROM_COMMIT;
197 static void rollback_index_files(void)
199 switch (commit_style) {
201 break; /* nothing to do */
203 rollback_lock_file(&index_lock);
206 rollback_lock_file(&index_lock);
207 rollback_lock_file(&false_lock);
212 static int commit_index_files(void)
216 switch (commit_style) {
218 break; /* nothing to do */
220 err = commit_lock_file(&index_lock);
223 err = commit_lock_file(&index_lock);
224 rollback_lock_file(&false_lock);
232 * Take a union of paths in the index and the named tree (typically, "HEAD"),
233 * and return the paths that match the given pattern in list.
235 static int list_paths(struct string_list *list, const char *with_tree,
236 const char *prefix, const char **pattern)
241 for (i = 0; pattern[i]; i++)
246 char *max_prefix = common_prefix(pattern);
247 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
251 for (i = 0; i < active_nr; i++) {
252 struct cache_entry *ce = active_cache[i];
253 struct string_list_item *item;
255 if (ce->ce_flags & CE_UPDATE)
257 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
259 item = string_list_insert(list, ce->name);
260 if (ce_skip_worktree(ce))
261 item->util = item; /* better a valid pointer than a fake one */
264 return report_path_error(m, pattern, prefix);
267 static void add_remove_files(struct string_list *list)
270 for (i = 0; i < list->nr; i++) {
272 struct string_list_item *p = &(list->items[i]);
274 /* p->util is skip-worktree */
278 if (!lstat(p->string, &st)) {
279 if (add_to_cache(p->string, &st, 0))
280 die(_("updating files failed"));
282 remove_file_from_cache(p->string);
286 static void create_base_index(const struct commit *current_head)
289 struct unpack_trees_options opts;
297 memset(&opts, 0, sizeof(opts));
301 opts.src_index = &the_index;
302 opts.dst_index = &the_index;
304 opts.fn = oneway_merge;
305 tree = parse_tree_indirect(current_head->object.sha1);
307 die(_("failed to unpack HEAD tree object"));
309 init_tree_desc(&t, tree->buffer, tree->size);
310 if (unpack_trees(1, &t, &opts))
311 exit(128); /* We've already reported the error, finish dying */
314 static void refresh_cache_or_die(int refresh_flags)
317 * refresh_flags contains REFRESH_QUIET, so the only errors
318 * are for unmerged entries.
320 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
321 die_resolve_conflict("commit");
324 static char *prepare_index(int argc, const char **argv, const char *prefix,
325 const struct commit *current_head, int is_status)
328 struct string_list partial;
329 const char **pathspec = NULL;
330 char *old_index_env = NULL;
331 int refresh_flags = REFRESH_QUIET;
334 refresh_flags |= REFRESH_UNMERGED;
337 pathspec = get_pathspec(prefix, argv);
339 if (read_cache_preload(pathspec) < 0)
340 die(_("index file corrupt"));
343 fd = hold_locked_index(&index_lock, 1);
345 refresh_cache_or_die(refresh_flags);
347 if (write_cache(fd, active_cache, active_nr) ||
348 close_lock_file(&index_lock))
349 die(_("unable to create temporary index"));
351 old_index_env = getenv(INDEX_ENVIRONMENT);
352 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
354 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
355 die(_("interactive add failed"));
357 if (old_index_env && *old_index_env)
358 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
360 unsetenv(INDEX_ENVIRONMENT);
363 read_cache_from(index_lock.filename);
365 commit_style = COMMIT_NORMAL;
366 return index_lock.filename;
370 * Non partial, non as-is commit.
372 * (1) get the real index;
373 * (2) update the_index as necessary;
374 * (3) write the_index out to the real index (still locked);
375 * (4) return the name of the locked index file.
377 * The caller should run hooks on the locked real index, and
378 * (A) if all goes well, commit the real index;
379 * (B) on failure, rollback the real index.
381 if (all || (also && pathspec && *pathspec)) {
382 fd = hold_locked_index(&index_lock, 1);
383 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
384 refresh_cache_or_die(refresh_flags);
385 update_main_cache_tree(WRITE_TREE_SILENT);
386 if (write_cache(fd, active_cache, active_nr) ||
387 close_lock_file(&index_lock))
388 die(_("unable to write new_index file"));
389 commit_style = COMMIT_NORMAL;
390 return index_lock.filename;
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 (!pathspec || !*pathspec) {
403 fd = hold_locked_index(&index_lock, 1);
404 refresh_cache_or_die(refresh_flags);
405 if (active_cache_changed) {
406 update_main_cache_tree(WRITE_TREE_SILENT);
407 if (write_cache(fd, active_cache, active_nr) ||
408 commit_locked_index(&index_lock))
409 die(_("unable to write new_index file"));
411 rollback_lock_file(&index_lock);
413 commit_style = COMMIT_AS_IS;
414 return get_index_file();
420 * (0) find the set of affected paths;
421 * (1) get lock on the real index file;
422 * (2) update the_index with the given paths;
423 * (3) write the_index out to the real index (still locked);
424 * (4) get lock on the false index file;
425 * (5) reset the_index from HEAD;
426 * (6) update the_index the same way as (2);
427 * (7) write the_index out to the false index file;
428 * (8) return the name of the false index file (still locked);
430 * The caller should run hooks on the locked false index, and
431 * create commit from it. Then
432 * (A) if all goes well, commit the real index;
433 * (B) on failure, rollback the real index;
434 * In either case, rollback the false index.
436 commit_style = COMMIT_PARTIAL;
438 if (whence != FROM_COMMIT) {
439 if (whence == FROM_MERGE)
440 die(_("cannot do a partial commit during a merge."));
441 else if (whence == FROM_CHERRY_PICK)
442 die(_("cannot do a partial commit during a cherry-pick."));
445 memset(&partial, 0, sizeof(partial));
446 partial.strdup_strings = 1;
447 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, pathspec))
451 if (read_cache() < 0)
452 die(_("cannot read the index"));
454 fd = hold_locked_index(&index_lock, 1);
455 add_remove_files(&partial);
456 refresh_cache(REFRESH_QUIET);
457 if (write_cache(fd, active_cache, active_nr) ||
458 close_lock_file(&index_lock))
459 die(_("unable to write new_index file"));
461 fd = hold_lock_file_for_update(&false_lock,
462 git_path("next-index-%"PRIuMAX,
463 (uintmax_t) getpid()),
466 create_base_index(current_head);
467 add_remove_files(&partial);
468 refresh_cache(REFRESH_QUIET);
470 if (write_cache(fd, active_cache, active_nr) ||
471 close_lock_file(&false_lock))
472 die(_("unable to write temporary index file"));
475 read_cache_from(false_lock.filename);
477 return false_lock.filename;
480 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
483 unsigned char sha1[20];
485 if (s->relative_paths)
490 s->reference = "HEAD^1";
492 s->verbose = verbose;
493 s->index_file = index_file;
496 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
498 wt_status_collect(s);
500 switch (status_format) {
501 case STATUS_FORMAT_SHORT:
502 wt_shortstatus_print(s, null_termination, status_show_branch);
504 case STATUS_FORMAT_PORCELAIN:
505 wt_porcelain_print(s, null_termination);
507 case STATUS_FORMAT_LONG:
512 return s->commitable;
515 static int is_a_merge(const struct commit *current_head)
517 return !!(current_head->parents && current_head->parents->next);
520 static const char sign_off_header[] = "Signed-off-by: ";
522 static void export_one(const char *var, const char *s, const char *e, int hack)
524 struct strbuf buf = STRBUF_INIT;
526 strbuf_addch(&buf, hack);
527 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
528 setenv(var, buf.buf, 1);
529 strbuf_release(&buf);
532 static void determine_author_info(struct strbuf *author_ident)
534 char *name, *email, *date;
535 struct ident_split author;
537 name = getenv("GIT_AUTHOR_NAME");
538 email = getenv("GIT_AUTHOR_EMAIL");
539 date = getenv("GIT_AUTHOR_DATE");
541 if (author_message) {
542 const char *a, *lb, *rb, *eol;
545 a = strstr(author_message_buffer, "\nauthor ");
547 die(_("invalid commit: %s"), author_message);
549 lb = strchrnul(a + strlen("\nauthor "), '<');
550 rb = strchrnul(lb, '>');
551 eol = strchrnul(rb, '\n');
552 if (!*lb || !*rb || !*eol)
553 die(_("invalid commit: %s"), author_message);
555 if (lb == a + strlen("\nauthor "))
556 /* \nauthor <foo@example.com> */
557 name = xcalloc(1, 1);
559 name = xmemdupz(a + strlen("\nauthor "),
561 (a + strlen("\nauthor "))));
562 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
563 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
564 len = eol - (rb + strlen("> "));
565 date = xmalloc(len + 2);
567 memcpy(date + 1, rb + strlen("> "), len);
568 date[len + 1] = '\0';
572 const char *lb = strstr(force_author, " <");
573 const char *rb = strchr(force_author, '>');
576 die(_("malformed --author parameter"));
577 name = xstrndup(force_author, lb - force_author);
578 email = xstrndup(lb + 2, rb - (lb + 2));
583 strbuf_addstr(author_ident, fmt_ident(name, email, date,
584 IDENT_ERROR_ON_NO_NAME));
585 if (!split_ident_line(&author, author_ident->buf, author_ident->len)) {
586 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
587 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
588 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
592 static int ends_rfc2822_footer(struct strbuf *sb)
599 const char *buf = sb->buf;
601 for (i = len - 1; i > 0; i--) {
602 if (hit && buf[i] == '\n')
604 hit = (buf[i] == '\n');
607 while (i < len - 1 && buf[i] == '\n')
610 for (; i < len; i = k) {
611 for (k = i; k < len && buf[k] != '\n'; k++)
615 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
620 for (j = 0; i + j < len; j++) {
633 static char *cut_ident_timestamp_part(char *string)
635 char *ket = strrchr(string, '>');
636 if (!ket || ket[1] != ' ')
637 die(_("Malformed ident string: '%s'"), string);
642 static int prepare_to_commit(const char *index_file, const char *prefix,
643 struct commit *current_head,
645 struct strbuf *author_ident)
648 struct strbuf committer_ident = STRBUF_INIT;
649 int commitable, saved_color_setting;
650 struct strbuf sb = STRBUF_INIT;
652 const char *hook_arg1 = NULL;
653 const char *hook_arg2 = NULL;
655 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
657 /* This checks and barfs if author is badly specified */
658 determine_author_info(author_ident);
660 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
663 if (squash_message) {
665 * Insert the proper subject line before other commit
666 * message options add their content.
668 if (use_message && !strcmp(use_message, squash_message))
669 strbuf_addstr(&sb, "squash! ");
671 struct pretty_print_context ctx = {0};
673 c = lookup_commit_reference_by_name(squash_message);
675 die(_("could not lookup commit %s"), squash_message);
676 ctx.output_encoding = get_commit_output_encoding();
677 format_commit_message(c, "squash! %s\n\n", &sb,
683 strbuf_addbuf(&sb, &message);
684 hook_arg1 = "message";
685 } else if (logfile && !strcmp(logfile, "-")) {
687 fprintf(stderr, _("(reading log message from standard input)\n"));
688 if (strbuf_read(&sb, 0, 0) < 0)
689 die_errno(_("could not read log from standard input"));
690 hook_arg1 = "message";
691 } else if (logfile) {
692 if (strbuf_read_file(&sb, logfile, 0) < 0)
693 die_errno(_("could not read log file '%s'"),
695 hook_arg1 = "message";
696 } else if (use_message) {
697 buffer = strstr(use_message_buffer, "\n\n");
698 if (!buffer || buffer[2] == '\0')
699 die(_("commit has empty message"));
700 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
701 hook_arg1 = "commit";
702 hook_arg2 = use_message;
703 } else if (fixup_message) {
704 struct pretty_print_context ctx = {0};
705 struct commit *commit;
706 commit = lookup_commit_reference_by_name(fixup_message);
708 die(_("could not lookup commit %s"), fixup_message);
709 ctx.output_encoding = get_commit_output_encoding();
710 format_commit_message(commit, "fixup! %s\n\n",
712 hook_arg1 = "message";
713 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
714 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
715 die_errno(_("could not read MERGE_MSG"));
717 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
718 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
719 die_errno(_("could not read SQUASH_MSG"));
720 hook_arg1 = "squash";
721 } else if (template_file) {
722 if (strbuf_read_file(&sb, template_file, 0) < 0)
723 die_errno(_("could not read '%s'"), template_file);
724 hook_arg1 = "template";
725 clean_message_contents = 0;
729 * The remaining cases don't modify the template message, but
730 * just set the argument(s) to the prepare-commit-msg hook.
732 else if (whence == FROM_MERGE)
734 else if (whence == FROM_CHERRY_PICK) {
735 hook_arg1 = "commit";
736 hook_arg2 = "CHERRY_PICK_HEAD";
739 if (squash_message) {
741 * If squash_commit was used for the commit subject,
742 * then we're possibly hijacking other commit log options.
743 * Reset the hook args to tell the real story.
745 hook_arg1 = "message";
749 s->fp = fopen(git_path(commit_editmsg), "w");
751 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
753 if (clean_message_contents)
757 struct strbuf sob = STRBUF_INIT;
760 strbuf_addstr(&sob, sign_off_header);
761 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
762 getenv("GIT_COMMITTER_EMAIL")));
763 strbuf_addch(&sob, '\n');
764 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
766 if (prefixcmp(sb.buf + i, sob.buf)) {
767 if (!i || !ends_rfc2822_footer(&sb))
768 strbuf_addch(&sb, '\n');
769 strbuf_addbuf(&sb, &sob);
771 strbuf_release(&sob);
774 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
775 die_errno(_("could not write commit template"));
779 /* This checks if committer ident is explicitly given */
780 strbuf_addstr(&committer_ident, git_committer_info(0));
781 if (use_editor && include_status) {
782 char *ai_tmp, *ci_tmp;
783 if (whence != FROM_COMMIT)
784 status_printf_ln(s, GIT_COLOR_NORMAL,
787 "It looks like you may be committing a merge.\n"
788 "If this is not correct, please remove the file\n"
792 "It looks like you may be committing a cherry-pick.\n"
793 "If this is not correct, please remove the file\n"
796 git_path(whence == FROM_MERGE
798 : "CHERRY_PICK_HEAD"));
800 fprintf(s->fp, "\n");
801 status_printf(s, GIT_COLOR_NORMAL,
802 _("Please enter the commit message for your changes."));
803 if (cleanup_mode == CLEANUP_ALL)
804 status_printf_more(s, GIT_COLOR_NORMAL,
805 _(" Lines starting\n"
806 "with '#' will be ignored, and an empty"
807 " message aborts the commit.\n"));
808 else /* CLEANUP_SPACE, that is. */
809 status_printf_more(s, GIT_COLOR_NORMAL,
810 _(" Lines starting\n"
811 "with '#' will be kept; you may remove them"
812 " yourself if you want to.\n"
813 "An empty message aborts the commit.\n"));
814 if (only_include_assumed)
815 status_printf_ln(s, GIT_COLOR_NORMAL,
816 "%s", only_include_assumed);
818 ai_tmp = cut_ident_timestamp_part(author_ident->buf);
819 ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
820 if (strcmp(author_ident->buf, committer_ident.buf))
821 status_printf_ln(s, GIT_COLOR_NORMAL,
824 ident_shown++ ? "" : "\n",
827 if (!user_ident_sufficiently_given())
828 status_printf_ln(s, GIT_COLOR_NORMAL,
831 ident_shown++ ? "" : "\n",
832 committer_ident.buf);
835 status_printf_ln(s, GIT_COLOR_NORMAL, "");
837 saved_color_setting = s->use_color;
839 commitable = run_status(s->fp, index_file, prefix, 1, s);
840 s->use_color = saved_color_setting;
845 unsigned char sha1[20];
846 const char *parent = "HEAD";
848 if (!active_nr && read_cache() < 0)
849 die(_("Cannot read index"));
854 if (get_sha1(parent, sha1))
855 commitable = !!active_nr;
857 commitable = index_differs_from(parent, 0);
859 strbuf_release(&committer_ident);
864 * Reject an attempt to record a non-merge empty commit without
865 * explicit --allow-empty. In the cherry-pick case, it may be
866 * empty due to conflict resolution, which the user should okay.
868 if (!commitable && whence != FROM_MERGE && !allow_empty &&
869 !(amend && is_a_merge(current_head))) {
870 run_status(stdout, index_file, prefix, 0, s);
872 fputs(_(empty_amend_advice), stderr);
873 else if (whence == FROM_CHERRY_PICK)
874 fputs(_(empty_cherry_pick_advice), stderr);
879 * Re-read the index as pre-commit hook could have updated it,
880 * and write it out as a tree. We must do this before we invoke
881 * the editor and after we invoke run_status above.
884 read_cache_from(index_file);
885 if (update_main_cache_tree(0)) {
886 error(_("Error building trees"));
890 if (run_hook(index_file, "prepare-commit-msg",
891 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
895 char index[PATH_MAX];
896 const char *env[2] = { NULL };
898 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
899 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
901 _("Please supply the message using either -m or -F option.\n"));
907 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
914 static int rest_is_empty(struct strbuf *sb, int start)
919 /* Check if the rest is just whitespace and Signed-of-by's. */
920 for (i = start; i < sb->len; i++) {
921 nl = memchr(sb->buf + i, '\n', sb->len - i);
927 if (strlen(sign_off_header) <= eol - i &&
928 !prefixcmp(sb->buf + i, sign_off_header)) {
933 if (!isspace(sb->buf[i++]))
941 * Find out if the message in the strbuf contains only whitespace and
942 * Signed-off-by lines.
944 static int message_is_empty(struct strbuf *sb)
946 if (cleanup_mode == CLEANUP_NONE && sb->len)
948 return rest_is_empty(sb, 0);
952 * See if the user edited the message in the editor or left what
953 * was in the template intact
955 static int template_untouched(struct strbuf *sb)
957 struct strbuf tmpl = STRBUF_INIT;
960 if (cleanup_mode == CLEANUP_NONE && sb->len)
963 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
966 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
967 start = (char *)skip_prefix(sb->buf, tmpl.buf);
970 strbuf_release(&tmpl);
971 return rest_is_empty(sb, start - sb->buf);
974 static const char *find_author_by_nickname(const char *name)
976 struct rev_info revs;
977 struct commit *commit;
978 struct strbuf buf = STRBUF_INIT;
982 init_revisions(&revs, NULL);
983 strbuf_addf(&buf, "--author=%s", name);
988 setup_revisions(ac, av, &revs, NULL);
989 prepare_revision_walk(&revs);
990 commit = get_revision(&revs);
992 struct pretty_print_context ctx = {0};
993 ctx.date_mode = DATE_NORMAL;
994 strbuf_release(&buf);
995 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
996 return strbuf_detach(&buf, NULL);
998 die(_("No existing author found with '%s'"), name);
1002 static void handle_untracked_files_arg(struct wt_status *s)
1004 if (!untracked_files_arg)
1005 ; /* default already initialized */
1006 else if (!strcmp(untracked_files_arg, "no"))
1007 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1008 else if (!strcmp(untracked_files_arg, "normal"))
1009 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1010 else if (!strcmp(untracked_files_arg, "all"))
1011 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1013 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1016 static const char *read_commit_message(const char *name)
1018 const char *out_enc, *out;
1019 struct commit *commit;
1021 commit = lookup_commit_reference_by_name(name);
1023 die(_("could not lookup commit %s"), name);
1024 out_enc = get_commit_output_encoding();
1025 out = logmsg_reencode(commit, out_enc);
1028 * If we failed to reencode the buffer, just copy it
1029 * byte for byte so the user can try to fix it up.
1030 * This also handles the case where input and output
1031 * encodings are identical.
1034 out = xstrdup(commit->buffer);
1038 static int parse_and_validate_options(int argc, const char *argv[],
1039 const char * const usage[],
1041 struct commit *current_head,
1042 struct wt_status *s)
1046 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
1049 if (force_author && !strchr(force_author, '>'))
1050 force_author = find_author_by_nickname(force_author);
1052 if (force_author && renew_authorship)
1053 die(_("Using both --reset-author and --author does not make sense"));
1055 if (logfile || message.len || use_message || fixup_message)
1058 use_editor = edit_flag;
1060 setenv("GIT_EDITOR", ":", 1);
1062 /* Sanity check options */
1063 if (amend && !current_head)
1064 die(_("You have nothing to amend."));
1065 if (amend && whence != FROM_COMMIT) {
1066 if (whence == FROM_MERGE)
1067 die(_("You are in the middle of a merge -- cannot amend."));
1068 else if (whence == FROM_CHERRY_PICK)
1069 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1071 if (fixup_message && squash_message)
1072 die(_("Options --squash and --fixup cannot be used together"));
1082 die(_("Only one of -c/-C/-F/--fixup can be used."));
1083 if (message.len && f > 0)
1084 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1085 if (f || message.len)
1086 template_file = NULL;
1088 use_message = edit_message;
1089 if (amend && !use_message && !fixup_message)
1090 use_message = "HEAD";
1091 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1092 die(_("--reset-author can be used only with -C, -c or --amend."));
1094 use_message_buffer = read_commit_message(use_message);
1095 if (!renew_authorship) {
1096 author_message = use_message;
1097 author_message_buffer = use_message_buffer;
1100 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1101 author_message = "CHERRY_PICK_HEAD";
1102 author_message_buffer = read_commit_message(author_message);
1105 if (patch_interactive)
1108 if (!!also + !!only + !!all + !!interactive > 1)
1109 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1110 if (argc == 0 && (also || (only && !amend)))
1111 die(_("No paths with --include/--only does not make sense."));
1112 if (argc == 0 && only && amend)
1113 only_include_assumed = _("Clever... amending the last one with dirty index.");
1114 if (argc > 0 && !also && !only)
1115 only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1116 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1117 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1118 else if (!strcmp(cleanup_arg, "verbatim"))
1119 cleanup_mode = CLEANUP_NONE;
1120 else if (!strcmp(cleanup_arg, "whitespace"))
1121 cleanup_mode = CLEANUP_SPACE;
1122 else if (!strcmp(cleanup_arg, "strip"))
1123 cleanup_mode = CLEANUP_ALL;
1125 die(_("Invalid cleanup mode %s"), cleanup_arg);
1127 handle_untracked_files_arg(s);
1129 if (all && argc > 0)
1130 die(_("Paths with -a does not make sense."));
1132 if (null_termination && status_format == STATUS_FORMAT_LONG)
1133 status_format = STATUS_FORMAT_PORCELAIN;
1134 if (status_format != STATUS_FORMAT_LONG)
1140 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1141 const struct commit *current_head, struct wt_status *s)
1144 const char *index_file;
1146 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1147 commitable = run_status(stdout, index_file, prefix, 0, s);
1148 rollback_index_files();
1150 return commitable ? 0 : 1;
1153 static int parse_status_slot(const char *var, int offset)
1155 if (!strcasecmp(var+offset, "header"))
1156 return WT_STATUS_HEADER;
1157 if (!strcasecmp(var+offset, "branch"))
1158 return WT_STATUS_ONBRANCH;
1159 if (!strcasecmp(var+offset, "updated")
1160 || !strcasecmp(var+offset, "added"))
1161 return WT_STATUS_UPDATED;
1162 if (!strcasecmp(var+offset, "changed"))
1163 return WT_STATUS_CHANGED;
1164 if (!strcasecmp(var+offset, "untracked"))
1165 return WT_STATUS_UNTRACKED;
1166 if (!strcasecmp(var+offset, "nobranch"))
1167 return WT_STATUS_NOBRANCH;
1168 if (!strcasecmp(var+offset, "unmerged"))
1169 return WT_STATUS_UNMERGED;
1173 static int git_status_config(const char *k, const char *v, void *cb)
1175 struct wt_status *s = cb;
1177 if (!strcmp(k, "status.submodulesummary")) {
1179 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1180 if (is_bool && s->submodule_summary)
1181 s->submodule_summary = -1;
1184 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1185 s->use_color = git_config_colorbool(k, v);
1188 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1189 int slot = parse_status_slot(k, 13);
1193 return config_error_nonbool(k);
1194 color_parse(v, k, s->color_palette[slot]);
1197 if (!strcmp(k, "status.relativepaths")) {
1198 s->relative_paths = git_config_bool(k, v);
1201 if (!strcmp(k, "status.showuntrackedfiles")) {
1203 return config_error_nonbool(k);
1204 else if (!strcmp(v, "no"))
1205 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1206 else if (!strcmp(v, "normal"))
1207 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1208 else if (!strcmp(v, "all"))
1209 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1211 return error(_("Invalid untracked files mode '%s'"), v);
1214 return git_diff_ui_config(k, v, NULL);
1217 int cmd_status(int argc, const char **argv, const char *prefix)
1221 unsigned char sha1[20];
1222 static struct option builtin_status_options[] = {
1223 OPT__VERBOSE(&verbose, "be verbose"),
1224 OPT_SET_INT('s', "short", &status_format,
1225 "show status concisely", STATUS_FORMAT_SHORT),
1226 OPT_BOOLEAN('b', "branch", &status_show_branch,
1227 "show branch information"),
1228 OPT_SET_INT(0, "porcelain", &status_format,
1229 "machine-readable output",
1230 STATUS_FORMAT_PORCELAIN),
1231 OPT_BOOLEAN('z', "null", &null_termination,
1232 "terminate entries with NUL"),
1233 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1235 "show untracked files, optional modes: all, normal, no. (Default: all)",
1236 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1237 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1238 "show ignored files"),
1239 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, "when",
1240 "ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)",
1241 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1245 if (argc == 2 && !strcmp(argv[1], "-h"))
1246 usage_with_options(builtin_status_usage, builtin_status_options);
1248 wt_status_prepare(&s);
1249 gitmodules_config();
1250 git_config(git_status_config, &s);
1251 determine_whence(&s);
1252 argc = parse_options(argc, argv, prefix,
1253 builtin_status_options,
1254 builtin_status_usage, 0);
1256 if (null_termination && status_format == STATUS_FORMAT_LONG)
1257 status_format = STATUS_FORMAT_PORCELAIN;
1259 handle_untracked_files_arg(&s);
1260 if (show_ignored_in_status)
1261 s.show_ignored_files = 1;
1263 s.pathspec = get_pathspec(prefix, argv);
1265 read_cache_preload(s.pathspec);
1266 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1268 fd = hold_locked_index(&index_lock, 0);
1270 update_index_if_able(&the_index, &index_lock);
1272 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1273 s.ignore_submodule_arg = ignore_submodule_arg;
1274 wt_status_collect(&s);
1276 if (s.relative_paths)
1279 switch (status_format) {
1280 case STATUS_FORMAT_SHORT:
1281 wt_shortstatus_print(&s, null_termination, status_show_branch);
1283 case STATUS_FORMAT_PORCELAIN:
1284 wt_porcelain_print(&s, null_termination);
1286 case STATUS_FORMAT_LONG:
1287 s.verbose = verbose;
1288 s.ignore_submodule_arg = ignore_submodule_arg;
1289 wt_status_print(&s);
1295 static void print_summary(const char *prefix, const unsigned char *sha1,
1298 struct rev_info rev;
1299 struct commit *commit;
1300 struct strbuf format = STRBUF_INIT;
1301 unsigned char junk_sha1[20];
1303 struct pretty_print_context pctx = {0};
1304 struct strbuf author_ident = STRBUF_INIT;
1305 struct strbuf committer_ident = STRBUF_INIT;
1307 commit = lookup_commit(sha1);
1309 die(_("couldn't look up newly created commit"));
1310 if (!commit || parse_commit(commit))
1311 die(_("could not parse newly created commit"));
1313 strbuf_addstr(&format, "format:%h] %s");
1315 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1316 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1317 if (strbuf_cmp(&author_ident, &committer_ident)) {
1318 strbuf_addstr(&format, "\n Author: ");
1319 strbuf_addbuf_percentquote(&format, &author_ident);
1321 if (!user_ident_sufficiently_given()) {
1322 strbuf_addstr(&format, "\n Committer: ");
1323 strbuf_addbuf_percentquote(&format, &committer_ident);
1324 if (advice_implicit_identity) {
1325 strbuf_addch(&format, '\n');
1326 strbuf_addstr(&format, _(implicit_ident_advice));
1329 strbuf_release(&author_ident);
1330 strbuf_release(&committer_ident);
1332 init_revisions(&rev, prefix);
1333 setup_revisions(0, NULL, &rev, NULL);
1336 rev.diffopt.output_format =
1337 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1339 rev.verbose_header = 1;
1340 rev.show_root_diff = 1;
1341 get_commit_format(format.buf, &rev);
1342 rev.always_show_header = 0;
1343 rev.diffopt.detect_rename = 1;
1344 rev.diffopt.break_opt = 0;
1345 diff_setup_done(&rev.diffopt);
1347 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1349 !prefixcmp(head, "refs/heads/") ?
1351 !strcmp(head, "HEAD") ?
1352 _("detached HEAD") :
1354 initial_commit ? _(" (root-commit)") : "");
1356 if (!log_tree_commit(&rev, commit)) {
1357 rev.always_show_header = 1;
1358 rev.use_terminator = 1;
1359 log_tree_commit(&rev, commit);
1362 strbuf_release(&format);
1365 static int git_commit_config(const char *k, const char *v, void *cb)
1367 struct wt_status *s = cb;
1370 if (!strcmp(k, "commit.template"))
1371 return git_config_pathname(&template_file, k, v);
1372 if (!strcmp(k, "commit.status")) {
1373 include_status = git_config_bool(k, v);
1377 status = git_gpg_config(k, v, NULL);
1380 return git_status_config(k, v, s);
1383 static const char post_rewrite_hook[] = "hooks/post-rewrite";
1385 static int run_rewrite_hook(const unsigned char *oldsha1,
1386 const unsigned char *newsha1)
1388 /* oldsha1 SP newsha1 LF NUL */
1389 static char buf[2*40 + 3];
1390 struct child_process proc;
1391 const char *argv[3];
1395 if (access(git_path(post_rewrite_hook), X_OK) < 0)
1398 argv[0] = git_path(post_rewrite_hook);
1402 memset(&proc, 0, sizeof(proc));
1405 proc.stdout_to_stderr = 1;
1407 code = start_command(&proc);
1410 n = snprintf(buf, sizeof(buf), "%s %s\n",
1411 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1412 write_in_full(proc.in, buf, n);
1414 return finish_command(&proc);
1417 int cmd_commit(int argc, const char **argv, const char *prefix)
1419 struct strbuf sb = STRBUF_INIT;
1420 struct strbuf author_ident = STRBUF_INIT;
1421 const char *index_file, *reflog_msg;
1423 unsigned char sha1[20];
1424 struct ref_lock *ref_lock;
1425 struct commit_list *parents = NULL, **pptr = &parents;
1426 struct stat statbuf;
1427 int allow_fast_forward = 1;
1429 struct commit *current_head = NULL;
1430 struct commit_extra_header *extra = NULL;
1432 if (argc == 2 && !strcmp(argv[1], "-h"))
1433 usage_with_options(builtin_commit_usage, builtin_commit_options);
1435 wt_status_prepare(&s);
1436 git_config(git_commit_config, &s);
1437 determine_whence(&s);
1439 if (get_sha1("HEAD", sha1))
1440 current_head = NULL;
1442 current_head = lookup_commit_or_die(sha1, "HEAD");
1443 if (!current_head || parse_commit(current_head))
1444 die(_("could not parse HEAD commit"));
1446 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1447 prefix, current_head, &s);
1449 return dry_run_commit(argc, argv, prefix, current_head, &s);
1450 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1452 /* Set up everything for writing the commit object. This includes
1453 running hooks, writing the trees, and interacting with the user. */
1454 if (!prepare_to_commit(index_file, prefix,
1455 current_head, &s, &author_ident)) {
1456 rollback_index_files();
1460 /* Determine parents */
1461 reflog_msg = getenv("GIT_REFLOG_ACTION");
1462 if (!current_head) {
1464 reflog_msg = "commit (initial)";
1466 struct commit_list *c;
1469 reflog_msg = "commit (amend)";
1470 for (c = current_head->parents; c; c = c->next)
1471 pptr = &commit_list_insert(c->item, pptr)->next;
1472 } else if (whence == FROM_MERGE) {
1473 struct strbuf m = STRBUF_INIT;
1477 reflog_msg = "commit (merge)";
1478 pptr = &commit_list_insert(current_head, pptr)->next;
1479 fp = fopen(git_path("MERGE_HEAD"), "r");
1481 die_errno(_("could not open '%s' for reading"),
1482 git_path("MERGE_HEAD"));
1483 while (strbuf_getline(&m, fp, '\n') != EOF) {
1484 struct commit *parent;
1486 parent = get_merge_parent(m.buf);
1488 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1489 pptr = &commit_list_insert(parent, pptr)->next;
1493 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1494 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1495 die_errno(_("could not read MERGE_MODE"));
1496 if (!strcmp(sb.buf, "no-ff"))
1497 allow_fast_forward = 0;
1499 if (allow_fast_forward)
1500 parents = reduce_heads(parents);
1503 reflog_msg = (whence == FROM_CHERRY_PICK)
1504 ? "commit (cherry-pick)"
1506 pptr = &commit_list_insert(current_head, pptr)->next;
1509 /* Finally, get the commit message */
1511 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1512 int saved_errno = errno;
1513 rollback_index_files();
1514 die(_("could not read commit message: %s"), strerror(saved_errno));
1517 /* Truncate the message just before the diff, if any. */
1519 p = strstr(sb.buf, "\ndiff --git ");
1521 strbuf_setlen(&sb, p - sb.buf + 1);
1524 if (cleanup_mode != CLEANUP_NONE)
1525 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1526 if (template_untouched(&sb) && !allow_empty_message) {
1527 rollback_index_files();
1528 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1531 if (message_is_empty(&sb) && !allow_empty_message) {
1532 rollback_index_files();
1533 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1538 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1539 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1541 struct commit_extra_header **tail = &extra;
1542 append_merge_tag_headers(parents, &tail);
1545 if (commit_tree_extended(&sb, active_cache_tree->sha1, parents, sha1,
1546 author_ident.buf, sign_commit, extra)) {
1547 rollback_index_files();
1548 die(_("failed to write commit object"));
1550 strbuf_release(&author_ident);
1551 free_commit_extra_headers(extra);
1553 ref_lock = lock_any_ref_for_update("HEAD",
1556 : current_head->object.sha1,
1559 nl = strchr(sb.buf, '\n');
1561 strbuf_setlen(&sb, nl + 1 - sb.buf);
1563 strbuf_addch(&sb, '\n');
1564 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1565 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1568 rollback_index_files();
1569 die(_("cannot lock HEAD ref"));
1571 if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1572 rollback_index_files();
1573 die(_("cannot update HEAD ref"));
1576 unlink(git_path("CHERRY_PICK_HEAD"));
1577 unlink(git_path("REVERT_HEAD"));
1578 unlink(git_path("MERGE_HEAD"));
1579 unlink(git_path("MERGE_MSG"));
1580 unlink(git_path("MERGE_MODE"));
1581 unlink(git_path("SQUASH_MSG"));
1583 if (commit_index_files())
1584 die (_("Repository has been updated, but unable to write\n"
1585 "new_index file. Check that disk is not full or quota is\n"
1586 "not exceeded, and then \"git reset HEAD\" to recover."));
1589 run_hook(get_index_file(), "post-commit", NULL);
1590 if (amend && !no_post_rewrite) {
1591 struct notes_rewrite_cfg *cfg;
1592 cfg = init_copy_notes_for_rewrite("amend");
1594 /* we are amending, so current_head is not NULL */
1595 copy_note_for_rewrite(cfg, current_head->object.sha1, sha1);
1596 finish_copy_notes_for_rewrite(cfg);
1598 run_rewrite_hook(current_head->object.sha1, sha1);
1601 print_summary(prefix, sha1, !current_head);