status: disable display of '#' comment prefix by default
[git.git] / builtin / commit.c
blob61975ad1df0bfa79225a28f267f5dde660e2737c
1 /*
2 * Builtin "git commit"
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6 */
8 #include "cache.h"
9 #include "cache-tree.h"
10 #include "color.h"
11 #include "dir.h"
12 #include "builtin.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "commit.h"
16 #include "revision.h"
17 #include "wt-status.h"
18 #include "run-command.h"
19 #include "refs.h"
20 #include "log-tree.h"
21 #include "strbuf.h"
22 #include "utf8.h"
23 #include "parse-options.h"
24 #include "string-list.h"
25 #include "rerere.h"
26 #include "unpack-trees.h"
27 #include "quote.h"
28 #include "submodule.h"
29 #include "gpg-interface.h"
30 #include "column.h"
31 #include "sequencer.h"
32 #include "notes-utils.h"
34 static const char * const builtin_commit_usage[] = {
35 N_("git commit [options] [--] <pathspec>..."),
36 NULL
39 static const char * const builtin_status_usage[] = {
40 N_("git status [options] [--] <pathspec>..."),
41 NULL
44 static const char implicit_ident_advice[] =
45 N_("Your name and email address were configured automatically based\n"
46 "on your username and hostname. Please check that they are accurate.\n"
47 "You can suppress this message by setting them explicitly:\n"
48 "\n"
49 " git config --global user.name \"Your Name\"\n"
50 " git config --global user.email you@example.com\n"
51 "\n"
52 "After doing this, you may fix the identity used for this commit with:\n"
53 "\n"
54 " git commit --amend --reset-author\n");
56 static const char empty_amend_advice[] =
57 N_("You asked to amend the most recent commit, but doing so would make\n"
58 "it empty. You can repeat your command with --allow-empty, or you can\n"
59 "remove the commit entirely with \"git reset HEAD^\".\n");
61 static const char empty_cherry_pick_advice[] =
62 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
63 "If you wish to commit it anyway, use:\n"
64 "\n"
65 " git commit --allow-empty\n"
66 "\n");
68 static const char empty_cherry_pick_advice_single[] =
69 N_("Otherwise, please use 'git reset'\n");
71 static const char empty_cherry_pick_advice_multi[] =
72 N_("If you wish to skip this commit, use:\n"
73 "\n"
74 " git reset\n"
75 "\n"
76 "Then \"git cherry-pick --continue\" will resume cherry-picking\n"
77 "the remaining commits.\n");
79 static const char *use_message_buffer;
80 static const char commit_editmsg[] = "COMMIT_EDITMSG";
81 static struct lock_file index_lock; /* real index */
82 static struct lock_file false_lock; /* used only for partial commits */
83 static enum {
84 COMMIT_AS_IS = 1,
85 COMMIT_NORMAL,
86 COMMIT_PARTIAL
87 } commit_style;
89 static const char *logfile, *force_author;
90 static const char *template_file;
92 * The _message variables are commit names from which to take
93 * the commit message and/or authorship.
95 static const char *author_message, *author_message_buffer;
96 static char *edit_message, *use_message;
97 static char *fixup_message, *squash_message;
98 static int all, also, interactive, patch_interactive, only, amend, signoff;
99 static int edit_flag = -1; /* unspecified */
100 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
101 static int no_post_rewrite, allow_empty_message;
102 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
103 static char *sign_commit;
106 * The default commit message cleanup mode will remove the lines
107 * beginning with # (shell comments) and leading and trailing
108 * whitespaces (empty lines or containing only whitespaces)
109 * if editor is used, and only the whitespaces if the message
110 * is specified explicitly.
112 static enum {
113 CLEANUP_SPACE,
114 CLEANUP_NONE,
115 CLEANUP_ALL
116 } cleanup_mode;
117 static const char *cleanup_arg;
119 static enum commit_whence whence;
120 static int sequencer_in_use;
121 static int use_editor = 1, include_status = 1;
122 static int show_ignored_in_status, have_option_m;
123 static const char *only_include_assumed;
124 static struct strbuf message = STRBUF_INIT;
126 static enum status_format {
127 STATUS_FORMAT_NONE = 0,
128 STATUS_FORMAT_LONG,
129 STATUS_FORMAT_SHORT,
130 STATUS_FORMAT_PORCELAIN,
132 STATUS_FORMAT_UNSPECIFIED
133 } status_format = STATUS_FORMAT_UNSPECIFIED;
135 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
137 struct strbuf *buf = opt->value;
138 if (unset) {
139 have_option_m = 0;
140 strbuf_setlen(buf, 0);
141 } else {
142 have_option_m = 1;
143 if (buf->len)
144 strbuf_addch(buf, '\n');
145 strbuf_addstr(buf, arg);
146 strbuf_complete_line(buf);
148 return 0;
151 static void determine_whence(struct wt_status *s)
153 if (file_exists(git_path("MERGE_HEAD")))
154 whence = FROM_MERGE;
155 else if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
156 whence = FROM_CHERRY_PICK;
157 if (file_exists(git_path("sequencer")))
158 sequencer_in_use = 1;
160 else
161 whence = FROM_COMMIT;
162 if (s)
163 s->whence = whence;
166 static void rollback_index_files(void)
168 switch (commit_style) {
169 case COMMIT_AS_IS:
170 break; /* nothing to do */
171 case COMMIT_NORMAL:
172 rollback_lock_file(&index_lock);
173 break;
174 case COMMIT_PARTIAL:
175 rollback_lock_file(&index_lock);
176 rollback_lock_file(&false_lock);
177 break;
181 static int commit_index_files(void)
183 int err = 0;
185 switch (commit_style) {
186 case COMMIT_AS_IS:
187 break; /* nothing to do */
188 case COMMIT_NORMAL:
189 err = commit_lock_file(&index_lock);
190 break;
191 case COMMIT_PARTIAL:
192 err = commit_lock_file(&index_lock);
193 rollback_lock_file(&false_lock);
194 break;
197 return err;
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)
207 int i;
208 char *m;
210 if (!pattern)
211 return 0;
213 for (i = 0; pattern[i]; i++)
215 m = xcalloc(1, i);
217 if (with_tree) {
218 char *max_prefix = common_prefix(pattern);
219 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
220 free(max_prefix);
223 for (i = 0; i < active_nr; i++) {
224 const struct cache_entry *ce = active_cache[i];
225 struct string_list_item *item;
227 if (ce->ce_flags & CE_UPDATE)
228 continue;
229 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
230 continue;
231 item = string_list_insert(list, ce->name);
232 if (ce_skip_worktree(ce))
233 item->util = item; /* better a valid pointer than a fake one */
236 return report_path_error(m, pattern, prefix);
239 static void add_remove_files(struct string_list *list)
241 int i;
242 for (i = 0; i < list->nr; i++) {
243 struct stat st;
244 struct string_list_item *p = &(list->items[i]);
246 /* p->util is skip-worktree */
247 if (p->util)
248 continue;
250 if (!lstat(p->string, &st)) {
251 if (add_to_cache(p->string, &st, 0))
252 die(_("updating files failed"));
253 } else
254 remove_file_from_cache(p->string);
258 static void create_base_index(const struct commit *current_head)
260 struct tree *tree;
261 struct unpack_trees_options opts;
262 struct tree_desc t;
264 if (!current_head) {
265 discard_cache();
266 return;
269 memset(&opts, 0, sizeof(opts));
270 opts.head_idx = 1;
271 opts.index_only = 1;
272 opts.merge = 1;
273 opts.src_index = &the_index;
274 opts.dst_index = &the_index;
276 opts.fn = oneway_merge;
277 tree = parse_tree_indirect(current_head->object.sha1);
278 if (!tree)
279 die(_("failed to unpack HEAD tree object"));
280 parse_tree(tree);
281 init_tree_desc(&t, tree->buffer, tree->size);
282 if (unpack_trees(1, &t, &opts))
283 exit(128); /* We've already reported the error, finish dying */
286 static void refresh_cache_or_die(int refresh_flags)
289 * refresh_flags contains REFRESH_QUIET, so the only errors
290 * are for unmerged entries.
292 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
293 die_resolve_conflict("commit");
296 static char *prepare_index(int argc, const char **argv, const char *prefix,
297 const struct commit *current_head, int is_status)
299 int fd;
300 struct string_list partial;
301 const char **pathspec = NULL;
302 char *old_index_env = NULL;
303 int refresh_flags = REFRESH_QUIET;
305 if (is_status)
306 refresh_flags |= REFRESH_UNMERGED;
308 if (*argv)
309 pathspec = get_pathspec(prefix, argv);
311 if (read_cache_preload(pathspec) < 0)
312 die(_("index file corrupt"));
314 if (interactive) {
315 fd = hold_locked_index(&index_lock, 1);
317 refresh_cache_or_die(refresh_flags);
319 if (write_cache(fd, active_cache, active_nr) ||
320 close_lock_file(&index_lock))
321 die(_("unable to create temporary index"));
323 old_index_env = getenv(INDEX_ENVIRONMENT);
324 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
326 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
327 die(_("interactive add failed"));
329 if (old_index_env && *old_index_env)
330 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
331 else
332 unsetenv(INDEX_ENVIRONMENT);
334 discard_cache();
335 read_cache_from(index_lock.filename);
337 commit_style = COMMIT_NORMAL;
338 return index_lock.filename;
342 * Non partial, non as-is commit.
344 * (1) get the real index;
345 * (2) update the_index as necessary;
346 * (3) write the_index out to the real index (still locked);
347 * (4) return the name of the locked index file.
349 * The caller should run hooks on the locked real index, and
350 * (A) if all goes well, commit the real index;
351 * (B) on failure, rollback the real index.
353 if (all || (also && pathspec && *pathspec)) {
354 fd = hold_locked_index(&index_lock, 1);
355 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
356 refresh_cache_or_die(refresh_flags);
357 update_main_cache_tree(WRITE_TREE_SILENT);
358 if (write_cache(fd, active_cache, active_nr) ||
359 close_lock_file(&index_lock))
360 die(_("unable to write new_index file"));
361 commit_style = COMMIT_NORMAL;
362 return index_lock.filename;
366 * As-is commit.
368 * (1) return the name of the real index file.
370 * The caller should run hooks on the real index,
371 * and create commit from the_index.
372 * We still need to refresh the index here.
374 if (!only && (!pathspec || !*pathspec)) {
375 fd = hold_locked_index(&index_lock, 1);
376 refresh_cache_or_die(refresh_flags);
377 if (active_cache_changed) {
378 update_main_cache_tree(WRITE_TREE_SILENT);
379 if (write_cache(fd, active_cache, active_nr) ||
380 commit_locked_index(&index_lock))
381 die(_("unable to write new_index file"));
382 } else {
383 rollback_lock_file(&index_lock);
385 commit_style = COMMIT_AS_IS;
386 return get_index_file();
390 * A partial commit.
392 * (0) find the set of affected paths;
393 * (1) get lock on the real index file;
394 * (2) update the_index with the given paths;
395 * (3) write the_index out to the real index (still locked);
396 * (4) get lock on the false index file;
397 * (5) reset the_index from HEAD;
398 * (6) update the_index the same way as (2);
399 * (7) write the_index out to the false index file;
400 * (8) return the name of the false index file (still locked);
402 * The caller should run hooks on the locked false index, and
403 * create commit from it. Then
404 * (A) if all goes well, commit the real index;
405 * (B) on failure, rollback the real index;
406 * In either case, rollback the false index.
408 commit_style = COMMIT_PARTIAL;
410 if (whence != FROM_COMMIT) {
411 if (whence == FROM_MERGE)
412 die(_("cannot do a partial commit during a merge."));
413 else if (whence == FROM_CHERRY_PICK)
414 die(_("cannot do a partial commit during a cherry-pick."));
417 memset(&partial, 0, sizeof(partial));
418 partial.strdup_strings = 1;
419 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, pathspec))
420 exit(1);
422 discard_cache();
423 if (read_cache() < 0)
424 die(_("cannot read the index"));
426 fd = hold_locked_index(&index_lock, 1);
427 add_remove_files(&partial);
428 refresh_cache(REFRESH_QUIET);
429 if (write_cache(fd, active_cache, active_nr) ||
430 close_lock_file(&index_lock))
431 die(_("unable to write new_index file"));
433 fd = hold_lock_file_for_update(&false_lock,
434 git_path("next-index-%"PRIuMAX,
435 (uintmax_t) getpid()),
436 LOCK_DIE_ON_ERROR);
438 create_base_index(current_head);
439 add_remove_files(&partial);
440 refresh_cache(REFRESH_QUIET);
442 if (write_cache(fd, active_cache, active_nr) ||
443 close_lock_file(&false_lock))
444 die(_("unable to write temporary index file"));
446 discard_cache();
447 read_cache_from(false_lock.filename);
449 return false_lock.filename;
452 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
453 struct wt_status *s)
455 unsigned char sha1[20];
457 if (s->relative_paths)
458 s->prefix = prefix;
460 if (amend) {
461 s->amend = 1;
462 s->reference = "HEAD^1";
464 s->verbose = verbose;
465 s->index_file = index_file;
466 s->fp = fp;
467 s->nowarn = nowarn;
468 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
470 wt_status_collect(s);
472 switch (status_format) {
473 case STATUS_FORMAT_SHORT:
474 wt_shortstatus_print(s);
475 break;
476 case STATUS_FORMAT_PORCELAIN:
477 wt_porcelain_print(s);
478 break;
479 case STATUS_FORMAT_UNSPECIFIED:
480 die("BUG: finalize_deferred_config() should have been called");
481 break;
482 case STATUS_FORMAT_NONE:
483 case STATUS_FORMAT_LONG:
484 wt_status_print(s);
485 break;
488 return s->commitable;
491 static int is_a_merge(const struct commit *current_head)
493 return !!(current_head->parents && current_head->parents->next);
496 static void export_one(const char *var, const char *s, const char *e, int hack)
498 struct strbuf buf = STRBUF_INIT;
499 if (hack)
500 strbuf_addch(&buf, hack);
501 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
502 setenv(var, buf.buf, 1);
503 strbuf_release(&buf);
506 static int sane_ident_split(struct ident_split *person)
508 if (!person->name_begin || !person->name_end ||
509 person->name_begin == person->name_end)
510 return 0; /* no human readable name */
511 if (!person->mail_begin || !person->mail_end ||
512 person->mail_begin == person->mail_end)
513 return 0; /* no usable mail */
514 if (!person->date_begin || !person->date_end ||
515 !person->tz_begin || !person->tz_end)
516 return 0;
517 return 1;
520 static void determine_author_info(struct strbuf *author_ident)
522 char *name, *email, *date;
523 struct ident_split author;
525 name = getenv("GIT_AUTHOR_NAME");
526 email = getenv("GIT_AUTHOR_EMAIL");
527 date = getenv("GIT_AUTHOR_DATE");
529 if (author_message) {
530 const char *a, *lb, *rb, *eol;
531 size_t len;
533 a = strstr(author_message_buffer, "\nauthor ");
534 if (!a)
535 die(_("invalid commit: %s"), author_message);
537 lb = strchrnul(a + strlen("\nauthor "), '<');
538 rb = strchrnul(lb, '>');
539 eol = strchrnul(rb, '\n');
540 if (!*lb || !*rb || !*eol)
541 die(_("invalid commit: %s"), author_message);
543 if (lb == a + strlen("\nauthor "))
544 /* \nauthor <foo@example.com> */
545 name = xcalloc(1, 1);
546 else
547 name = xmemdupz(a + strlen("\nauthor "),
548 (lb - strlen(" ") -
549 (a + strlen("\nauthor "))));
550 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
551 len = eol - (rb + strlen("> "));
552 date = xmalloc(len + 2);
553 *date = '@';
554 memcpy(date + 1, rb + strlen("> "), len);
555 date[len + 1] = '\0';
558 if (force_author) {
559 const char *lb = strstr(force_author, " <");
560 const char *rb = strchr(force_author, '>');
562 if (!lb || !rb)
563 die(_("malformed --author parameter"));
564 name = xstrndup(force_author, lb - force_author);
565 email = xstrndup(lb + 2, rb - (lb + 2));
568 if (force_date)
569 date = force_date;
570 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
571 if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
572 sane_ident_split(&author)) {
573 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
574 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
575 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
579 static char *cut_ident_timestamp_part(char *string)
581 char *ket = strrchr(string, '>');
582 if (!ket || ket[1] != ' ')
583 die(_("Malformed ident string: '%s'"), string);
584 *++ket = '\0';
585 return ket;
588 static int prepare_to_commit(const char *index_file, const char *prefix,
589 struct commit *current_head,
590 struct wt_status *s,
591 struct strbuf *author_ident)
593 struct stat statbuf;
594 struct strbuf committer_ident = STRBUF_INIT;
595 int commitable, saved_color_setting;
596 struct strbuf sb = STRBUF_INIT;
597 char *buffer;
598 const char *hook_arg1 = NULL;
599 const char *hook_arg2 = NULL;
600 int ident_shown = 0;
601 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
602 int old_display_comment_prefix;
604 /* This checks and barfs if author is badly specified */
605 determine_author_info(author_ident);
607 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
608 return 0;
610 if (squash_message) {
612 * Insert the proper subject line before other commit
613 * message options add their content.
615 if (use_message && !strcmp(use_message, squash_message))
616 strbuf_addstr(&sb, "squash! ");
617 else {
618 struct pretty_print_context ctx = {0};
619 struct commit *c;
620 c = lookup_commit_reference_by_name(squash_message);
621 if (!c)
622 die(_("could not lookup commit %s"), squash_message);
623 ctx.output_encoding = get_commit_output_encoding();
624 format_commit_message(c, "squash! %s\n\n", &sb,
625 &ctx);
629 if (message.len) {
630 strbuf_addbuf(&sb, &message);
631 hook_arg1 = "message";
632 } else if (logfile && !strcmp(logfile, "-")) {
633 if (isatty(0))
634 fprintf(stderr, _("(reading log message from standard input)\n"));
635 if (strbuf_read(&sb, 0, 0) < 0)
636 die_errno(_("could not read log from standard input"));
637 hook_arg1 = "message";
638 } else if (logfile) {
639 if (strbuf_read_file(&sb, logfile, 0) < 0)
640 die_errno(_("could not read log file '%s'"),
641 logfile);
642 hook_arg1 = "message";
643 } else if (use_message) {
644 buffer = strstr(use_message_buffer, "\n\n");
645 if (!use_editor && (!buffer || buffer[2] == '\0'))
646 die(_("commit has empty message"));
647 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
648 hook_arg1 = "commit";
649 hook_arg2 = use_message;
650 } else if (fixup_message) {
651 struct pretty_print_context ctx = {0};
652 struct commit *commit;
653 commit = lookup_commit_reference_by_name(fixup_message);
654 if (!commit)
655 die(_("could not lookup commit %s"), fixup_message);
656 ctx.output_encoding = get_commit_output_encoding();
657 format_commit_message(commit, "fixup! %s\n\n",
658 &sb, &ctx);
659 hook_arg1 = "message";
660 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
661 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
662 die_errno(_("could not read MERGE_MSG"));
663 hook_arg1 = "merge";
664 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
665 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
666 die_errno(_("could not read SQUASH_MSG"));
667 hook_arg1 = "squash";
668 } else if (template_file) {
669 if (strbuf_read_file(&sb, template_file, 0) < 0)
670 die_errno(_("could not read '%s'"), template_file);
671 hook_arg1 = "template";
672 clean_message_contents = 0;
676 * The remaining cases don't modify the template message, but
677 * just set the argument(s) to the prepare-commit-msg hook.
679 else if (whence == FROM_MERGE)
680 hook_arg1 = "merge";
681 else if (whence == FROM_CHERRY_PICK) {
682 hook_arg1 = "commit";
683 hook_arg2 = "CHERRY_PICK_HEAD";
686 if (squash_message) {
688 * If squash_commit was used for the commit subject,
689 * then we're possibly hijacking other commit log options.
690 * Reset the hook args to tell the real story.
692 hook_arg1 = "message";
693 hook_arg2 = "";
696 s->fp = fopen(git_path(commit_editmsg), "w");
697 if (s->fp == NULL)
698 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
700 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
701 old_display_comment_prefix = s->display_comment_prefix;
702 s->display_comment_prefix = 1;
704 if (clean_message_contents)
705 stripspace(&sb, 0);
707 if (signoff) {
709 * See if we have a Conflicts: block at the end. If yes, count
710 * its size, so we can ignore it.
712 int ignore_footer = 0;
713 int i, eol, previous = 0;
714 const char *nl;
716 for (i = 0; i < sb.len; i++) {
717 nl = memchr(sb.buf + i, '\n', sb.len - i);
718 if (nl)
719 eol = nl - sb.buf;
720 else
721 eol = sb.len;
722 if (!prefixcmp(sb.buf + previous, "\nConflicts:\n")) {
723 ignore_footer = sb.len - previous;
724 break;
726 while (i < eol)
727 i++;
728 previous = eol;
731 append_signoff(&sb, ignore_footer, 0);
734 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
735 die_errno(_("could not write commit template"));
737 strbuf_release(&sb);
739 /* This checks if committer ident is explicitly given */
740 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
741 if (use_editor && include_status) {
742 char *ai_tmp, *ci_tmp;
743 if (whence != FROM_COMMIT)
744 status_printf_ln(s, GIT_COLOR_NORMAL,
745 whence == FROM_MERGE
746 ? _("\n"
747 "It looks like you may be committing a merge.\n"
748 "If this is not correct, please remove the file\n"
749 " %s\n"
750 "and try again.\n")
751 : _("\n"
752 "It looks like you may be committing a cherry-pick.\n"
753 "If this is not correct, please remove the file\n"
754 " %s\n"
755 "and try again.\n"),
756 git_path(whence == FROM_MERGE
757 ? "MERGE_HEAD"
758 : "CHERRY_PICK_HEAD"));
760 fprintf(s->fp, "\n");
761 if (cleanup_mode == CLEANUP_ALL)
762 status_printf(s, GIT_COLOR_NORMAL,
763 _("Please enter the commit message for your changes."
764 " Lines starting\nwith '%c' will be ignored, and an empty"
765 " message aborts the commit.\n"), comment_line_char);
766 else /* CLEANUP_SPACE, that is. */
767 status_printf(s, GIT_COLOR_NORMAL,
768 _("Please enter the commit message for your changes."
769 " Lines starting\n"
770 "with '%c' will be kept; you may remove them"
771 " yourself if you want to.\n"
772 "An empty message aborts the commit.\n"), comment_line_char);
773 if (only_include_assumed)
774 status_printf_ln(s, GIT_COLOR_NORMAL,
775 "%s", only_include_assumed);
777 ai_tmp = cut_ident_timestamp_part(author_ident->buf);
778 ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
779 if (strcmp(author_ident->buf, committer_ident.buf))
780 status_printf_ln(s, GIT_COLOR_NORMAL,
781 _("%s"
782 "Author: %s"),
783 ident_shown++ ? "" : "\n",
784 author_ident->buf);
786 if (!committer_ident_sufficiently_given())
787 status_printf_ln(s, GIT_COLOR_NORMAL,
788 _("%s"
789 "Committer: %s"),
790 ident_shown++ ? "" : "\n",
791 committer_ident.buf);
793 if (ident_shown)
794 status_printf_ln(s, GIT_COLOR_NORMAL, "");
796 saved_color_setting = s->use_color;
797 s->use_color = 0;
798 commitable = run_status(s->fp, index_file, prefix, 1, s);
799 s->use_color = saved_color_setting;
801 *ai_tmp = ' ';
802 *ci_tmp = ' ';
803 } else {
804 unsigned char sha1[20];
805 const char *parent = "HEAD";
807 if (!active_nr && read_cache() < 0)
808 die(_("Cannot read index"));
810 if (amend)
811 parent = "HEAD^1";
813 if (get_sha1(parent, sha1))
814 commitable = !!active_nr;
815 else
816 commitable = index_differs_from(parent, 0);
818 strbuf_release(&committer_ident);
820 fclose(s->fp);
823 * Reject an attempt to record a non-merge empty commit without
824 * explicit --allow-empty. In the cherry-pick case, it may be
825 * empty due to conflict resolution, which the user should okay.
827 if (!commitable && whence != FROM_MERGE && !allow_empty &&
828 !(amend && is_a_merge(current_head))) {
829 s->display_comment_prefix = old_display_comment_prefix;
830 run_status(stdout, index_file, prefix, 0, s);
831 if (amend)
832 fputs(_(empty_amend_advice), stderr);
833 else if (whence == FROM_CHERRY_PICK) {
834 fputs(_(empty_cherry_pick_advice), stderr);
835 if (!sequencer_in_use)
836 fputs(_(empty_cherry_pick_advice_single), stderr);
837 else
838 fputs(_(empty_cherry_pick_advice_multi), stderr);
840 return 0;
844 * Re-read the index as pre-commit hook could have updated it,
845 * and write it out as a tree. We must do this before we invoke
846 * the editor and after we invoke run_status above.
848 discard_cache();
849 read_cache_from(index_file);
850 if (update_main_cache_tree(0)) {
851 error(_("Error building trees"));
852 return 0;
855 if (run_hook(index_file, "prepare-commit-msg",
856 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
857 return 0;
859 if (use_editor) {
860 char index[PATH_MAX];
861 const char *env[2] = { NULL };
862 env[0] = index;
863 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
864 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
865 fprintf(stderr,
866 _("Please supply the message using either -m or -F option.\n"));
867 exit(1);
871 if (!no_verify &&
872 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
873 return 0;
876 return 1;
879 static int rest_is_empty(struct strbuf *sb, int start)
881 int i, eol;
882 const char *nl;
884 /* Check if the rest is just whitespace and Signed-of-by's. */
885 for (i = start; i < sb->len; i++) {
886 nl = memchr(sb->buf + i, '\n', sb->len - i);
887 if (nl)
888 eol = nl - sb->buf;
889 else
890 eol = sb->len;
892 if (strlen(sign_off_header) <= eol - i &&
893 !prefixcmp(sb->buf + i, sign_off_header)) {
894 i = eol;
895 continue;
897 while (i < eol)
898 if (!isspace(sb->buf[i++]))
899 return 0;
902 return 1;
906 * Find out if the message in the strbuf contains only whitespace and
907 * Signed-off-by lines.
909 static int message_is_empty(struct strbuf *sb)
911 if (cleanup_mode == CLEANUP_NONE && sb->len)
912 return 0;
913 return rest_is_empty(sb, 0);
917 * See if the user edited the message in the editor or left what
918 * was in the template intact
920 static int template_untouched(struct strbuf *sb)
922 struct strbuf tmpl = STRBUF_INIT;
923 char *start;
925 if (cleanup_mode == CLEANUP_NONE && sb->len)
926 return 0;
928 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
929 return 0;
931 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
932 start = (char *)skip_prefix(sb->buf, tmpl.buf);
933 if (!start)
934 start = sb->buf;
935 strbuf_release(&tmpl);
936 return rest_is_empty(sb, start - sb->buf);
939 static const char *find_author_by_nickname(const char *name)
941 struct rev_info revs;
942 struct commit *commit;
943 struct strbuf buf = STRBUF_INIT;
944 const char *av[20];
945 int ac = 0;
947 init_revisions(&revs, NULL);
948 strbuf_addf(&buf, "--author=%s", name);
949 av[++ac] = "--all";
950 av[++ac] = "-i";
951 av[++ac] = buf.buf;
952 av[++ac] = NULL;
953 setup_revisions(ac, av, &revs, NULL);
954 prepare_revision_walk(&revs);
955 commit = get_revision(&revs);
956 if (commit) {
957 struct pretty_print_context ctx = {0};
958 ctx.date_mode = DATE_NORMAL;
959 strbuf_release(&buf);
960 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
961 return strbuf_detach(&buf, NULL);
963 die(_("No existing author found with '%s'"), name);
967 static void handle_untracked_files_arg(struct wt_status *s)
969 if (!untracked_files_arg)
970 ; /* default already initialized */
971 else if (!strcmp(untracked_files_arg, "no"))
972 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
973 else if (!strcmp(untracked_files_arg, "normal"))
974 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
975 else if (!strcmp(untracked_files_arg, "all"))
976 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
977 else
978 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
981 static const char *read_commit_message(const char *name)
983 const char *out_enc;
984 struct commit *commit;
986 commit = lookup_commit_reference_by_name(name);
987 if (!commit)
988 die(_("could not lookup commit %s"), name);
989 out_enc = get_commit_output_encoding();
990 return logmsg_reencode(commit, NULL, out_enc);
994 * Enumerate what needs to be propagated when --porcelain
995 * is not in effect here.
997 static struct status_deferred_config {
998 enum status_format status_format;
999 int show_branch;
1000 } status_deferred_config = {
1001 STATUS_FORMAT_UNSPECIFIED,
1002 -1 /* unspecified */
1005 static void finalize_deferred_config(struct wt_status *s)
1007 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1008 !s->null_termination);
1010 if (s->null_termination) {
1011 if (status_format == STATUS_FORMAT_NONE ||
1012 status_format == STATUS_FORMAT_UNSPECIFIED)
1013 status_format = STATUS_FORMAT_PORCELAIN;
1014 else if (status_format == STATUS_FORMAT_LONG)
1015 die(_("--long and -z are incompatible"));
1018 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1019 status_format = status_deferred_config.status_format;
1020 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1021 status_format = STATUS_FORMAT_NONE;
1023 if (use_deferred_config && s->show_branch < 0)
1024 s->show_branch = status_deferred_config.show_branch;
1025 if (s->show_branch < 0)
1026 s->show_branch = 0;
1029 static int parse_and_validate_options(int argc, const char *argv[],
1030 const struct option *options,
1031 const char * const usage[],
1032 const char *prefix,
1033 struct commit *current_head,
1034 struct wt_status *s)
1036 int f = 0;
1038 argc = parse_options(argc, argv, prefix, options, usage, 0);
1039 finalize_deferred_config(s);
1041 if (force_author && !strchr(force_author, '>'))
1042 force_author = find_author_by_nickname(force_author);
1044 if (force_author && renew_authorship)
1045 die(_("Using both --reset-author and --author does not make sense"));
1047 if (logfile || have_option_m || use_message || fixup_message)
1048 use_editor = 0;
1049 if (0 <= edit_flag)
1050 use_editor = edit_flag;
1051 if (!use_editor)
1052 setenv("GIT_EDITOR", ":", 1);
1054 /* Sanity check options */
1055 if (amend && !current_head)
1056 die(_("You have nothing to amend."));
1057 if (amend && whence != FROM_COMMIT) {
1058 if (whence == FROM_MERGE)
1059 die(_("You are in the middle of a merge -- cannot amend."));
1060 else if (whence == FROM_CHERRY_PICK)
1061 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1063 if (fixup_message && squash_message)
1064 die(_("Options --squash and --fixup cannot be used together"));
1065 if (use_message)
1066 f++;
1067 if (edit_message)
1068 f++;
1069 if (fixup_message)
1070 f++;
1071 if (logfile)
1072 f++;
1073 if (f > 1)
1074 die(_("Only one of -c/-C/-F/--fixup can be used."));
1075 if (message.len && f > 0)
1076 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1077 if (f || message.len)
1078 template_file = NULL;
1079 if (edit_message)
1080 use_message = edit_message;
1081 if (amend && !use_message && !fixup_message)
1082 use_message = "HEAD";
1083 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1084 die(_("--reset-author can be used only with -C, -c or --amend."));
1085 if (use_message) {
1086 use_message_buffer = read_commit_message(use_message);
1087 if (!renew_authorship) {
1088 author_message = use_message;
1089 author_message_buffer = use_message_buffer;
1092 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1093 author_message = "CHERRY_PICK_HEAD";
1094 author_message_buffer = read_commit_message(author_message);
1097 if (patch_interactive)
1098 interactive = 1;
1100 if (!!also + !!only + !!all + !!interactive > 1)
1101 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1102 if (argc == 0 && (also || (only && !amend)))
1103 die(_("No paths with --include/--only does not make sense."));
1104 if (argc == 0 && only && amend)
1105 only_include_assumed = _("Clever... amending the last one with dirty index.");
1106 if (argc > 0 && !also && !only)
1107 only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1108 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1109 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1110 else if (!strcmp(cleanup_arg, "verbatim"))
1111 cleanup_mode = CLEANUP_NONE;
1112 else if (!strcmp(cleanup_arg, "whitespace"))
1113 cleanup_mode = CLEANUP_SPACE;
1114 else if (!strcmp(cleanup_arg, "strip"))
1115 cleanup_mode = CLEANUP_ALL;
1116 else
1117 die(_("Invalid cleanup mode %s"), cleanup_arg);
1119 handle_untracked_files_arg(s);
1121 if (all && argc > 0)
1122 die(_("Paths with -a does not make sense."));
1124 if (status_format != STATUS_FORMAT_NONE)
1125 dry_run = 1;
1127 return argc;
1130 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1131 const struct commit *current_head, struct wt_status *s)
1133 int commitable;
1134 const char *index_file;
1136 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1137 commitable = run_status(stdout, index_file, prefix, 0, s);
1138 rollback_index_files();
1140 return commitable ? 0 : 1;
1143 static int parse_status_slot(const char *var, int offset)
1145 if (!strcasecmp(var+offset, "header"))
1146 return WT_STATUS_HEADER;
1147 if (!strcasecmp(var+offset, "branch"))
1148 return WT_STATUS_ONBRANCH;
1149 if (!strcasecmp(var+offset, "updated")
1150 || !strcasecmp(var+offset, "added"))
1151 return WT_STATUS_UPDATED;
1152 if (!strcasecmp(var+offset, "changed"))
1153 return WT_STATUS_CHANGED;
1154 if (!strcasecmp(var+offset, "untracked"))
1155 return WT_STATUS_UNTRACKED;
1156 if (!strcasecmp(var+offset, "nobranch"))
1157 return WT_STATUS_NOBRANCH;
1158 if (!strcasecmp(var+offset, "unmerged"))
1159 return WT_STATUS_UNMERGED;
1160 return -1;
1163 static int git_status_config(const char *k, const char *v, void *cb)
1165 struct wt_status *s = cb;
1167 if (!prefixcmp(k, "column."))
1168 return git_column_config(k, v, "status", &s->colopts);
1169 if (!strcmp(k, "status.submodulesummary")) {
1170 int is_bool;
1171 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1172 if (is_bool && s->submodule_summary)
1173 s->submodule_summary = -1;
1174 return 0;
1176 if (!strcmp(k, "status.short")) {
1177 if (git_config_bool(k, v))
1178 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1179 else
1180 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1181 return 0;
1183 if (!strcmp(k, "status.branch")) {
1184 status_deferred_config.show_branch = git_config_bool(k, v);
1185 return 0;
1187 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1188 s->use_color = git_config_colorbool(k, v);
1189 return 0;
1191 if (!strcmp(k, "status.displaycommentprefix")) {
1192 s->display_comment_prefix = git_config_bool(k, v);
1193 return 0;
1195 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1196 int slot = parse_status_slot(k, 13);
1197 if (slot < 0)
1198 return 0;
1199 if (!v)
1200 return config_error_nonbool(k);
1201 color_parse(v, k, s->color_palette[slot]);
1202 return 0;
1204 if (!strcmp(k, "status.relativepaths")) {
1205 s->relative_paths = git_config_bool(k, v);
1206 return 0;
1208 if (!strcmp(k, "status.showuntrackedfiles")) {
1209 if (!v)
1210 return config_error_nonbool(k);
1211 else if (!strcmp(v, "no"))
1212 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1213 else if (!strcmp(v, "normal"))
1214 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1215 else if (!strcmp(v, "all"))
1216 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1217 else
1218 return error(_("Invalid untracked files mode '%s'"), v);
1219 return 0;
1221 return git_diff_ui_config(k, v, NULL);
1224 int cmd_status(int argc, const char **argv, const char *prefix)
1226 static struct wt_status s;
1227 int fd;
1228 unsigned char sha1[20];
1229 static struct option builtin_status_options[] = {
1230 OPT__VERBOSE(&verbose, N_("be verbose")),
1231 OPT_SET_INT('s', "short", &status_format,
1232 N_("show status concisely"), STATUS_FORMAT_SHORT),
1233 OPT_BOOL('b', "branch", &s.show_branch,
1234 N_("show branch information")),
1235 OPT_SET_INT(0, "porcelain", &status_format,
1236 N_("machine-readable output"),
1237 STATUS_FORMAT_PORCELAIN),
1238 OPT_SET_INT(0, "long", &status_format,
1239 N_("show status in long format (default)"),
1240 STATUS_FORMAT_LONG),
1241 OPT_BOOLEAN('z', "null", &s.null_termination,
1242 N_("terminate entries with NUL")),
1243 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1244 N_("mode"),
1245 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1246 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1247 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1248 N_("show ignored files")),
1249 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1250 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1251 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1252 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1253 OPT_END(),
1256 if (argc == 2 && !strcmp(argv[1], "-h"))
1257 usage_with_options(builtin_status_usage, builtin_status_options);
1259 wt_status_prepare(&s);
1260 gitmodules_config();
1261 git_config(git_status_config, &s);
1262 determine_whence(&s);
1263 argc = parse_options(argc, argv, prefix,
1264 builtin_status_options,
1265 builtin_status_usage, 0);
1266 finalize_colopts(&s.colopts, -1);
1267 finalize_deferred_config(&s);
1269 handle_untracked_files_arg(&s);
1270 if (show_ignored_in_status)
1271 s.show_ignored_files = 1;
1272 if (*argv)
1273 s.pathspec = get_pathspec(prefix, argv);
1275 read_cache_preload(s.pathspec);
1276 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1278 fd = hold_locked_index(&index_lock, 0);
1279 if (0 <= fd)
1280 update_index_if_able(&the_index, &index_lock);
1282 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1283 s.ignore_submodule_arg = ignore_submodule_arg;
1284 wt_status_collect(&s);
1286 if (s.relative_paths)
1287 s.prefix = prefix;
1289 switch (status_format) {
1290 case STATUS_FORMAT_SHORT:
1291 wt_shortstatus_print(&s);
1292 break;
1293 case STATUS_FORMAT_PORCELAIN:
1294 wt_porcelain_print(&s);
1295 break;
1296 case STATUS_FORMAT_UNSPECIFIED:
1297 die("BUG: finalize_deferred_config() should have been called");
1298 break;
1299 case STATUS_FORMAT_NONE:
1300 case STATUS_FORMAT_LONG:
1301 s.verbose = verbose;
1302 s.ignore_submodule_arg = ignore_submodule_arg;
1303 wt_status_print(&s);
1304 break;
1306 return 0;
1309 static void print_summary(const char *prefix, const unsigned char *sha1,
1310 int initial_commit)
1312 struct rev_info rev;
1313 struct commit *commit;
1314 struct strbuf format = STRBUF_INIT;
1315 unsigned char junk_sha1[20];
1316 const char *head;
1317 struct pretty_print_context pctx = {0};
1318 struct strbuf author_ident = STRBUF_INIT;
1319 struct strbuf committer_ident = STRBUF_INIT;
1321 commit = lookup_commit(sha1);
1322 if (!commit)
1323 die(_("couldn't look up newly created commit"));
1324 if (!commit || parse_commit(commit))
1325 die(_("could not parse newly created commit"));
1327 strbuf_addstr(&format, "format:%h] %s");
1329 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1330 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1331 if (strbuf_cmp(&author_ident, &committer_ident)) {
1332 strbuf_addstr(&format, "\n Author: ");
1333 strbuf_addbuf_percentquote(&format, &author_ident);
1335 if (!committer_ident_sufficiently_given()) {
1336 strbuf_addstr(&format, "\n Committer: ");
1337 strbuf_addbuf_percentquote(&format, &committer_ident);
1338 if (advice_implicit_identity) {
1339 strbuf_addch(&format, '\n');
1340 strbuf_addstr(&format, _(implicit_ident_advice));
1343 strbuf_release(&author_ident);
1344 strbuf_release(&committer_ident);
1346 init_revisions(&rev, prefix);
1347 setup_revisions(0, NULL, &rev, NULL);
1349 rev.diff = 1;
1350 rev.diffopt.output_format =
1351 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1353 rev.verbose_header = 1;
1354 rev.show_root_diff = 1;
1355 get_commit_format(format.buf, &rev);
1356 rev.always_show_header = 0;
1357 rev.diffopt.detect_rename = 1;
1358 rev.diffopt.break_opt = 0;
1359 diff_setup_done(&rev.diffopt);
1361 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1362 printf("[%s%s ",
1363 !prefixcmp(head, "refs/heads/") ?
1364 head + 11 :
1365 !strcmp(head, "HEAD") ?
1366 _("detached HEAD") :
1367 head,
1368 initial_commit ? _(" (root-commit)") : "");
1370 if (!log_tree_commit(&rev, commit)) {
1371 rev.always_show_header = 1;
1372 rev.use_terminator = 1;
1373 log_tree_commit(&rev, commit);
1376 strbuf_release(&format);
1379 static int git_commit_config(const char *k, const char *v, void *cb)
1381 struct wt_status *s = cb;
1382 int status;
1384 if (!strcmp(k, "commit.template"))
1385 return git_config_pathname(&template_file, k, v);
1386 if (!strcmp(k, "commit.status")) {
1387 include_status = git_config_bool(k, v);
1388 return 0;
1390 if (!strcmp(k, "commit.cleanup"))
1391 return git_config_string(&cleanup_arg, k, v);
1393 status = git_gpg_config(k, v, NULL);
1394 if (status)
1395 return status;
1396 return git_status_config(k, v, s);
1399 static int run_rewrite_hook(const unsigned char *oldsha1,
1400 const unsigned char *newsha1)
1402 /* oldsha1 SP newsha1 LF NUL */
1403 static char buf[2*40 + 3];
1404 struct child_process proc;
1405 const char *argv[3];
1406 int code;
1407 size_t n;
1409 argv[0] = find_hook("post-rewrite");
1410 if (!argv[0])
1411 return 0;
1413 argv[1] = "amend";
1414 argv[2] = NULL;
1416 memset(&proc, 0, sizeof(proc));
1417 proc.argv = argv;
1418 proc.in = -1;
1419 proc.stdout_to_stderr = 1;
1421 code = start_command(&proc);
1422 if (code)
1423 return code;
1424 n = snprintf(buf, sizeof(buf), "%s %s\n",
1425 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1426 write_in_full(proc.in, buf, n);
1427 close(proc.in);
1428 return finish_command(&proc);
1431 int cmd_commit(int argc, const char **argv, const char *prefix)
1433 static struct wt_status s;
1434 static struct option builtin_commit_options[] = {
1435 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1436 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1438 OPT_GROUP(N_("Commit message options")),
1439 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1440 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1441 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1442 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1443 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1444 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1445 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1446 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1447 OPT_BOOLEAN(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1448 OPT_BOOLEAN('s', "signoff", &signoff, N_("add Signed-off-by:")),
1449 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1450 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1451 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1452 OPT_BOOLEAN(0, "status", &include_status, N_("include status in commit message template")),
1453 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key id"),
1454 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1455 /* end commit message options */
1457 OPT_GROUP(N_("Commit contents options")),
1458 OPT_BOOLEAN('a', "all", &all, N_("commit all changed files")),
1459 OPT_BOOLEAN('i', "include", &also, N_("add specified files to index for commit")),
1460 OPT_BOOLEAN(0, "interactive", &interactive, N_("interactively add files")),
1461 OPT_BOOLEAN('p', "patch", &patch_interactive, N_("interactively add changes")),
1462 OPT_BOOLEAN('o', "only", &only, N_("commit only specified files")),
1463 OPT_BOOLEAN('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1464 OPT_BOOLEAN(0, "dry-run", &dry_run, N_("show what would be committed")),
1465 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1466 STATUS_FORMAT_SHORT),
1467 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1468 OPT_SET_INT(0, "porcelain", &status_format,
1469 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1470 OPT_SET_INT(0, "long", &status_format,
1471 N_("show status in long format (default)"),
1472 STATUS_FORMAT_LONG),
1473 OPT_BOOLEAN('z', "null", &s.null_termination,
1474 N_("terminate entries with NUL")),
1475 OPT_BOOLEAN(0, "amend", &amend, N_("amend previous commit")),
1476 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1477 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, N_("mode"), N_("show untracked files, optional modes: all, normal, no. (Default: all)"), PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1478 /* end commit contents options */
1480 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
1481 N_("ok to record an empty change"),
1482 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1483 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
1484 N_("ok to record a change with an empty message"),
1485 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1487 OPT_END()
1490 struct strbuf sb = STRBUF_INIT;
1491 struct strbuf author_ident = STRBUF_INIT;
1492 const char *index_file, *reflog_msg;
1493 char *nl, *p;
1494 unsigned char sha1[20];
1495 struct ref_lock *ref_lock;
1496 struct commit_list *parents = NULL, **pptr = &parents;
1497 struct stat statbuf;
1498 int allow_fast_forward = 1;
1499 struct commit *current_head = NULL;
1500 struct commit_extra_header *extra = NULL;
1502 if (argc == 2 && !strcmp(argv[1], "-h"))
1503 usage_with_options(builtin_commit_usage, builtin_commit_options);
1505 wt_status_prepare(&s);
1506 gitmodules_config();
1507 git_config(git_commit_config, &s);
1508 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1509 determine_whence(&s);
1510 s.colopts = 0;
1512 if (get_sha1("HEAD", sha1))
1513 current_head = NULL;
1514 else {
1515 current_head = lookup_commit_or_die(sha1, "HEAD");
1516 if (!current_head || parse_commit(current_head))
1517 die(_("could not parse HEAD commit"));
1519 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1520 builtin_commit_usage,
1521 prefix, current_head, &s);
1522 if (dry_run)
1523 return dry_run_commit(argc, argv, prefix, current_head, &s);
1524 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1526 /* Set up everything for writing the commit object. This includes
1527 running hooks, writing the trees, and interacting with the user. */
1528 if (!prepare_to_commit(index_file, prefix,
1529 current_head, &s, &author_ident)) {
1530 rollback_index_files();
1531 return 1;
1534 /* Determine parents */
1535 reflog_msg = getenv("GIT_REFLOG_ACTION");
1536 if (!current_head) {
1537 if (!reflog_msg)
1538 reflog_msg = "commit (initial)";
1539 } else if (amend) {
1540 struct commit_list *c;
1542 if (!reflog_msg)
1543 reflog_msg = "commit (amend)";
1544 for (c = current_head->parents; c; c = c->next)
1545 pptr = &commit_list_insert(c->item, pptr)->next;
1546 } else if (whence == FROM_MERGE) {
1547 struct strbuf m = STRBUF_INIT;
1548 FILE *fp;
1550 if (!reflog_msg)
1551 reflog_msg = "commit (merge)";
1552 pptr = &commit_list_insert(current_head, pptr)->next;
1553 fp = fopen(git_path("MERGE_HEAD"), "r");
1554 if (fp == NULL)
1555 die_errno(_("could not open '%s' for reading"),
1556 git_path("MERGE_HEAD"));
1557 while (strbuf_getline(&m, fp, '\n') != EOF) {
1558 struct commit *parent;
1560 parent = get_merge_parent(m.buf);
1561 if (!parent)
1562 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1563 pptr = &commit_list_insert(parent, pptr)->next;
1565 fclose(fp);
1566 strbuf_release(&m);
1567 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1568 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1569 die_errno(_("could not read MERGE_MODE"));
1570 if (!strcmp(sb.buf, "no-ff"))
1571 allow_fast_forward = 0;
1573 if (allow_fast_forward)
1574 parents = reduce_heads(parents);
1575 } else {
1576 if (!reflog_msg)
1577 reflog_msg = (whence == FROM_CHERRY_PICK)
1578 ? "commit (cherry-pick)"
1579 : "commit";
1580 pptr = &commit_list_insert(current_head, pptr)->next;
1583 /* Finally, get the commit message */
1584 strbuf_reset(&sb);
1585 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1586 int saved_errno = errno;
1587 rollback_index_files();
1588 die(_("could not read commit message: %s"), strerror(saved_errno));
1591 /* Truncate the message just before the diff, if any. */
1592 if (verbose) {
1593 p = strstr(sb.buf, "\ndiff --git ");
1594 if (p != NULL)
1595 strbuf_setlen(&sb, p - sb.buf + 1);
1598 if (cleanup_mode != CLEANUP_NONE)
1599 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1600 if (template_untouched(&sb) && !allow_empty_message) {
1601 rollback_index_files();
1602 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1603 exit(1);
1605 if (message_is_empty(&sb) && !allow_empty_message) {
1606 rollback_index_files();
1607 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1608 exit(1);
1611 if (amend) {
1612 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1613 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1614 } else {
1615 struct commit_extra_header **tail = &extra;
1616 append_merge_tag_headers(parents, &tail);
1619 if (commit_tree_extended(&sb, active_cache_tree->sha1, parents, sha1,
1620 author_ident.buf, sign_commit, extra)) {
1621 rollback_index_files();
1622 die(_("failed to write commit object"));
1624 strbuf_release(&author_ident);
1625 free_commit_extra_headers(extra);
1627 ref_lock = lock_any_ref_for_update("HEAD",
1628 !current_head
1629 ? NULL
1630 : current_head->object.sha1,
1633 nl = strchr(sb.buf, '\n');
1634 if (nl)
1635 strbuf_setlen(&sb, nl + 1 - sb.buf);
1636 else
1637 strbuf_addch(&sb, '\n');
1638 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1639 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1641 if (!ref_lock) {
1642 rollback_index_files();
1643 die(_("cannot lock HEAD ref"));
1645 if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1646 rollback_index_files();
1647 die(_("cannot update HEAD ref"));
1650 unlink(git_path("CHERRY_PICK_HEAD"));
1651 unlink(git_path("REVERT_HEAD"));
1652 unlink(git_path("MERGE_HEAD"));
1653 unlink(git_path("MERGE_MSG"));
1654 unlink(git_path("MERGE_MODE"));
1655 unlink(git_path("SQUASH_MSG"));
1657 if (commit_index_files())
1658 die (_("Repository has been updated, but unable to write\n"
1659 "new_index file. Check that disk is not full or quota is\n"
1660 "not exceeded, and then \"git reset HEAD\" to recover."));
1662 rerere(0);
1663 run_hook(get_index_file(), "post-commit", NULL);
1664 if (amend && !no_post_rewrite) {
1665 struct notes_rewrite_cfg *cfg;
1666 cfg = init_copy_notes_for_rewrite("amend");
1667 if (cfg) {
1668 /* we are amending, so current_head is not NULL */
1669 copy_note_for_rewrite(cfg, current_head->object.sha1, sha1);
1670 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1672 run_rewrite_hook(current_head->object.sha1, sha1);
1674 if (!quiet)
1675 print_summary(prefix, sha1, !current_head);
1677 return 0;