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 "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 "If the identity used for this commit is wrong, you can fix it with:\n"
50 " git commit --amend --author='Your Name <you@example.com>'\n";
52 static const char empty_amend_advice[] =
53 "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 unsigned char head_sha1[20];
59 static char *use_message_buffer;
60 static const char commit_editmsg[] = "COMMIT_EDITMSG";
61 static struct lock_file index_lock; /* real index */
62 static struct lock_file false_lock; /* used only for partial commits */
69 static const char *logfile, *force_author;
70 static const char *template_file;
71 static char *edit_message, *use_message;
72 static char *fixup_message;
73 static char *author_name, *author_email, *author_date;
74 static int all, edit_flag, also, interactive, only, amend, signoff;
75 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
76 static int no_post_rewrite, allow_empty_message;
77 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
79 * The default commit message cleanup mode will remove the lines
80 * beginning with # (shell comments) and leading and trailing
81 * whitespaces (empty lines or containing only whitespaces)
82 * if editor is used, and only the whitespaces if the message
83 * is specified explicitly.
90 static char *cleanup_arg;
92 static int use_editor = 1, initial_commit, in_merge, include_status = 1;
93 static int show_ignored_in_status;
94 static const char *only_include_assumed;
95 static struct strbuf message;
97 static int null_termination;
101 STATUS_FORMAT_PORCELAIN
102 } status_format = STATUS_FORMAT_LONG;
103 static int status_show_branch;
105 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
107 struct strbuf *buf = opt->value;
109 strbuf_setlen(buf, 0);
111 strbuf_addstr(buf, arg);
112 strbuf_addstr(buf, "\n\n");
117 static struct option builtin_commit_options[] = {
119 OPT__VERBOSE(&verbose),
121 OPT_GROUP("Commit message options"),
122 OPT_FILENAME('F', "file", &logfile, "read log from file"),
123 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
124 OPT_STRING(0, "date", &force_date, "DATE", "override date for commit"),
125 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
126 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
127 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
128 OPT_STRING(0, "fixup", &fixup_message, "COMMIT", "use autosquash formatted message to fixup specified commit"),
129 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
130 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
131 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
132 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
133 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
134 OPT_BOOLEAN(0, "status", &include_status, "include status in commit message template"),
135 /* end commit message options */
137 OPT_GROUP("Commit contents options"),
138 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
139 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
140 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
141 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
142 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
143 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
144 OPT_SET_INT(0, "short", &status_format, "show status concisely",
145 STATUS_FORMAT_SHORT),
146 OPT_BOOLEAN(0, "branch", &status_show_branch, "show branch information"),
147 OPT_SET_INT(0, "porcelain", &status_format,
148 "show porcelain output format", STATUS_FORMAT_PORCELAIN),
149 OPT_BOOLEAN('z', "null", &null_termination,
150 "terminate entries with NUL"),
151 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
152 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, "bypass post-rewrite hook"),
153 { 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" },
154 /* end commit contents options */
156 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
157 "ok to record an empty change",
158 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
159 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
160 "ok to record a change with an empty message",
161 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
166 static void rollback_index_files(void)
168 switch (commit_style) {
170 break; /* nothing to do */
172 rollback_lock_file(&index_lock);
175 rollback_lock_file(&index_lock);
176 rollback_lock_file(&false_lock);
181 static int commit_index_files(void)
185 switch (commit_style) {
187 break; /* nothing to do */
189 err = commit_lock_file(&index_lock);
192 err = commit_lock_file(&index_lock);
193 rollback_lock_file(&false_lock);
201 * Take a union of paths in the index and the named tree (typically, "HEAD"),
202 * and return the paths that match the given pattern in list.
204 static int list_paths(struct string_list *list, const char *with_tree,
205 const char *prefix, const char **pattern)
210 for (i = 0; pattern[i]; i++)
215 overlay_tree_on_cache(with_tree, prefix);
217 for (i = 0; i < active_nr; i++) {
218 struct cache_entry *ce = active_cache[i];
219 struct string_list_item *item;
221 if (ce->ce_flags & CE_UPDATE)
223 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
225 item = string_list_insert(list, ce->name);
226 if (ce_skip_worktree(ce))
227 item->util = item; /* better a valid pointer than a fake one */
230 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
233 static void add_remove_files(struct string_list *list)
236 for (i = 0; i < list->nr; i++) {
238 struct string_list_item *p = &(list->items[i]);
240 /* p->util is skip-worktree */
244 if (!lstat(p->string, &st)) {
245 if (add_to_cache(p->string, &st, 0))
246 die("updating files failed");
248 remove_file_from_cache(p->string);
252 static void create_base_index(void)
255 struct unpack_trees_options opts;
258 if (initial_commit) {
263 memset(&opts, 0, sizeof(opts));
267 opts.src_index = &the_index;
268 opts.dst_index = &the_index;
270 opts.fn = oneway_merge;
271 tree = parse_tree_indirect(head_sha1);
273 die("failed to unpack HEAD tree object");
275 init_tree_desc(&t, tree->buffer, tree->size);
276 if (unpack_trees(1, &t, &opts))
277 exit(128); /* We've already reported the error, finish dying */
280 static void refresh_cache_or_die(int refresh_flags)
283 * refresh_flags contains REFRESH_QUIET, so the only errors
284 * are for unmerged entries.
286 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
287 die_resolve_conflict("commit");
290 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
293 struct string_list partial;
294 const char **pathspec = NULL;
295 int refresh_flags = REFRESH_QUIET;
298 refresh_flags |= REFRESH_UNMERGED;
300 if (interactive_add(argc, argv, prefix) != 0)
301 die("interactive add failed");
302 if (read_cache_preload(NULL) < 0)
303 die("index file corrupt");
304 commit_style = COMMIT_AS_IS;
305 return get_index_file();
309 pathspec = get_pathspec(prefix, argv);
311 if (read_cache_preload(pathspec) < 0)
312 die("index file corrupt");
315 * Non partial, non as-is commit.
317 * (1) get the real index;
318 * (2) update the_index as necessary;
319 * (3) write the_index out to the real index (still locked);
320 * (4) return the name of the locked index file.
322 * The caller should run hooks on the locked real index, and
323 * (A) if all goes well, commit the real index;
324 * (B) on failure, rollback the real index.
326 if (all || (also && pathspec && *pathspec)) {
327 fd = hold_locked_index(&index_lock, 1);
328 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
329 refresh_cache_or_die(refresh_flags);
330 if (write_cache(fd, active_cache, active_nr) ||
331 close_lock_file(&index_lock))
332 die("unable to write new_index file");
333 commit_style = COMMIT_NORMAL;
334 return index_lock.filename;
340 * (1) return the name of the real index file.
342 * The caller should run hooks on the real index,
343 * and create commit from the_index.
344 * We still need to refresh the index here.
346 if (!pathspec || !*pathspec) {
347 fd = hold_locked_index(&index_lock, 1);
348 refresh_cache_or_die(refresh_flags);
349 if (active_cache_changed) {
350 if (write_cache(fd, active_cache, active_nr) ||
351 commit_locked_index(&index_lock))
352 die("unable to write new_index file");
354 rollback_lock_file(&index_lock);
356 commit_style = COMMIT_AS_IS;
357 return get_index_file();
363 * (0) find the set of affected paths;
364 * (1) get lock on the real index file;
365 * (2) update the_index with the given paths;
366 * (3) write the_index out to the real index (still locked);
367 * (4) get lock on the false index file;
368 * (5) reset the_index from HEAD;
369 * (6) update the_index the same way as (2);
370 * (7) write the_index out to the false index file;
371 * (8) return the name of the false index file (still locked);
373 * The caller should run hooks on the locked false index, and
374 * create commit from it. Then
375 * (A) if all goes well, commit the real index;
376 * (B) on failure, rollback the real index;
377 * In either case, rollback the false index.
379 commit_style = COMMIT_PARTIAL;
382 die("cannot do a partial commit during a merge.");
384 memset(&partial, 0, sizeof(partial));
385 partial.strdup_strings = 1;
386 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
390 if (read_cache() < 0)
391 die("cannot read the index");
393 fd = hold_locked_index(&index_lock, 1);
394 add_remove_files(&partial);
395 refresh_cache(REFRESH_QUIET);
396 if (write_cache(fd, active_cache, active_nr) ||
397 close_lock_file(&index_lock))
398 die("unable to write new_index file");
400 fd = hold_lock_file_for_update(&false_lock,
401 git_path("next-index-%"PRIuMAX,
402 (uintmax_t) getpid()),
406 add_remove_files(&partial);
407 refresh_cache(REFRESH_QUIET);
409 if (write_cache(fd, active_cache, active_nr) ||
410 close_lock_file(&false_lock))
411 die("unable to write temporary index file");
414 read_cache_from(false_lock.filename);
416 return false_lock.filename;
419 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
422 unsigned char sha1[20];
424 if (s->relative_paths)
429 s->reference = "HEAD^1";
431 s->verbose = verbose;
432 s->index_file = index_file;
435 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
437 wt_status_collect(s);
439 switch (status_format) {
440 case STATUS_FORMAT_SHORT:
441 wt_shortstatus_print(s, null_termination, status_show_branch);
443 case STATUS_FORMAT_PORCELAIN:
444 wt_porcelain_print(s, null_termination);
446 case STATUS_FORMAT_LONG:
451 return s->commitable;
454 static int is_a_merge(const unsigned char *sha1)
456 struct commit *commit = lookup_commit(sha1);
457 if (!commit || parse_commit(commit))
458 die("could not parse HEAD commit");
459 return !!(commit->parents && commit->parents->next);
462 static const char sign_off_header[] = "Signed-off-by: ";
464 static void determine_author_info(void)
466 char *name, *email, *date;
468 name = getenv("GIT_AUTHOR_NAME");
469 email = getenv("GIT_AUTHOR_EMAIL");
470 date = getenv("GIT_AUTHOR_DATE");
472 if (use_message && !renew_authorship) {
473 const char *a, *lb, *rb, *eol;
475 a = strstr(use_message_buffer, "\nauthor ");
477 die("invalid commit: %s", use_message);
479 lb = strchrnul(a + strlen("\nauthor "), '<');
480 rb = strchrnul(lb, '>');
481 eol = strchrnul(rb, '\n');
482 if (!*lb || !*rb || !*eol)
483 die("invalid commit: %s", use_message);
485 if (lb == a + strlen("\nauthor "))
486 /* \nauthor <foo@example.com> */
487 name = xcalloc(1, 1);
489 name = xmemdupz(a + strlen("\nauthor "),
491 (a + strlen("\nauthor "))));
492 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
493 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
497 const char *lb = strstr(force_author, " <");
498 const char *rb = strchr(force_author, '>');
501 die("malformed --author parameter");
502 name = xstrndup(force_author, lb - force_author);
503 email = xstrndup(lb + 2, rb - (lb + 2));
510 author_email = email;
514 static int ends_rfc2822_footer(struct strbuf *sb)
521 const char *buf = sb->buf;
523 for (i = len - 1; i > 0; i--) {
524 if (hit && buf[i] == '\n')
526 hit = (buf[i] == '\n');
529 while (i < len - 1 && buf[i] == '\n')
532 for (; i < len; i = k) {
533 for (k = i; k < len && buf[k] != '\n'; k++)
537 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
542 for (j = 0; i + j < len; j++) {
555 static int prepare_to_commit(const char *index_file, const char *prefix,
559 int commitable, saved_color_setting;
560 struct strbuf sb = STRBUF_INIT;
563 const char *hook_arg1 = NULL;
564 const char *hook_arg2 = NULL;
567 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
571 strbuf_addbuf(&sb, &message);
572 hook_arg1 = "message";
573 } else if (logfile && !strcmp(logfile, "-")) {
575 fprintf(stderr, "(reading log message from standard input)\n");
576 if (strbuf_read(&sb, 0, 0) < 0)
577 die_errno("could not read log from standard input");
578 hook_arg1 = "message";
579 } else if (logfile) {
580 if (strbuf_read_file(&sb, logfile, 0) < 0)
581 die_errno("could not read log file '%s'",
583 hook_arg1 = "message";
584 } else if (use_message) {
585 buffer = strstr(use_message_buffer, "\n\n");
586 if (!buffer || buffer[2] == '\0')
587 die("commit has empty message");
588 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
589 hook_arg1 = "commit";
590 hook_arg2 = use_message;
591 } else if (fixup_message) {
592 struct pretty_print_context ctx = {0};
593 struct commit *commit;
594 commit = lookup_commit_reference_by_name(fixup_message);
596 die("could not lookup commit %s", fixup_message);
597 ctx.output_encoding = get_commit_output_encoding();
598 format_commit_message(commit, "fixup! %s\n\n",
600 hook_arg1 = "message";
601 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
602 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
603 die_errno("could not read MERGE_MSG");
605 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
606 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
607 die_errno("could not read SQUASH_MSG");
608 hook_arg1 = "squash";
609 } else if (template_file && !stat(template_file, &statbuf)) {
610 if (strbuf_read_file(&sb, template_file, 0) < 0)
611 die_errno("could not read '%s'", template_file);
612 hook_arg1 = "template";
616 * This final case does not modify the template message,
617 * it just sets the argument to the prepare-commit-msg hook.
622 fp = fopen(git_path(commit_editmsg), "w");
624 die_errno("could not open '%s'", git_path(commit_editmsg));
626 if (cleanup_mode != CLEANUP_NONE)
630 struct strbuf sob = STRBUF_INIT;
633 strbuf_addstr(&sob, sign_off_header);
634 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
635 getenv("GIT_COMMITTER_EMAIL")));
636 strbuf_addch(&sob, '\n');
637 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
639 if (prefixcmp(sb.buf + i, sob.buf)) {
640 if (!i || !ends_rfc2822_footer(&sb))
641 strbuf_addch(&sb, '\n');
642 strbuf_addbuf(&sb, &sob);
644 strbuf_release(&sob);
647 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
648 die_errno("could not write commit template");
652 determine_author_info();
654 /* This checks if committer ident is explicitly given */
655 git_committer_info(0);
656 if (use_editor && include_status) {
658 const char *committer_ident;
663 "# It looks like you may be committing a MERGE.\n"
664 "# If this is not correct, please remove the file\n"
668 git_path("MERGE_HEAD"));
672 "# Please enter the commit message for your changes.");
673 if (cleanup_mode == CLEANUP_ALL)
676 "# with '#' will be ignored, and an empty"
677 " message aborts the commit.\n");
678 else /* CLEANUP_SPACE, that is. */
681 "# with '#' will be kept; you may remove them"
682 " yourself if you want to.\n"
683 "# An empty message aborts the commit.\n");
684 if (only_include_assumed)
685 fprintf(fp, "# %s\n", only_include_assumed);
687 author_ident = xstrdup(fmt_name(author_name, author_email));
688 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
689 getenv("GIT_COMMITTER_EMAIL"));
690 if (strcmp(author_ident, committer_ident))
694 ident_shown++ ? "" : "#\n",
698 if (!user_ident_sufficiently_given())
702 ident_shown++ ? "" : "#\n",
708 saved_color_setting = s->use_color;
710 commitable = run_status(fp, index_file, prefix, 1, s);
711 s->use_color = saved_color_setting;
713 unsigned char sha1[20];
714 const char *parent = "HEAD";
716 if (!active_nr && read_cache() < 0)
717 die("Cannot read index");
722 if (get_sha1(parent, sha1))
723 commitable = !!active_nr;
725 commitable = index_differs_from(parent, 0);
730 if (!commitable && !in_merge && !allow_empty &&
731 !(amend && is_a_merge(head_sha1))) {
732 run_status(stdout, index_file, prefix, 0, s);
734 fputs(empty_amend_advice, stderr);
739 * Re-read the index as pre-commit hook could have updated it,
740 * and write it out as a tree. We must do this before we invoke
741 * the editor and after we invoke run_status above.
744 read_cache_from(index_file);
745 if (!active_cache_tree)
746 active_cache_tree = cache_tree();
747 if (cache_tree_update(active_cache_tree,
748 active_cache, active_nr, 0, 0) < 0) {
749 error("Error building trees");
753 if (run_hook(index_file, "prepare-commit-msg",
754 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
758 char index[PATH_MAX];
759 const char *env[2] = { NULL };
761 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
762 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
764 "Please supply the message using either -m or -F option.\n");
770 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
778 * Find out if the message in the strbuf contains only whitespace and
779 * Signed-off-by lines.
781 static int message_is_empty(struct strbuf *sb)
783 struct strbuf tmpl = STRBUF_INIT;
785 int eol, i, start = 0;
787 if (cleanup_mode == CLEANUP_NONE && sb->len)
790 /* See if the template is just a prefix of the message. */
791 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
792 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
793 if (start + tmpl.len <= sb->len &&
794 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
797 strbuf_release(&tmpl);
799 /* Check if the rest is just whitespace and Signed-of-by's. */
800 for (i = start; i < sb->len; i++) {
801 nl = memchr(sb->buf + i, '\n', sb->len - i);
807 if (strlen(sign_off_header) <= eol - i &&
808 !prefixcmp(sb->buf + i, sign_off_header)) {
813 if (!isspace(sb->buf[i++]))
820 static const char *find_author_by_nickname(const char *name)
822 struct rev_info revs;
823 struct commit *commit;
824 struct strbuf buf = STRBUF_INIT;
828 init_revisions(&revs, NULL);
829 strbuf_addf(&buf, "--author=%s", name);
834 setup_revisions(ac, av, &revs, NULL);
835 prepare_revision_walk(&revs);
836 commit = get_revision(&revs);
838 struct pretty_print_context ctx = {0};
839 ctx.date_mode = DATE_NORMAL;
840 strbuf_release(&buf);
841 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
842 return strbuf_detach(&buf, NULL);
844 die("No existing author found with '%s'", name);
848 static void handle_untracked_files_arg(struct wt_status *s)
850 if (!untracked_files_arg)
851 ; /* default already initialized */
852 else if (!strcmp(untracked_files_arg, "no"))
853 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
854 else if (!strcmp(untracked_files_arg, "normal"))
855 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
856 else if (!strcmp(untracked_files_arg, "all"))
857 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
859 die("Invalid untracked files mode '%s'", untracked_files_arg);
862 static int parse_and_validate_options(int argc, const char *argv[],
863 const char * const usage[],
869 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
872 if (force_author && !strchr(force_author, '>'))
873 force_author = find_author_by_nickname(force_author);
875 if (force_author && renew_authorship)
876 die("Using both --reset-author and --author does not make sense");
878 if (logfile || message.len || use_message || fixup_message)
883 setenv("GIT_EDITOR", ":", 1);
885 if (get_sha1("HEAD", head_sha1))
888 /* Sanity check options */
889 if (amend && initial_commit)
890 die("You have nothing to amend.");
891 if (amend && in_merge)
892 die("You are in the middle of a merge -- cannot amend.");
903 die("Only one of -c/-C/-F/--fixup can be used.");
904 if (message.len && f > 0)
905 die("Option -m cannot be combined with -c/-C/-F/--fixup.");
907 use_message = edit_message;
908 if (amend && !use_message && !fixup_message)
909 use_message = "HEAD";
910 if (!use_message && renew_authorship)
911 die("--reset-author can be used only with -C, -c or --amend.");
914 struct commit *commit;
916 commit = lookup_commit_reference_by_name(use_message);
918 die("could not lookup commit %s", use_message);
919 out_enc = get_commit_output_encoding();
920 use_message_buffer = logmsg_reencode(commit, out_enc);
923 * If we failed to reencode the buffer, just copy it
924 * byte for byte so the user can try to fix it up.
925 * This also handles the case where input and output
926 * encodings are identical.
928 if (use_message_buffer == NULL)
929 use_message_buffer = xstrdup(commit->buffer);
932 if (!!also + !!only + !!all + !!interactive > 1)
933 die("Only one of --include/--only/--all/--interactive can be used.");
934 if (argc == 0 && (also || (only && !amend)))
935 die("No paths with --include/--only does not make sense.");
936 if (argc == 0 && only && amend)
937 only_include_assumed = "Clever... amending the last one with dirty index.";
938 if (argc > 0 && !also && !only)
939 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
940 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
941 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
942 else if (!strcmp(cleanup_arg, "verbatim"))
943 cleanup_mode = CLEANUP_NONE;
944 else if (!strcmp(cleanup_arg, "whitespace"))
945 cleanup_mode = CLEANUP_SPACE;
946 else if (!strcmp(cleanup_arg, "strip"))
947 cleanup_mode = CLEANUP_ALL;
949 die("Invalid cleanup mode %s", cleanup_arg);
951 handle_untracked_files_arg(s);
954 die("Paths with -a does not make sense.");
955 else if (interactive && argc > 0)
956 die("Paths with --interactive does not make sense.");
958 if (null_termination && status_format == STATUS_FORMAT_LONG)
959 status_format = STATUS_FORMAT_PORCELAIN;
960 if (status_format != STATUS_FORMAT_LONG)
966 static int dry_run_commit(int argc, const char **argv, const char *prefix,
970 const char *index_file;
972 index_file = prepare_index(argc, argv, prefix, 1);
973 commitable = run_status(stdout, index_file, prefix, 0, s);
974 rollback_index_files();
976 return commitable ? 0 : 1;
979 static int parse_status_slot(const char *var, int offset)
981 if (!strcasecmp(var+offset, "header"))
982 return WT_STATUS_HEADER;
983 if (!strcasecmp(var+offset, "updated")
984 || !strcasecmp(var+offset, "added"))
985 return WT_STATUS_UPDATED;
986 if (!strcasecmp(var+offset, "changed"))
987 return WT_STATUS_CHANGED;
988 if (!strcasecmp(var+offset, "untracked"))
989 return WT_STATUS_UNTRACKED;
990 if (!strcasecmp(var+offset, "nobranch"))
991 return WT_STATUS_NOBRANCH;
992 if (!strcasecmp(var+offset, "unmerged"))
993 return WT_STATUS_UNMERGED;
997 static int git_status_config(const char *k, const char *v, void *cb)
999 struct wt_status *s = cb;
1001 if (!strcmp(k, "status.submodulesummary")) {
1003 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1004 if (is_bool && s->submodule_summary)
1005 s->submodule_summary = -1;
1008 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1009 s->use_color = git_config_colorbool(k, v, -1);
1012 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1013 int slot = parse_status_slot(k, 13);
1017 return config_error_nonbool(k);
1018 color_parse(v, k, s->color_palette[slot]);
1021 if (!strcmp(k, "status.relativepaths")) {
1022 s->relative_paths = git_config_bool(k, v);
1025 if (!strcmp(k, "status.showuntrackedfiles")) {
1027 return config_error_nonbool(k);
1028 else if (!strcmp(v, "no"))
1029 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1030 else if (!strcmp(v, "normal"))
1031 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1032 else if (!strcmp(v, "all"))
1033 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1035 return error("Invalid untracked files mode '%s'", v);
1038 return git_diff_ui_config(k, v, NULL);
1041 int cmd_status(int argc, const char **argv, const char *prefix)
1045 unsigned char sha1[20];
1046 static struct option builtin_status_options[] = {
1047 OPT__VERBOSE(&verbose),
1048 OPT_SET_INT('s', "short", &status_format,
1049 "show status concisely", STATUS_FORMAT_SHORT),
1050 OPT_BOOLEAN('b', "branch", &status_show_branch,
1051 "show branch information"),
1052 OPT_SET_INT(0, "porcelain", &status_format,
1053 "show porcelain output format",
1054 STATUS_FORMAT_PORCELAIN),
1055 OPT_BOOLEAN('z', "null", &null_termination,
1056 "terminate entries with NUL"),
1057 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1059 "show untracked files, optional modes: all, normal, no. (Default: all)",
1060 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1061 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1062 "show ignored files"),
1063 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, "when",
1064 "ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)",
1065 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1069 if (null_termination && status_format == STATUS_FORMAT_LONG)
1070 status_format = STATUS_FORMAT_PORCELAIN;
1072 wt_status_prepare(&s);
1073 gitmodules_config();
1074 git_config(git_status_config, &s);
1075 in_merge = file_exists(git_path("MERGE_HEAD"));
1076 argc = parse_options(argc, argv, prefix,
1077 builtin_status_options,
1078 builtin_status_usage, 0);
1079 handle_untracked_files_arg(&s);
1080 if (show_ignored_in_status)
1081 s.show_ignored_files = 1;
1083 s.pathspec = get_pathspec(prefix, argv);
1085 read_cache_preload(s.pathspec);
1086 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1088 fd = hold_locked_index(&index_lock, 0);
1090 if (active_cache_changed &&
1091 !write_cache(fd, active_cache, active_nr))
1092 commit_locked_index(&index_lock);
1094 rollback_lock_file(&index_lock);
1097 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1098 s.in_merge = in_merge;
1099 s.ignore_submodule_arg = ignore_submodule_arg;
1100 wt_status_collect(&s);
1102 if (s.relative_paths)
1104 if (s.use_color == -1)
1105 s.use_color = git_use_color_default;
1106 if (diff_use_color_default == -1)
1107 diff_use_color_default = git_use_color_default;
1109 switch (status_format) {
1110 case STATUS_FORMAT_SHORT:
1111 wt_shortstatus_print(&s, null_termination, status_show_branch);
1113 case STATUS_FORMAT_PORCELAIN:
1114 wt_porcelain_print(&s, null_termination);
1116 case STATUS_FORMAT_LONG:
1117 s.verbose = verbose;
1118 s.ignore_submodule_arg = ignore_submodule_arg;
1119 wt_status_print(&s);
1125 static void print_summary(const char *prefix, const unsigned char *sha1)
1127 struct rev_info rev;
1128 struct commit *commit;
1129 struct strbuf format = STRBUF_INIT;
1130 unsigned char junk_sha1[20];
1131 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1132 struct pretty_print_context pctx = {0};
1133 struct strbuf author_ident = STRBUF_INIT;
1134 struct strbuf committer_ident = STRBUF_INIT;
1136 commit = lookup_commit(sha1);
1138 die("couldn't look up newly created commit");
1139 if (!commit || parse_commit(commit))
1140 die("could not parse newly created commit");
1142 strbuf_addstr(&format, "format:%h] %s");
1144 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1145 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1146 if (strbuf_cmp(&author_ident, &committer_ident)) {
1147 strbuf_addstr(&format, "\n Author: ");
1148 strbuf_addbuf_percentquote(&format, &author_ident);
1150 if (!user_ident_sufficiently_given()) {
1151 strbuf_addstr(&format, "\n Committer: ");
1152 strbuf_addbuf_percentquote(&format, &committer_ident);
1153 if (advice_implicit_identity) {
1154 strbuf_addch(&format, '\n');
1155 strbuf_addstr(&format, implicit_ident_advice);
1158 strbuf_release(&author_ident);
1159 strbuf_release(&committer_ident);
1161 init_revisions(&rev, prefix);
1162 setup_revisions(0, NULL, &rev, NULL);
1165 rev.diffopt.output_format =
1166 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1168 rev.verbose_header = 1;
1169 rev.show_root_diff = 1;
1170 get_commit_format(format.buf, &rev);
1171 rev.always_show_header = 0;
1172 rev.diffopt.detect_rename = 1;
1173 rev.diffopt.rename_limit = 100;
1174 rev.diffopt.break_opt = 0;
1175 diff_setup_done(&rev.diffopt);
1178 !prefixcmp(head, "refs/heads/") ?
1180 !strcmp(head, "HEAD") ?
1183 initial_commit ? " (root-commit)" : "");
1185 if (!log_tree_commit(&rev, commit)) {
1186 rev.always_show_header = 1;
1187 rev.use_terminator = 1;
1188 log_tree_commit(&rev, commit);
1191 strbuf_release(&format);
1194 static int git_commit_config(const char *k, const char *v, void *cb)
1196 struct wt_status *s = cb;
1198 if (!strcmp(k, "commit.template"))
1199 return git_config_pathname(&template_file, k, v);
1200 if (!strcmp(k, "commit.status")) {
1201 include_status = git_config_bool(k, v);
1205 return git_status_config(k, v, s);
1208 static const char post_rewrite_hook[] = "hooks/post-rewrite";
1210 static int run_rewrite_hook(const unsigned char *oldsha1,
1211 const unsigned char *newsha1)
1213 /* oldsha1 SP newsha1 LF NUL */
1214 static char buf[2*40 + 3];
1215 struct child_process proc;
1216 const char *argv[3];
1220 if (access(git_path(post_rewrite_hook), X_OK) < 0)
1223 argv[0] = git_path(post_rewrite_hook);
1227 memset(&proc, 0, sizeof(proc));
1230 proc.stdout_to_stderr = 1;
1232 code = start_command(&proc);
1235 n = snprintf(buf, sizeof(buf), "%s %s\n",
1236 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1237 write_in_full(proc.in, buf, n);
1239 return finish_command(&proc);
1242 int cmd_commit(int argc, const char **argv, const char *prefix)
1244 struct strbuf sb = STRBUF_INIT;
1245 const char *index_file, *reflog_msg;
1247 unsigned char commit_sha1[20];
1248 struct ref_lock *ref_lock;
1249 struct commit_list *parents = NULL, **pptr = &parents;
1250 struct stat statbuf;
1251 int allow_fast_forward = 1;
1254 wt_status_prepare(&s);
1255 git_config(git_commit_config, &s);
1256 in_merge = file_exists(git_path("MERGE_HEAD"));
1257 s.in_merge = in_merge;
1259 if (s.use_color == -1)
1260 s.use_color = git_use_color_default;
1261 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1264 if (diff_use_color_default == -1)
1265 diff_use_color_default = git_use_color_default;
1266 return dry_run_commit(argc, argv, prefix, &s);
1268 index_file = prepare_index(argc, argv, prefix, 0);
1270 /* Set up everything for writing the commit object. This includes
1271 running hooks, writing the trees, and interacting with the user. */
1272 if (!prepare_to_commit(index_file, prefix, &s)) {
1273 rollback_index_files();
1277 /* Determine parents */
1278 reflog_msg = getenv("GIT_REFLOG_ACTION");
1279 if (initial_commit) {
1281 reflog_msg = "commit (initial)";
1283 struct commit_list *c;
1284 struct commit *commit;
1287 reflog_msg = "commit (amend)";
1288 commit = lookup_commit(head_sha1);
1289 if (!commit || parse_commit(commit))
1290 die("could not parse HEAD commit");
1292 for (c = commit->parents; c; c = c->next)
1293 pptr = &commit_list_insert(c->item, pptr)->next;
1294 } else if (in_merge) {
1295 struct strbuf m = STRBUF_INIT;
1299 reflog_msg = "commit (merge)";
1300 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1301 fp = fopen(git_path("MERGE_HEAD"), "r");
1303 die_errno("could not open '%s' for reading",
1304 git_path("MERGE_HEAD"));
1305 while (strbuf_getline(&m, fp, '\n') != EOF) {
1306 unsigned char sha1[20];
1307 if (get_sha1_hex(m.buf, sha1) < 0)
1308 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1309 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1313 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1314 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1315 die_errno("could not read MERGE_MODE");
1316 if (!strcmp(sb.buf, "no-ff"))
1317 allow_fast_forward = 0;
1319 if (allow_fast_forward)
1320 parents = reduce_heads(parents);
1323 reflog_msg = "commit";
1324 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1327 /* Finally, get the commit message */
1329 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1330 int saved_errno = errno;
1331 rollback_index_files();
1332 die("could not read commit message: %s", strerror(saved_errno));
1335 /* Truncate the message just before the diff, if any. */
1337 p = strstr(sb.buf, "\ndiff --git ");
1339 strbuf_setlen(&sb, p - sb.buf + 1);
1342 if (cleanup_mode != CLEANUP_NONE)
1343 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1344 if (message_is_empty(&sb) && !allow_empty_message) {
1345 rollback_index_files();
1346 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1350 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1351 fmt_ident(author_name, author_email, author_date,
1352 IDENT_ERROR_ON_NO_NAME))) {
1353 rollback_index_files();
1354 die("failed to write commit object");
1357 ref_lock = lock_any_ref_for_update("HEAD",
1358 initial_commit ? NULL : head_sha1,
1361 nl = strchr(sb.buf, '\n');
1363 strbuf_setlen(&sb, nl + 1 - sb.buf);
1365 strbuf_addch(&sb, '\n');
1366 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1367 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1370 rollback_index_files();
1371 die("cannot lock HEAD ref");
1373 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1374 rollback_index_files();
1375 die("cannot update HEAD ref");
1378 unlink(git_path("MERGE_HEAD"));
1379 unlink(git_path("MERGE_MSG"));
1380 unlink(git_path("MERGE_MODE"));
1381 unlink(git_path("SQUASH_MSG"));
1383 if (commit_index_files())
1384 die ("Repository has been updated, but unable to write\n"
1385 "new_index file. Check that disk is not full or quota is\n"
1386 "not exceeded, and then \"git reset HEAD\" to recover.");
1389 run_hook(get_index_file(), "post-commit", NULL);
1390 if (amend && !no_post_rewrite) {
1391 struct notes_rewrite_cfg *cfg;
1392 cfg = init_copy_notes_for_rewrite("amend");
1394 copy_note_for_rewrite(cfg, head_sha1, commit_sha1);
1395 finish_copy_notes_for_rewrite(cfg);
1397 run_rewrite_hook(head_sha1, commit_sha1);
1400 print_summary(prefix, commit_sha1);