Merge branch 'maint'
[git/gitweb.git] / builtin / commit.c
blob1621dfcd4008fc5853fc078a32bf9eefb6c52023
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"
33 static const char * const builtin_commit_usage[] = {
34 N_("git commit [options] [--] <pathspec>..."),
35 NULL
38 static const char * const builtin_status_usage[] = {
39 N_("git status [options] [--] <pathspec>..."),
40 NULL
43 static const char implicit_ident_advice[] =
44 N_("Your name and email address were configured automatically based\n"
45 "on your username and hostname. Please check that they are accurate.\n"
46 "You can suppress this message by setting them explicitly:\n"
47 "\n"
48 " git config --global user.name \"Your Name\"\n"
49 " git config --global user.email you@example.com\n"
50 "\n"
51 "After doing this, you may fix the identity used for this commit with:\n"
52 "\n"
53 " git commit --amend --reset-author\n");
55 static const char empty_amend_advice[] =
56 N_("You asked to amend the most recent commit, but doing so would make\n"
57 "it empty. You can repeat your command with --allow-empty, or you can\n"
58 "remove the commit entirely with \"git reset HEAD^\".\n");
60 static const char empty_cherry_pick_advice[] =
61 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
62 "If you wish to commit it anyway, use:\n"
63 "\n"
64 " git commit --allow-empty\n"
65 "\n"
66 "Otherwise, please use 'git reset'\n");
68 static const char *use_message_buffer;
69 static const char commit_editmsg[] = "COMMIT_EDITMSG";
70 static struct lock_file index_lock; /* real index */
71 static struct lock_file false_lock; /* used only for partial commits */
72 static enum {
73 COMMIT_AS_IS = 1,
74 COMMIT_NORMAL,
75 COMMIT_PARTIAL
76 } commit_style;
78 static const char *logfile, *force_author;
79 static const char *template_file;
81 * The _message variables are commit names from which to take
82 * the commit message and/or authorship.
84 static const char *author_message, *author_message_buffer;
85 static char *edit_message, *use_message;
86 static char *fixup_message, *squash_message;
87 static int all, also, interactive, patch_interactive, only, amend, signoff;
88 static int edit_flag = -1; /* unspecified */
89 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
90 static int no_post_rewrite, allow_empty_message;
91 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
92 static char *sign_commit;
95 * The default commit message cleanup mode will remove the lines
96 * beginning with # (shell comments) and leading and trailing
97 * whitespaces (empty lines or containing only whitespaces)
98 * if editor is used, and only the whitespaces if the message
99 * is specified explicitly.
101 static enum {
102 CLEANUP_SPACE,
103 CLEANUP_NONE,
104 CLEANUP_ALL
105 } cleanup_mode;
106 static const char *cleanup_arg;
108 static enum commit_whence whence;
109 static int use_editor = 1, include_status = 1;
110 static int show_ignored_in_status, have_option_m;
111 static const char *only_include_assumed;
112 static struct strbuf message = STRBUF_INIT;
114 static enum {
115 STATUS_FORMAT_NONE = 0,
116 STATUS_FORMAT_LONG,
117 STATUS_FORMAT_SHORT,
118 STATUS_FORMAT_PORCELAIN
119 } status_format;
121 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
123 struct strbuf *buf = opt->value;
124 if (unset) {
125 have_option_m = 0;
126 strbuf_setlen(buf, 0);
127 } else {
128 have_option_m = 1;
129 if (buf->len)
130 strbuf_addch(buf, '\n');
131 strbuf_addstr(buf, arg);
132 strbuf_complete_line(buf);
134 return 0;
137 static void determine_whence(struct wt_status *s)
139 if (file_exists(git_path("MERGE_HEAD")))
140 whence = FROM_MERGE;
141 else if (file_exists(git_path("CHERRY_PICK_HEAD")))
142 whence = FROM_CHERRY_PICK;
143 else
144 whence = FROM_COMMIT;
145 if (s)
146 s->whence = whence;
149 static void rollback_index_files(void)
151 switch (commit_style) {
152 case COMMIT_AS_IS:
153 break; /* nothing to do */
154 case COMMIT_NORMAL:
155 rollback_lock_file(&index_lock);
156 break;
157 case COMMIT_PARTIAL:
158 rollback_lock_file(&index_lock);
159 rollback_lock_file(&false_lock);
160 break;
164 static int commit_index_files(void)
166 int err = 0;
168 switch (commit_style) {
169 case COMMIT_AS_IS:
170 break; /* nothing to do */
171 case COMMIT_NORMAL:
172 err = commit_lock_file(&index_lock);
173 break;
174 case COMMIT_PARTIAL:
175 err = commit_lock_file(&index_lock);
176 rollback_lock_file(&false_lock);
177 break;
180 return err;
184 * Take a union of paths in the index and the named tree (typically, "HEAD"),
185 * and return the paths that match the given pattern in list.
187 static int list_paths(struct string_list *list, const char *with_tree,
188 const char *prefix, const char **pattern)
190 int i;
191 char *m;
193 if (!pattern)
194 return 0;
196 for (i = 0; pattern[i]; i++)
198 m = xcalloc(1, i);
200 if (with_tree) {
201 char *max_prefix = common_prefix(pattern);
202 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
203 free(max_prefix);
206 for (i = 0; i < active_nr; i++) {
207 struct cache_entry *ce = active_cache[i];
208 struct string_list_item *item;
210 if (ce->ce_flags & CE_UPDATE)
211 continue;
212 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
213 continue;
214 item = string_list_insert(list, ce->name);
215 if (ce_skip_worktree(ce))
216 item->util = item; /* better a valid pointer than a fake one */
219 return report_path_error(m, pattern, prefix);
222 static void add_remove_files(struct string_list *list)
224 int i;
225 for (i = 0; i < list->nr; i++) {
226 struct stat st;
227 struct string_list_item *p = &(list->items[i]);
229 /* p->util is skip-worktree */
230 if (p->util)
231 continue;
233 if (!lstat(p->string, &st)) {
234 if (add_to_cache(p->string, &st, 0))
235 die(_("updating files failed"));
236 } else
237 remove_file_from_cache(p->string);
241 static void create_base_index(const struct commit *current_head)
243 struct tree *tree;
244 struct unpack_trees_options opts;
245 struct tree_desc t;
247 if (!current_head) {
248 discard_cache();
249 return;
252 memset(&opts, 0, sizeof(opts));
253 opts.head_idx = 1;
254 opts.index_only = 1;
255 opts.merge = 1;
256 opts.src_index = &the_index;
257 opts.dst_index = &the_index;
259 opts.fn = oneway_merge;
260 tree = parse_tree_indirect(current_head->object.sha1);
261 if (!tree)
262 die(_("failed to unpack HEAD tree object"));
263 parse_tree(tree);
264 init_tree_desc(&t, tree->buffer, tree->size);
265 if (unpack_trees(1, &t, &opts))
266 exit(128); /* We've already reported the error, finish dying */
269 static void refresh_cache_or_die(int refresh_flags)
272 * refresh_flags contains REFRESH_QUIET, so the only errors
273 * are for unmerged entries.
275 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
276 die_resolve_conflict("commit");
279 static char *prepare_index(int argc, const char **argv, const char *prefix,
280 const struct commit *current_head, int is_status)
282 int fd;
283 struct string_list partial;
284 const char **pathspec = NULL;
285 char *old_index_env = NULL;
286 int refresh_flags = REFRESH_QUIET;
288 if (is_status)
289 refresh_flags |= REFRESH_UNMERGED;
291 if (*argv)
292 pathspec = get_pathspec(prefix, argv);
294 if (read_cache_preload(pathspec) < 0)
295 die(_("index file corrupt"));
297 if (interactive) {
298 fd = hold_locked_index(&index_lock, 1);
300 refresh_cache_or_die(refresh_flags);
302 if (write_cache(fd, active_cache, active_nr) ||
303 close_lock_file(&index_lock))
304 die(_("unable to create temporary index"));
306 old_index_env = getenv(INDEX_ENVIRONMENT);
307 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
309 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
310 die(_("interactive add failed"));
312 if (old_index_env && *old_index_env)
313 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
314 else
315 unsetenv(INDEX_ENVIRONMENT);
317 discard_cache();
318 read_cache_from(index_lock.filename);
320 commit_style = COMMIT_NORMAL;
321 return index_lock.filename;
325 * Non partial, non as-is commit.
327 * (1) get the real index;
328 * (2) update the_index as necessary;
329 * (3) write the_index out to the real index (still locked);
330 * (4) return the name of the locked index file.
332 * The caller should run hooks on the locked real index, and
333 * (A) if all goes well, commit the real index;
334 * (B) on failure, rollback the real index.
336 if (all || (also && pathspec && *pathspec)) {
337 fd = hold_locked_index(&index_lock, 1);
338 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
339 refresh_cache_or_die(refresh_flags);
340 update_main_cache_tree(WRITE_TREE_SILENT);
341 if (write_cache(fd, active_cache, active_nr) ||
342 close_lock_file(&index_lock))
343 die(_("unable to write new_index file"));
344 commit_style = COMMIT_NORMAL;
345 return index_lock.filename;
349 * As-is commit.
351 * (1) return the name of the real index file.
353 * The caller should run hooks on the real index,
354 * and create commit from the_index.
355 * We still need to refresh the index here.
357 if (!only && (!pathspec || !*pathspec)) {
358 fd = hold_locked_index(&index_lock, 1);
359 refresh_cache_or_die(refresh_flags);
360 if (active_cache_changed) {
361 update_main_cache_tree(WRITE_TREE_SILENT);
362 if (write_cache(fd, active_cache, active_nr) ||
363 commit_locked_index(&index_lock))
364 die(_("unable to write new_index file"));
365 } else {
366 rollback_lock_file(&index_lock);
368 commit_style = COMMIT_AS_IS;
369 return get_index_file();
373 * A partial commit.
375 * (0) find the set of affected paths;
376 * (1) get lock on the real index file;
377 * (2) update the_index with the given paths;
378 * (3) write the_index out to the real index (still locked);
379 * (4) get lock on the false index file;
380 * (5) reset the_index from HEAD;
381 * (6) update the_index the same way as (2);
382 * (7) write the_index out to the false index file;
383 * (8) return the name of the false index file (still locked);
385 * The caller should run hooks on the locked false index, and
386 * create commit from it. Then
387 * (A) if all goes well, commit the real index;
388 * (B) on failure, rollback the real index;
389 * In either case, rollback the false index.
391 commit_style = COMMIT_PARTIAL;
393 if (whence != FROM_COMMIT) {
394 if (whence == FROM_MERGE)
395 die(_("cannot do a partial commit during a merge."));
396 else if (whence == FROM_CHERRY_PICK)
397 die(_("cannot do a partial commit during a cherry-pick."));
400 memset(&partial, 0, sizeof(partial));
401 partial.strdup_strings = 1;
402 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, pathspec))
403 exit(1);
405 discard_cache();
406 if (read_cache() < 0)
407 die(_("cannot read the index"));
409 fd = hold_locked_index(&index_lock, 1);
410 add_remove_files(&partial);
411 refresh_cache(REFRESH_QUIET);
412 if (write_cache(fd, active_cache, active_nr) ||
413 close_lock_file(&index_lock))
414 die(_("unable to write new_index file"));
416 fd = hold_lock_file_for_update(&false_lock,
417 git_path("next-index-%"PRIuMAX,
418 (uintmax_t) getpid()),
419 LOCK_DIE_ON_ERROR);
421 create_base_index(current_head);
422 add_remove_files(&partial);
423 refresh_cache(REFRESH_QUIET);
425 if (write_cache(fd, active_cache, active_nr) ||
426 close_lock_file(&false_lock))
427 die(_("unable to write temporary index file"));
429 discard_cache();
430 read_cache_from(false_lock.filename);
432 return false_lock.filename;
435 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
436 struct wt_status *s)
438 unsigned char sha1[20];
440 if (s->relative_paths)
441 s->prefix = prefix;
443 if (amend) {
444 s->amend = 1;
445 s->reference = "HEAD^1";
447 s->verbose = verbose;
448 s->index_file = index_file;
449 s->fp = fp;
450 s->nowarn = nowarn;
451 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
453 wt_status_collect(s);
455 switch (status_format) {
456 case STATUS_FORMAT_SHORT:
457 wt_shortstatus_print(s);
458 break;
459 case STATUS_FORMAT_PORCELAIN:
460 wt_porcelain_print(s);
461 break;
462 case STATUS_FORMAT_NONE:
463 case STATUS_FORMAT_LONG:
464 wt_status_print(s);
465 break;
468 return s->commitable;
471 static int is_a_merge(const struct commit *current_head)
473 return !!(current_head->parents && current_head->parents->next);
476 static void export_one(const char *var, const char *s, const char *e, int hack)
478 struct strbuf buf = STRBUF_INIT;
479 if (hack)
480 strbuf_addch(&buf, hack);
481 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
482 setenv(var, buf.buf, 1);
483 strbuf_release(&buf);
486 static int sane_ident_split(struct ident_split *person)
488 if (!person->name_begin || !person->name_end ||
489 person->name_begin == person->name_end)
490 return 0; /* no human readable name */
491 if (!person->mail_begin || !person->mail_end ||
492 person->mail_begin == person->mail_end)
493 return 0; /* no usable mail */
494 if (!person->date_begin || !person->date_end ||
495 !person->tz_begin || !person->tz_end)
496 return 0;
497 return 1;
500 static void determine_author_info(struct strbuf *author_ident)
502 char *name, *email, *date;
503 struct ident_split author;
505 name = getenv("GIT_AUTHOR_NAME");
506 email = getenv("GIT_AUTHOR_EMAIL");
507 date = getenv("GIT_AUTHOR_DATE");
509 if (author_message) {
510 const char *a, *lb, *rb, *eol;
511 size_t len;
513 a = strstr(author_message_buffer, "\nauthor ");
514 if (!a)
515 die(_("invalid commit: %s"), author_message);
517 lb = strchrnul(a + strlen("\nauthor "), '<');
518 rb = strchrnul(lb, '>');
519 eol = strchrnul(rb, '\n');
520 if (!*lb || !*rb || !*eol)
521 die(_("invalid commit: %s"), author_message);
523 if (lb == a + strlen("\nauthor "))
524 /* \nauthor <foo@example.com> */
525 name = xcalloc(1, 1);
526 else
527 name = xmemdupz(a + strlen("\nauthor "),
528 (lb - strlen(" ") -
529 (a + strlen("\nauthor "))));
530 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
531 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
532 len = eol - (rb + strlen("> "));
533 date = xmalloc(len + 2);
534 *date = '@';
535 memcpy(date + 1, rb + strlen("> "), len);
536 date[len + 1] = '\0';
539 if (force_author) {
540 const char *lb = strstr(force_author, " <");
541 const char *rb = strchr(force_author, '>');
543 if (!lb || !rb)
544 die(_("malformed --author parameter"));
545 name = xstrndup(force_author, lb - force_author);
546 email = xstrndup(lb + 2, rb - (lb + 2));
549 if (force_date)
550 date = force_date;
551 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
552 if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
553 sane_ident_split(&author)) {
554 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
555 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
556 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
560 static char *cut_ident_timestamp_part(char *string)
562 char *ket = strrchr(string, '>');
563 if (!ket || ket[1] != ' ')
564 die(_("Malformed ident string: '%s'"), string);
565 *++ket = '\0';
566 return ket;
569 static int prepare_to_commit(const char *index_file, const char *prefix,
570 struct commit *current_head,
571 struct wt_status *s,
572 struct strbuf *author_ident)
574 struct stat statbuf;
575 struct strbuf committer_ident = STRBUF_INIT;
576 int commitable, saved_color_setting;
577 struct strbuf sb = STRBUF_INIT;
578 char *buffer;
579 const char *hook_arg1 = NULL;
580 const char *hook_arg2 = NULL;
581 int ident_shown = 0;
582 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
584 /* This checks and barfs if author is badly specified */
585 determine_author_info(author_ident);
587 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
588 return 0;
590 if (squash_message) {
592 * Insert the proper subject line before other commit
593 * message options add their content.
595 if (use_message && !strcmp(use_message, squash_message))
596 strbuf_addstr(&sb, "squash! ");
597 else {
598 struct pretty_print_context ctx = {0};
599 struct commit *c;
600 c = lookup_commit_reference_by_name(squash_message);
601 if (!c)
602 die(_("could not lookup commit %s"), squash_message);
603 ctx.output_encoding = get_commit_output_encoding();
604 format_commit_message(c, "squash! %s\n\n", &sb,
605 &ctx);
609 if (message.len) {
610 strbuf_addbuf(&sb, &message);
611 hook_arg1 = "message";
612 } else if (logfile && !strcmp(logfile, "-")) {
613 if (isatty(0))
614 fprintf(stderr, _("(reading log message from standard input)\n"));
615 if (strbuf_read(&sb, 0, 0) < 0)
616 die_errno(_("could not read log from standard input"));
617 hook_arg1 = "message";
618 } else if (logfile) {
619 if (strbuf_read_file(&sb, logfile, 0) < 0)
620 die_errno(_("could not read log file '%s'"),
621 logfile);
622 hook_arg1 = "message";
623 } else if (use_message) {
624 buffer = strstr(use_message_buffer, "\n\n");
625 if (!use_editor && (!buffer || buffer[2] == '\0'))
626 die(_("commit has empty message"));
627 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
628 hook_arg1 = "commit";
629 hook_arg2 = use_message;
630 } else if (fixup_message) {
631 struct pretty_print_context ctx = {0};
632 struct commit *commit;
633 commit = lookup_commit_reference_by_name(fixup_message);
634 if (!commit)
635 die(_("could not lookup commit %s"), fixup_message);
636 ctx.output_encoding = get_commit_output_encoding();
637 format_commit_message(commit, "fixup! %s\n\n",
638 &sb, &ctx);
639 hook_arg1 = "message";
640 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
641 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
642 die_errno(_("could not read MERGE_MSG"));
643 hook_arg1 = "merge";
644 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
645 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
646 die_errno(_("could not read SQUASH_MSG"));
647 hook_arg1 = "squash";
648 } else if (template_file) {
649 if (strbuf_read_file(&sb, template_file, 0) < 0)
650 die_errno(_("could not read '%s'"), template_file);
651 hook_arg1 = "template";
652 clean_message_contents = 0;
656 * The remaining cases don't modify the template message, but
657 * just set the argument(s) to the prepare-commit-msg hook.
659 else if (whence == FROM_MERGE)
660 hook_arg1 = "merge";
661 else if (whence == FROM_CHERRY_PICK) {
662 hook_arg1 = "commit";
663 hook_arg2 = "CHERRY_PICK_HEAD";
666 if (squash_message) {
668 * If squash_commit was used for the commit subject,
669 * then we're possibly hijacking other commit log options.
670 * Reset the hook args to tell the real story.
672 hook_arg1 = "message";
673 hook_arg2 = "";
676 s->fp = fopen(git_path(commit_editmsg), "w");
677 if (s->fp == NULL)
678 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
680 if (clean_message_contents)
681 stripspace(&sb, 0);
683 if (signoff) {
685 * See if we have a Conflicts: block at the end. If yes, count
686 * its size, so we can ignore it.
688 int ignore_footer = 0;
689 int i, eol, previous = 0;
690 const char *nl;
692 for (i = 0; i < sb.len; i++) {
693 nl = memchr(sb.buf + i, '\n', sb.len - i);
694 if (nl)
695 eol = nl - sb.buf;
696 else
697 eol = sb.len;
698 if (!prefixcmp(sb.buf + previous, "\nConflicts:\n")) {
699 ignore_footer = sb.len - previous;
700 break;
702 while (i < eol)
703 i++;
704 previous = eol;
707 append_signoff(&sb, ignore_footer, 0);
710 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
711 die_errno(_("could not write commit template"));
713 strbuf_release(&sb);
715 /* This checks if committer ident is explicitly given */
716 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
717 if (use_editor && include_status) {
718 char *ai_tmp, *ci_tmp;
719 if (whence != FROM_COMMIT)
720 status_printf_ln(s, GIT_COLOR_NORMAL,
721 whence == FROM_MERGE
722 ? _("\n"
723 "It looks like you may be committing a merge.\n"
724 "If this is not correct, please remove the file\n"
725 " %s\n"
726 "and try again.\n")
727 : _("\n"
728 "It looks like you may be committing a cherry-pick.\n"
729 "If this is not correct, please remove the file\n"
730 " %s\n"
731 "and try again.\n"),
732 git_path(whence == FROM_MERGE
733 ? "MERGE_HEAD"
734 : "CHERRY_PICK_HEAD"));
736 fprintf(s->fp, "\n");
737 if (cleanup_mode == CLEANUP_ALL)
738 status_printf(s, GIT_COLOR_NORMAL,
739 _("Please enter the commit message for your changes."
740 " Lines starting\nwith '%c' will be ignored, and an empty"
741 " message aborts the commit.\n"), comment_line_char);
742 else /* CLEANUP_SPACE, that is. */
743 status_printf(s, GIT_COLOR_NORMAL,
744 _("Please enter the commit message for your changes."
745 " Lines starting\n"
746 "with '%c' will be kept; you may remove them"
747 " yourself if you want to.\n"
748 "An empty message aborts the commit.\n"), comment_line_char);
749 if (only_include_assumed)
750 status_printf_ln(s, GIT_COLOR_NORMAL,
751 "%s", only_include_assumed);
753 ai_tmp = cut_ident_timestamp_part(author_ident->buf);
754 ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
755 if (strcmp(author_ident->buf, committer_ident.buf))
756 status_printf_ln(s, GIT_COLOR_NORMAL,
757 _("%s"
758 "Author: %s"),
759 ident_shown++ ? "" : "\n",
760 author_ident->buf);
762 if (!committer_ident_sufficiently_given())
763 status_printf_ln(s, GIT_COLOR_NORMAL,
764 _("%s"
765 "Committer: %s"),
766 ident_shown++ ? "" : "\n",
767 committer_ident.buf);
769 if (ident_shown)
770 status_printf_ln(s, GIT_COLOR_NORMAL, "");
772 saved_color_setting = s->use_color;
773 s->use_color = 0;
774 commitable = run_status(s->fp, index_file, prefix, 1, s);
775 s->use_color = saved_color_setting;
777 *ai_tmp = ' ';
778 *ci_tmp = ' ';
779 } else {
780 unsigned char sha1[20];
781 const char *parent = "HEAD";
783 if (!active_nr && read_cache() < 0)
784 die(_("Cannot read index"));
786 if (amend)
787 parent = "HEAD^1";
789 if (get_sha1(parent, sha1))
790 commitable = !!active_nr;
791 else
792 commitable = index_differs_from(parent, 0);
794 strbuf_release(&committer_ident);
796 fclose(s->fp);
799 * Reject an attempt to record a non-merge empty commit without
800 * explicit --allow-empty. In the cherry-pick case, it may be
801 * empty due to conflict resolution, which the user should okay.
803 if (!commitable && whence != FROM_MERGE && !allow_empty &&
804 !(amend && is_a_merge(current_head))) {
805 run_status(stdout, index_file, prefix, 0, s);
806 if (amend)
807 fputs(_(empty_amend_advice), stderr);
808 else if (whence == FROM_CHERRY_PICK)
809 fputs(_(empty_cherry_pick_advice), stderr);
810 return 0;
814 * Re-read the index as pre-commit hook could have updated it,
815 * and write it out as a tree. We must do this before we invoke
816 * the editor and after we invoke run_status above.
818 discard_cache();
819 read_cache_from(index_file);
820 if (update_main_cache_tree(0)) {
821 error(_("Error building trees"));
822 return 0;
825 if (run_hook(index_file, "prepare-commit-msg",
826 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
827 return 0;
829 if (use_editor) {
830 char index[PATH_MAX];
831 const char *env[2] = { NULL };
832 env[0] = index;
833 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
834 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
835 fprintf(stderr,
836 _("Please supply the message using either -m or -F option.\n"));
837 exit(1);
841 if (!no_verify &&
842 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
843 return 0;
846 return 1;
849 static int rest_is_empty(struct strbuf *sb, int start)
851 int i, eol;
852 const char *nl;
854 /* Check if the rest is just whitespace and Signed-of-by's. */
855 for (i = start; i < sb->len; i++) {
856 nl = memchr(sb->buf + i, '\n', sb->len - i);
857 if (nl)
858 eol = nl - sb->buf;
859 else
860 eol = sb->len;
862 if (strlen(sign_off_header) <= eol - i &&
863 !prefixcmp(sb->buf + i, sign_off_header)) {
864 i = eol;
865 continue;
867 while (i < eol)
868 if (!isspace(sb->buf[i++]))
869 return 0;
872 return 1;
876 * Find out if the message in the strbuf contains only whitespace and
877 * Signed-off-by lines.
879 static int message_is_empty(struct strbuf *sb)
881 if (cleanup_mode == CLEANUP_NONE && sb->len)
882 return 0;
883 return rest_is_empty(sb, 0);
887 * See if the user edited the message in the editor or left what
888 * was in the template intact
890 static int template_untouched(struct strbuf *sb)
892 struct strbuf tmpl = STRBUF_INIT;
893 char *start;
895 if (cleanup_mode == CLEANUP_NONE && sb->len)
896 return 0;
898 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
899 return 0;
901 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
902 start = (char *)skip_prefix(sb->buf, tmpl.buf);
903 if (!start)
904 start = sb->buf;
905 strbuf_release(&tmpl);
906 return rest_is_empty(sb, start - sb->buf);
909 static const char *find_author_by_nickname(const char *name)
911 struct rev_info revs;
912 struct commit *commit;
913 struct strbuf buf = STRBUF_INIT;
914 const char *av[20];
915 int ac = 0;
917 init_revisions(&revs, NULL);
918 strbuf_addf(&buf, "--author=%s", name);
919 av[++ac] = "--all";
920 av[++ac] = "-i";
921 av[++ac] = buf.buf;
922 av[++ac] = NULL;
923 setup_revisions(ac, av, &revs, NULL);
924 prepare_revision_walk(&revs);
925 commit = get_revision(&revs);
926 if (commit) {
927 struct pretty_print_context ctx = {0};
928 ctx.date_mode = DATE_NORMAL;
929 strbuf_release(&buf);
930 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
931 return strbuf_detach(&buf, NULL);
933 die(_("No existing author found with '%s'"), name);
937 static void handle_untracked_files_arg(struct wt_status *s)
939 if (!untracked_files_arg)
940 ; /* default already initialized */
941 else if (!strcmp(untracked_files_arg, "no"))
942 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
943 else if (!strcmp(untracked_files_arg, "normal"))
944 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
945 else if (!strcmp(untracked_files_arg, "all"))
946 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
947 else
948 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
951 static const char *read_commit_message(const char *name)
953 const char *out_enc;
954 struct commit *commit;
956 commit = lookup_commit_reference_by_name(name);
957 if (!commit)
958 die(_("could not lookup commit %s"), name);
959 out_enc = get_commit_output_encoding();
960 return logmsg_reencode(commit, NULL, out_enc);
963 static int parse_and_validate_options(int argc, const char *argv[],
964 const struct option *options,
965 const char * const usage[],
966 const char *prefix,
967 struct commit *current_head,
968 struct wt_status *s)
970 int f = 0;
972 argc = parse_options(argc, argv, prefix, options, usage, 0);
974 if (force_author && !strchr(force_author, '>'))
975 force_author = find_author_by_nickname(force_author);
977 if (force_author && renew_authorship)
978 die(_("Using both --reset-author and --author does not make sense"));
980 if (logfile || have_option_m || use_message || fixup_message)
981 use_editor = 0;
982 if (0 <= edit_flag)
983 use_editor = edit_flag;
984 if (!use_editor)
985 setenv("GIT_EDITOR", ":", 1);
987 /* Sanity check options */
988 if (amend && !current_head)
989 die(_("You have nothing to amend."));
990 if (amend && whence != FROM_COMMIT) {
991 if (whence == FROM_MERGE)
992 die(_("You are in the middle of a merge -- cannot amend."));
993 else if (whence == FROM_CHERRY_PICK)
994 die(_("You are in the middle of a cherry-pick -- cannot amend."));
996 if (fixup_message && squash_message)
997 die(_("Options --squash and --fixup cannot be used together"));
998 if (use_message)
999 f++;
1000 if (edit_message)
1001 f++;
1002 if (fixup_message)
1003 f++;
1004 if (logfile)
1005 f++;
1006 if (f > 1)
1007 die(_("Only one of -c/-C/-F/--fixup can be used."));
1008 if (message.len && f > 0)
1009 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1010 if (f || message.len)
1011 template_file = NULL;
1012 if (edit_message)
1013 use_message = edit_message;
1014 if (amend && !use_message && !fixup_message)
1015 use_message = "HEAD";
1016 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1017 die(_("--reset-author can be used only with -C, -c or --amend."));
1018 if (use_message) {
1019 use_message_buffer = read_commit_message(use_message);
1020 if (!renew_authorship) {
1021 author_message = use_message;
1022 author_message_buffer = use_message_buffer;
1025 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1026 author_message = "CHERRY_PICK_HEAD";
1027 author_message_buffer = read_commit_message(author_message);
1030 if (patch_interactive)
1031 interactive = 1;
1033 if (!!also + !!only + !!all + !!interactive > 1)
1034 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1035 if (argc == 0 && (also || (only && !amend)))
1036 die(_("No paths with --include/--only does not make sense."));
1037 if (argc == 0 && only && amend)
1038 only_include_assumed = _("Clever... amending the last one with dirty index.");
1039 if (argc > 0 && !also && !only)
1040 only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1041 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1042 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1043 else if (!strcmp(cleanup_arg, "verbatim"))
1044 cleanup_mode = CLEANUP_NONE;
1045 else if (!strcmp(cleanup_arg, "whitespace"))
1046 cleanup_mode = CLEANUP_SPACE;
1047 else if (!strcmp(cleanup_arg, "strip"))
1048 cleanup_mode = CLEANUP_ALL;
1049 else
1050 die(_("Invalid cleanup mode %s"), cleanup_arg);
1052 handle_untracked_files_arg(s);
1054 if (all && argc > 0)
1055 die(_("Paths with -a does not make sense."));
1057 if (s->null_termination) {
1058 if (status_format == STATUS_FORMAT_NONE)
1059 status_format = STATUS_FORMAT_PORCELAIN;
1060 else if (status_format == STATUS_FORMAT_LONG)
1061 die(_("--long and -z are incompatible"));
1063 if (status_format != STATUS_FORMAT_NONE)
1064 dry_run = 1;
1066 return argc;
1069 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1070 const struct commit *current_head, struct wt_status *s)
1072 int commitable;
1073 const char *index_file;
1075 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1076 commitable = run_status(stdout, index_file, prefix, 0, s);
1077 rollback_index_files();
1079 return commitable ? 0 : 1;
1082 static int parse_status_slot(const char *var, int offset)
1084 if (!strcasecmp(var+offset, "header"))
1085 return WT_STATUS_HEADER;
1086 if (!strcasecmp(var+offset, "branch"))
1087 return WT_STATUS_ONBRANCH;
1088 if (!strcasecmp(var+offset, "updated")
1089 || !strcasecmp(var+offset, "added"))
1090 return WT_STATUS_UPDATED;
1091 if (!strcasecmp(var+offset, "changed"))
1092 return WT_STATUS_CHANGED;
1093 if (!strcasecmp(var+offset, "untracked"))
1094 return WT_STATUS_UNTRACKED;
1095 if (!strcasecmp(var+offset, "nobranch"))
1096 return WT_STATUS_NOBRANCH;
1097 if (!strcasecmp(var+offset, "unmerged"))
1098 return WT_STATUS_UNMERGED;
1099 return -1;
1102 static int git_status_config(const char *k, const char *v, void *cb)
1104 struct wt_status *s = cb;
1106 if (!prefixcmp(k, "column."))
1107 return git_column_config(k, v, "status", &s->colopts);
1108 if (!strcmp(k, "status.submodulesummary")) {
1109 int is_bool;
1110 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1111 if (is_bool && s->submodule_summary)
1112 s->submodule_summary = -1;
1113 return 0;
1115 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1116 s->use_color = git_config_colorbool(k, v);
1117 return 0;
1119 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1120 int slot = parse_status_slot(k, 13);
1121 if (slot < 0)
1122 return 0;
1123 if (!v)
1124 return config_error_nonbool(k);
1125 color_parse(v, k, s->color_palette[slot]);
1126 return 0;
1128 if (!strcmp(k, "status.relativepaths")) {
1129 s->relative_paths = git_config_bool(k, v);
1130 return 0;
1132 if (!strcmp(k, "status.showuntrackedfiles")) {
1133 if (!v)
1134 return config_error_nonbool(k);
1135 else if (!strcmp(v, "no"))
1136 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1137 else if (!strcmp(v, "normal"))
1138 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1139 else if (!strcmp(v, "all"))
1140 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1141 else
1142 return error(_("Invalid untracked files mode '%s'"), v);
1143 return 0;
1145 return git_diff_ui_config(k, v, NULL);
1148 int cmd_status(int argc, const char **argv, const char *prefix)
1150 static struct wt_status s;
1151 int fd;
1152 unsigned char sha1[20];
1153 static struct option builtin_status_options[] = {
1154 OPT__VERBOSE(&verbose, N_("be verbose")),
1155 OPT_SET_INT('s', "short", &status_format,
1156 N_("show status concisely"), STATUS_FORMAT_SHORT),
1157 OPT_BOOLEAN('b', "branch", &s.show_branch,
1158 N_("show branch information")),
1159 OPT_SET_INT(0, "porcelain", &status_format,
1160 N_("machine-readable output"),
1161 STATUS_FORMAT_PORCELAIN),
1162 OPT_SET_INT(0, "long", &status_format,
1163 N_("show status in long format (default)"),
1164 STATUS_FORMAT_LONG),
1165 OPT_BOOLEAN('z', "null", &s.null_termination,
1166 N_("terminate entries with NUL")),
1167 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1168 N_("mode"),
1169 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1170 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1171 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1172 N_("show ignored files")),
1173 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1174 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1175 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1176 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1177 OPT_END(),
1180 if (argc == 2 && !strcmp(argv[1], "-h"))
1181 usage_with_options(builtin_status_usage, builtin_status_options);
1183 wt_status_prepare(&s);
1184 gitmodules_config();
1185 git_config(git_status_config, &s);
1186 determine_whence(&s);
1187 argc = parse_options(argc, argv, prefix,
1188 builtin_status_options,
1189 builtin_status_usage, 0);
1190 finalize_colopts(&s.colopts, -1);
1192 if (s.null_termination) {
1193 if (status_format == STATUS_FORMAT_NONE)
1194 status_format = STATUS_FORMAT_PORCELAIN;
1195 else if (status_format == STATUS_FORMAT_LONG)
1196 die(_("--long and -z are incompatible"));
1199 handle_untracked_files_arg(&s);
1200 if (show_ignored_in_status)
1201 s.show_ignored_files = 1;
1202 if (*argv)
1203 s.pathspec = get_pathspec(prefix, argv);
1205 read_cache_preload(s.pathspec);
1206 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1208 fd = hold_locked_index(&index_lock, 0);
1209 if (0 <= fd)
1210 update_index_if_able(&the_index, &index_lock);
1212 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1213 s.ignore_submodule_arg = ignore_submodule_arg;
1214 wt_status_collect(&s);
1216 if (s.relative_paths)
1217 s.prefix = prefix;
1219 switch (status_format) {
1220 case STATUS_FORMAT_SHORT:
1221 wt_shortstatus_print(&s);
1222 break;
1223 case STATUS_FORMAT_PORCELAIN:
1224 wt_porcelain_print(&s);
1225 break;
1226 case STATUS_FORMAT_NONE:
1227 case STATUS_FORMAT_LONG:
1228 s.verbose = verbose;
1229 s.ignore_submodule_arg = ignore_submodule_arg;
1230 wt_status_print(&s);
1231 break;
1233 return 0;
1236 static void print_summary(const char *prefix, const unsigned char *sha1,
1237 int initial_commit)
1239 struct rev_info rev;
1240 struct commit *commit;
1241 struct strbuf format = STRBUF_INIT;
1242 unsigned char junk_sha1[20];
1243 const char *head;
1244 struct pretty_print_context pctx = {0};
1245 struct strbuf author_ident = STRBUF_INIT;
1246 struct strbuf committer_ident = STRBUF_INIT;
1248 commit = lookup_commit(sha1);
1249 if (!commit)
1250 die(_("couldn't look up newly created commit"));
1251 if (!commit || parse_commit(commit))
1252 die(_("could not parse newly created commit"));
1254 strbuf_addstr(&format, "format:%h] %s");
1256 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1257 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1258 if (strbuf_cmp(&author_ident, &committer_ident)) {
1259 strbuf_addstr(&format, "\n Author: ");
1260 strbuf_addbuf_percentquote(&format, &author_ident);
1262 if (!committer_ident_sufficiently_given()) {
1263 strbuf_addstr(&format, "\n Committer: ");
1264 strbuf_addbuf_percentquote(&format, &committer_ident);
1265 if (advice_implicit_identity) {
1266 strbuf_addch(&format, '\n');
1267 strbuf_addstr(&format, _(implicit_ident_advice));
1270 strbuf_release(&author_ident);
1271 strbuf_release(&committer_ident);
1273 init_revisions(&rev, prefix);
1274 setup_revisions(0, NULL, &rev, NULL);
1276 rev.diff = 1;
1277 rev.diffopt.output_format =
1278 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1280 rev.verbose_header = 1;
1281 rev.show_root_diff = 1;
1282 get_commit_format(format.buf, &rev);
1283 rev.always_show_header = 0;
1284 rev.diffopt.detect_rename = 1;
1285 rev.diffopt.break_opt = 0;
1286 diff_setup_done(&rev.diffopt);
1288 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1289 printf("[%s%s ",
1290 !prefixcmp(head, "refs/heads/") ?
1291 head + 11 :
1292 !strcmp(head, "HEAD") ?
1293 _("detached HEAD") :
1294 head,
1295 initial_commit ? _(" (root-commit)") : "");
1297 if (!log_tree_commit(&rev, commit)) {
1298 rev.always_show_header = 1;
1299 rev.use_terminator = 1;
1300 log_tree_commit(&rev, commit);
1303 strbuf_release(&format);
1306 static int git_commit_config(const char *k, const char *v, void *cb)
1308 struct wt_status *s = cb;
1309 int status;
1311 if (!strcmp(k, "commit.template"))
1312 return git_config_pathname(&template_file, k, v);
1313 if (!strcmp(k, "commit.status")) {
1314 include_status = git_config_bool(k, v);
1315 return 0;
1317 if (!strcmp(k, "commit.cleanup"))
1318 return git_config_string(&cleanup_arg, k, v);
1320 status = git_gpg_config(k, v, NULL);
1321 if (status)
1322 return status;
1323 return git_status_config(k, v, s);
1326 static int run_rewrite_hook(const unsigned char *oldsha1,
1327 const unsigned char *newsha1)
1329 /* oldsha1 SP newsha1 LF NUL */
1330 static char buf[2*40 + 3];
1331 struct child_process proc;
1332 const char *argv[3];
1333 int code;
1334 size_t n;
1336 argv[0] = find_hook("post-rewrite");
1337 if (!argv[0])
1338 return 0;
1340 argv[1] = "amend";
1341 argv[2] = NULL;
1343 memset(&proc, 0, sizeof(proc));
1344 proc.argv = argv;
1345 proc.in = -1;
1346 proc.stdout_to_stderr = 1;
1348 code = start_command(&proc);
1349 if (code)
1350 return code;
1351 n = snprintf(buf, sizeof(buf), "%s %s\n",
1352 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1353 write_in_full(proc.in, buf, n);
1354 close(proc.in);
1355 return finish_command(&proc);
1358 int cmd_commit(int argc, const char **argv, const char *prefix)
1360 static struct wt_status s;
1361 static struct option builtin_commit_options[] = {
1362 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1363 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1365 OPT_GROUP(N_("Commit message options")),
1366 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1367 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1368 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1369 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1370 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1371 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1372 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1373 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1374 OPT_BOOLEAN(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1375 OPT_BOOLEAN('s', "signoff", &signoff, N_("add Signed-off-by:")),
1376 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1377 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1378 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1379 OPT_BOOLEAN(0, "status", &include_status, N_("include status in commit message template")),
1380 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key id"),
1381 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1382 /* end commit message options */
1384 OPT_GROUP(N_("Commit contents options")),
1385 OPT_BOOLEAN('a', "all", &all, N_("commit all changed files")),
1386 OPT_BOOLEAN('i', "include", &also, N_("add specified files to index for commit")),
1387 OPT_BOOLEAN(0, "interactive", &interactive, N_("interactively add files")),
1388 OPT_BOOLEAN('p', "patch", &patch_interactive, N_("interactively add changes")),
1389 OPT_BOOLEAN('o', "only", &only, N_("commit only specified files")),
1390 OPT_BOOLEAN('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1391 OPT_BOOLEAN(0, "dry-run", &dry_run, N_("show what would be committed")),
1392 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1393 STATUS_FORMAT_SHORT),
1394 OPT_BOOLEAN(0, "branch", &s.show_branch, N_("show branch information")),
1395 OPT_SET_INT(0, "porcelain", &status_format,
1396 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1397 OPT_SET_INT(0, "long", &status_format,
1398 N_("show status in long format (default)"),
1399 STATUS_FORMAT_LONG),
1400 OPT_BOOLEAN('z', "null", &s.null_termination,
1401 N_("terminate entries with NUL")),
1402 OPT_BOOLEAN(0, "amend", &amend, N_("amend previous commit")),
1403 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1404 { 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" },
1405 /* end commit contents options */
1407 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
1408 N_("ok to record an empty change"),
1409 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1410 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
1411 N_("ok to record a change with an empty message"),
1412 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1414 OPT_END()
1417 struct strbuf sb = STRBUF_INIT;
1418 struct strbuf author_ident = STRBUF_INIT;
1419 const char *index_file, *reflog_msg;
1420 char *nl, *p;
1421 unsigned char sha1[20];
1422 struct ref_lock *ref_lock;
1423 struct commit_list *parents = NULL, **pptr = &parents;
1424 struct stat statbuf;
1425 int allow_fast_forward = 1;
1426 struct commit *current_head = NULL;
1427 struct commit_extra_header *extra = NULL;
1429 if (argc == 2 && !strcmp(argv[1], "-h"))
1430 usage_with_options(builtin_commit_usage, builtin_commit_options);
1432 wt_status_prepare(&s);
1433 gitmodules_config();
1434 git_config(git_commit_config, &s);
1435 determine_whence(&s);
1436 s.colopts = 0;
1438 if (get_sha1("HEAD", sha1))
1439 current_head = NULL;
1440 else {
1441 current_head = lookup_commit_or_die(sha1, "HEAD");
1442 if (!current_head || parse_commit(current_head))
1443 die(_("could not parse HEAD commit"));
1445 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1446 builtin_commit_usage,
1447 prefix, current_head, &s);
1448 if (dry_run)
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();
1457 return 1;
1460 /* Determine parents */
1461 reflog_msg = getenv("GIT_REFLOG_ACTION");
1462 if (!current_head) {
1463 if (!reflog_msg)
1464 reflog_msg = "commit (initial)";
1465 } else if (amend) {
1466 struct commit_list *c;
1468 if (!reflog_msg)
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;
1474 FILE *fp;
1476 if (!reflog_msg)
1477 reflog_msg = "commit (merge)";
1478 pptr = &commit_list_insert(current_head, pptr)->next;
1479 fp = fopen(git_path("MERGE_HEAD"), "r");
1480 if (fp == NULL)
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);
1487 if (!parent)
1488 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1489 pptr = &commit_list_insert(parent, pptr)->next;
1491 fclose(fp);
1492 strbuf_release(&m);
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);
1501 } else {
1502 if (!reflog_msg)
1503 reflog_msg = (whence == FROM_CHERRY_PICK)
1504 ? "commit (cherry-pick)"
1505 : "commit";
1506 pptr = &commit_list_insert(current_head, pptr)->next;
1509 /* Finally, get the commit message */
1510 strbuf_reset(&sb);
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. */
1518 if (verbose) {
1519 p = strstr(sb.buf, "\ndiff --git ");
1520 if (p != NULL)
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"));
1529 exit(1);
1531 if (message_is_empty(&sb) && !allow_empty_message) {
1532 rollback_index_files();
1533 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1534 exit(1);
1537 if (amend) {
1538 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1539 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1540 } else {
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",
1554 !current_head
1555 ? NULL
1556 : current_head->object.sha1,
1559 nl = strchr(sb.buf, '\n');
1560 if (nl)
1561 strbuf_setlen(&sb, nl + 1 - sb.buf);
1562 else
1563 strbuf_addch(&sb, '\n');
1564 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1565 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1567 if (!ref_lock) {
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."));
1588 rerere(0);
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");
1593 if (cfg) {
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);
1600 if (!quiet)
1601 print_summary(prefix, sha1, !current_head);
1603 return 0;