Move copy_note_for_rewrite + friends from builtin/notes.c to notes-utils.c
[git/jrn.git] / builtin / commit.c
blobce4017608714bed8df7d2250a54fcf32f5bc14f0
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"
67 "Otherwise, please use 'git reset'\n");
69 static const char *use_message_buffer;
70 static const char commit_editmsg[] = "COMMIT_EDITMSG";
71 static struct lock_file index_lock; /* real index */
72 static struct lock_file false_lock; /* used only for partial commits */
73 static enum {
74 COMMIT_AS_IS = 1,
75 COMMIT_NORMAL,
76 COMMIT_PARTIAL
77 } commit_style;
79 static const char *logfile, *force_author;
80 static const char *template_file;
82 * The _message variables are commit names from which to take
83 * the commit message and/or authorship.
85 static const char *author_message, *author_message_buffer;
86 static char *edit_message, *use_message;
87 static char *fixup_message, *squash_message;
88 static int all, also, interactive, patch_interactive, only, amend, signoff;
89 static int edit_flag = -1; /* unspecified */
90 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
91 static int no_post_rewrite, allow_empty_message;
92 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
93 static char *sign_commit;
96 * The default commit message cleanup mode will remove the lines
97 * beginning with # (shell comments) and leading and trailing
98 * whitespaces (empty lines or containing only whitespaces)
99 * if editor is used, and only the whitespaces if the message
100 * is specified explicitly.
102 static enum {
103 CLEANUP_SPACE,
104 CLEANUP_NONE,
105 CLEANUP_ALL
106 } cleanup_mode;
107 static const char *cleanup_arg;
109 static enum commit_whence whence;
110 static int use_editor = 1, include_status = 1;
111 static int show_ignored_in_status;
112 static const char *only_include_assumed;
113 static struct strbuf message = STRBUF_INIT;
115 static enum {
116 STATUS_FORMAT_NONE = 0,
117 STATUS_FORMAT_LONG,
118 STATUS_FORMAT_SHORT,
119 STATUS_FORMAT_PORCELAIN
120 } status_format;
122 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
124 struct strbuf *buf = opt->value;
125 if (unset)
126 strbuf_setlen(buf, 0);
127 else {
128 if (buf->len)
129 strbuf_addch(buf, '\n');
130 strbuf_addstr(buf, arg);
131 strbuf_complete_line(buf);
133 return 0;
136 static void determine_whence(struct wt_status *s)
138 if (file_exists(git_path("MERGE_HEAD")))
139 whence = FROM_MERGE;
140 else if (file_exists(git_path("CHERRY_PICK_HEAD")))
141 whence = FROM_CHERRY_PICK;
142 else
143 whence = FROM_COMMIT;
144 if (s)
145 s->whence = whence;
148 static void rollback_index_files(void)
150 switch (commit_style) {
151 case COMMIT_AS_IS:
152 break; /* nothing to do */
153 case COMMIT_NORMAL:
154 rollback_lock_file(&index_lock);
155 break;
156 case COMMIT_PARTIAL:
157 rollback_lock_file(&index_lock);
158 rollback_lock_file(&false_lock);
159 break;
163 static int commit_index_files(void)
165 int err = 0;
167 switch (commit_style) {
168 case COMMIT_AS_IS:
169 break; /* nothing to do */
170 case COMMIT_NORMAL:
171 err = commit_lock_file(&index_lock);
172 break;
173 case COMMIT_PARTIAL:
174 err = commit_lock_file(&index_lock);
175 rollback_lock_file(&false_lock);
176 break;
179 return err;
183 * Take a union of paths in the index and the named tree (typically, "HEAD"),
184 * and return the paths that match the given pattern in list.
186 static int list_paths(struct string_list *list, const char *with_tree,
187 const char *prefix, const char **pattern)
189 int i;
190 char *m;
192 if (!pattern)
193 return 0;
195 for (i = 0; pattern[i]; i++)
197 m = xcalloc(1, i);
199 if (with_tree) {
200 char *max_prefix = common_prefix(pattern);
201 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
202 free(max_prefix);
205 for (i = 0; i < active_nr; i++) {
206 struct cache_entry *ce = active_cache[i];
207 struct string_list_item *item;
209 if (ce->ce_flags & CE_UPDATE)
210 continue;
211 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
212 continue;
213 item = string_list_insert(list, ce->name);
214 if (ce_skip_worktree(ce))
215 item->util = item; /* better a valid pointer than a fake one */
218 return report_path_error(m, pattern, prefix);
221 static void add_remove_files(struct string_list *list)
223 int i;
224 for (i = 0; i < list->nr; i++) {
225 struct stat st;
226 struct string_list_item *p = &(list->items[i]);
228 /* p->util is skip-worktree */
229 if (p->util)
230 continue;
232 if (!lstat(p->string, &st)) {
233 if (add_to_cache(p->string, &st, 0))
234 die(_("updating files failed"));
235 } else
236 remove_file_from_cache(p->string);
240 static void create_base_index(const struct commit *current_head)
242 struct tree *tree;
243 struct unpack_trees_options opts;
244 struct tree_desc t;
246 if (!current_head) {
247 discard_cache();
248 return;
251 memset(&opts, 0, sizeof(opts));
252 opts.head_idx = 1;
253 opts.index_only = 1;
254 opts.merge = 1;
255 opts.src_index = &the_index;
256 opts.dst_index = &the_index;
258 opts.fn = oneway_merge;
259 tree = parse_tree_indirect(current_head->object.sha1);
260 if (!tree)
261 die(_("failed to unpack HEAD tree object"));
262 parse_tree(tree);
263 init_tree_desc(&t, tree->buffer, tree->size);
264 if (unpack_trees(1, &t, &opts))
265 exit(128); /* We've already reported the error, finish dying */
268 static void refresh_cache_or_die(int refresh_flags)
271 * refresh_flags contains REFRESH_QUIET, so the only errors
272 * are for unmerged entries.
274 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
275 die_resolve_conflict("commit");
278 static char *prepare_index(int argc, const char **argv, const char *prefix,
279 const struct commit *current_head, int is_status)
281 int fd;
282 struct string_list partial;
283 const char **pathspec = NULL;
284 char *old_index_env = NULL;
285 int refresh_flags = REFRESH_QUIET;
287 if (is_status)
288 refresh_flags |= REFRESH_UNMERGED;
290 if (*argv)
291 pathspec = get_pathspec(prefix, argv);
293 if (read_cache_preload(pathspec) < 0)
294 die(_("index file corrupt"));
296 if (interactive) {
297 fd = hold_locked_index(&index_lock, 1);
299 refresh_cache_or_die(refresh_flags);
301 if (write_cache(fd, active_cache, active_nr) ||
302 close_lock_file(&index_lock))
303 die(_("unable to create temporary index"));
305 old_index_env = getenv(INDEX_ENVIRONMENT);
306 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
308 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
309 die(_("interactive add failed"));
311 if (old_index_env && *old_index_env)
312 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
313 else
314 unsetenv(INDEX_ENVIRONMENT);
316 discard_cache();
317 read_cache_from(index_lock.filename);
319 commit_style = COMMIT_NORMAL;
320 return index_lock.filename;
324 * Non partial, non as-is commit.
326 * (1) get the real index;
327 * (2) update the_index as necessary;
328 * (3) write the_index out to the real index (still locked);
329 * (4) return the name of the locked index file.
331 * The caller should run hooks on the locked real index, and
332 * (A) if all goes well, commit the real index;
333 * (B) on failure, rollback the real index.
335 if (all || (also && pathspec && *pathspec)) {
336 fd = hold_locked_index(&index_lock, 1);
337 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
338 refresh_cache_or_die(refresh_flags);
339 update_main_cache_tree(WRITE_TREE_SILENT);
340 if (write_cache(fd, active_cache, active_nr) ||
341 close_lock_file(&index_lock))
342 die(_("unable to write new_index file"));
343 commit_style = COMMIT_NORMAL;
344 return index_lock.filename;
348 * As-is commit.
350 * (1) return the name of the real index file.
352 * The caller should run hooks on the real index,
353 * and create commit from the_index.
354 * We still need to refresh the index here.
356 if (!only && (!pathspec || !*pathspec)) {
357 fd = hold_locked_index(&index_lock, 1);
358 refresh_cache_or_die(refresh_flags);
359 if (active_cache_changed) {
360 update_main_cache_tree(WRITE_TREE_SILENT);
361 if (write_cache(fd, active_cache, active_nr) ||
362 commit_locked_index(&index_lock))
363 die(_("unable to write new_index file"));
364 } else {
365 rollback_lock_file(&index_lock);
367 commit_style = COMMIT_AS_IS;
368 return get_index_file();
372 * A partial commit.
374 * (0) find the set of affected paths;
375 * (1) get lock on the real index file;
376 * (2) update the_index with the given paths;
377 * (3) write the_index out to the real index (still locked);
378 * (4) get lock on the false index file;
379 * (5) reset the_index from HEAD;
380 * (6) update the_index the same way as (2);
381 * (7) write the_index out to the false index file;
382 * (8) return the name of the false index file (still locked);
384 * The caller should run hooks on the locked false index, and
385 * create commit from it. Then
386 * (A) if all goes well, commit the real index;
387 * (B) on failure, rollback the real index;
388 * In either case, rollback the false index.
390 commit_style = COMMIT_PARTIAL;
392 if (whence != FROM_COMMIT) {
393 if (whence == FROM_MERGE)
394 die(_("cannot do a partial commit during a merge."));
395 else if (whence == FROM_CHERRY_PICK)
396 die(_("cannot do a partial commit during a cherry-pick."));
399 memset(&partial, 0, sizeof(partial));
400 partial.strdup_strings = 1;
401 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, pathspec))
402 exit(1);
404 discard_cache();
405 if (read_cache() < 0)
406 die(_("cannot read the index"));
408 fd = hold_locked_index(&index_lock, 1);
409 add_remove_files(&partial);
410 refresh_cache(REFRESH_QUIET);
411 if (write_cache(fd, active_cache, active_nr) ||
412 close_lock_file(&index_lock))
413 die(_("unable to write new_index file"));
415 fd = hold_lock_file_for_update(&false_lock,
416 git_path("next-index-%"PRIuMAX,
417 (uintmax_t) getpid()),
418 LOCK_DIE_ON_ERROR);
420 create_base_index(current_head);
421 add_remove_files(&partial);
422 refresh_cache(REFRESH_QUIET);
424 if (write_cache(fd, active_cache, active_nr) ||
425 close_lock_file(&false_lock))
426 die(_("unable to write temporary index file"));
428 discard_cache();
429 read_cache_from(false_lock.filename);
431 return false_lock.filename;
434 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
435 struct wt_status *s)
437 unsigned char sha1[20];
439 if (s->relative_paths)
440 s->prefix = prefix;
442 if (amend) {
443 s->amend = 1;
444 s->reference = "HEAD^1";
446 s->verbose = verbose;
447 s->index_file = index_file;
448 s->fp = fp;
449 s->nowarn = nowarn;
450 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
452 wt_status_collect(s);
454 switch (status_format) {
455 case STATUS_FORMAT_SHORT:
456 wt_shortstatus_print(s);
457 break;
458 case STATUS_FORMAT_PORCELAIN:
459 wt_porcelain_print(s);
460 break;
461 case STATUS_FORMAT_NONE:
462 case STATUS_FORMAT_LONG:
463 wt_status_print(s);
464 break;
467 return s->commitable;
470 static int is_a_merge(const struct commit *current_head)
472 return !!(current_head->parents && current_head->parents->next);
475 static void export_one(const char *var, const char *s, const char *e, int hack)
477 struct strbuf buf = STRBUF_INIT;
478 if (hack)
479 strbuf_addch(&buf, hack);
480 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
481 setenv(var, buf.buf, 1);
482 strbuf_release(&buf);
485 static int sane_ident_split(struct ident_split *person)
487 if (!person->name_begin || !person->name_end ||
488 person->name_begin == person->name_end)
489 return 0; /* no human readable name */
490 if (!person->mail_begin || !person->mail_end ||
491 person->mail_begin == person->mail_end)
492 return 0; /* no usable mail */
493 if (!person->date_begin || !person->date_end ||
494 !person->tz_begin || !person->tz_end)
495 return 0;
496 return 1;
499 static void determine_author_info(struct strbuf *author_ident)
501 char *name, *email, *date;
502 struct ident_split author;
504 name = getenv("GIT_AUTHOR_NAME");
505 email = getenv("GIT_AUTHOR_EMAIL");
506 date = getenv("GIT_AUTHOR_DATE");
508 if (author_message) {
509 const char *a, *lb, *rb, *eol;
510 size_t len;
512 a = strstr(author_message_buffer, "\nauthor ");
513 if (!a)
514 die(_("invalid commit: %s"), author_message);
516 lb = strchrnul(a + strlen("\nauthor "), '<');
517 rb = strchrnul(lb, '>');
518 eol = strchrnul(rb, '\n');
519 if (!*lb || !*rb || !*eol)
520 die(_("invalid commit: %s"), author_message);
522 if (lb == a + strlen("\nauthor "))
523 /* \nauthor <foo@example.com> */
524 name = xcalloc(1, 1);
525 else
526 name = xmemdupz(a + strlen("\nauthor "),
527 (lb - strlen(" ") -
528 (a + strlen("\nauthor "))));
529 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
530 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
531 len = eol - (rb + strlen("> "));
532 date = xmalloc(len + 2);
533 *date = '@';
534 memcpy(date + 1, rb + strlen("> "), len);
535 date[len + 1] = '\0';
538 if (force_author) {
539 const char *lb = strstr(force_author, " <");
540 const char *rb = strchr(force_author, '>');
542 if (!lb || !rb)
543 die(_("malformed --author parameter"));
544 name = xstrndup(force_author, lb - force_author);
545 email = xstrndup(lb + 2, rb - (lb + 2));
548 if (force_date)
549 date = force_date;
550 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
551 if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
552 sane_ident_split(&author)) {
553 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
554 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
555 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
559 static char *cut_ident_timestamp_part(char *string)
561 char *ket = strrchr(string, '>');
562 if (!ket || ket[1] != ' ')
563 die(_("Malformed ident string: '%s'"), string);
564 *++ket = '\0';
565 return ket;
568 static int prepare_to_commit(const char *index_file, const char *prefix,
569 struct commit *current_head,
570 struct wt_status *s,
571 struct strbuf *author_ident)
573 struct stat statbuf;
574 struct strbuf committer_ident = STRBUF_INIT;
575 int commitable, saved_color_setting;
576 struct strbuf sb = STRBUF_INIT;
577 char *buffer;
578 const char *hook_arg1 = NULL;
579 const char *hook_arg2 = NULL;
580 int ident_shown = 0;
581 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
583 /* This checks and barfs if author is badly specified */
584 determine_author_info(author_ident);
586 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
587 return 0;
589 if (squash_message) {
591 * Insert the proper subject line before other commit
592 * message options add their content.
594 if (use_message && !strcmp(use_message, squash_message))
595 strbuf_addstr(&sb, "squash! ");
596 else {
597 struct pretty_print_context ctx = {0};
598 struct commit *c;
599 c = lookup_commit_reference_by_name(squash_message);
600 if (!c)
601 die(_("could not lookup commit %s"), squash_message);
602 ctx.output_encoding = get_commit_output_encoding();
603 format_commit_message(c, "squash! %s\n\n", &sb,
604 &ctx);
608 if (message.len) {
609 strbuf_addbuf(&sb, &message);
610 hook_arg1 = "message";
611 } else if (logfile && !strcmp(logfile, "-")) {
612 if (isatty(0))
613 fprintf(stderr, _("(reading log message from standard input)\n"));
614 if (strbuf_read(&sb, 0, 0) < 0)
615 die_errno(_("could not read log from standard input"));
616 hook_arg1 = "message";
617 } else if (logfile) {
618 if (strbuf_read_file(&sb, logfile, 0) < 0)
619 die_errno(_("could not read log file '%s'"),
620 logfile);
621 hook_arg1 = "message";
622 } else if (use_message) {
623 buffer = strstr(use_message_buffer, "\n\n");
624 if (!use_editor && (!buffer || buffer[2] == '\0'))
625 die(_("commit has empty message"));
626 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
627 hook_arg1 = "commit";
628 hook_arg2 = use_message;
629 } else if (fixup_message) {
630 struct pretty_print_context ctx = {0};
631 struct commit *commit;
632 commit = lookup_commit_reference_by_name(fixup_message);
633 if (!commit)
634 die(_("could not lookup commit %s"), fixup_message);
635 ctx.output_encoding = get_commit_output_encoding();
636 format_commit_message(commit, "fixup! %s\n\n",
637 &sb, &ctx);
638 hook_arg1 = "message";
639 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
640 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
641 die_errno(_("could not read MERGE_MSG"));
642 hook_arg1 = "merge";
643 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
644 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
645 die_errno(_("could not read SQUASH_MSG"));
646 hook_arg1 = "squash";
647 } else if (template_file) {
648 if (strbuf_read_file(&sb, template_file, 0) < 0)
649 die_errno(_("could not read '%s'"), template_file);
650 hook_arg1 = "template";
651 clean_message_contents = 0;
655 * The remaining cases don't modify the template message, but
656 * just set the argument(s) to the prepare-commit-msg hook.
658 else if (whence == FROM_MERGE)
659 hook_arg1 = "merge";
660 else if (whence == FROM_CHERRY_PICK) {
661 hook_arg1 = "commit";
662 hook_arg2 = "CHERRY_PICK_HEAD";
665 if (squash_message) {
667 * If squash_commit was used for the commit subject,
668 * then we're possibly hijacking other commit log options.
669 * Reset the hook args to tell the real story.
671 hook_arg1 = "message";
672 hook_arg2 = "";
675 s->fp = fopen(git_path(commit_editmsg), "w");
676 if (s->fp == NULL)
677 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
679 if (clean_message_contents)
680 stripspace(&sb, 0);
682 if (signoff) {
684 * See if we have a Conflicts: block at the end. If yes, count
685 * its size, so we can ignore it.
687 int ignore_footer = 0;
688 int i, eol, previous = 0;
689 const char *nl;
691 for (i = 0; i < sb.len; i++) {
692 nl = memchr(sb.buf + i, '\n', sb.len - i);
693 if (nl)
694 eol = nl - sb.buf;
695 else
696 eol = sb.len;
697 if (!prefixcmp(sb.buf + previous, "\nConflicts:\n")) {
698 ignore_footer = sb.len - previous;
699 break;
701 while (i < eol)
702 i++;
703 previous = eol;
706 append_signoff(&sb, ignore_footer, 0);
709 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
710 die_errno(_("could not write commit template"));
712 strbuf_release(&sb);
714 /* This checks if committer ident is explicitly given */
715 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
716 if (use_editor && include_status) {
717 char *ai_tmp, *ci_tmp;
718 if (whence != FROM_COMMIT)
719 status_printf_ln(s, GIT_COLOR_NORMAL,
720 whence == FROM_MERGE
721 ? _("\n"
722 "It looks like you may be committing a merge.\n"
723 "If this is not correct, please remove the file\n"
724 " %s\n"
725 "and try again.\n")
726 : _("\n"
727 "It looks like you may be committing a cherry-pick.\n"
728 "If this is not correct, please remove the file\n"
729 " %s\n"
730 "and try again.\n"),
731 git_path(whence == FROM_MERGE
732 ? "MERGE_HEAD"
733 : "CHERRY_PICK_HEAD"));
735 fprintf(s->fp, "\n");
736 if (cleanup_mode == CLEANUP_ALL)
737 status_printf(s, GIT_COLOR_NORMAL,
738 _("Please enter the commit message for your changes."
739 " Lines starting\nwith '%c' will be ignored, and an empty"
740 " message aborts the commit.\n"), comment_line_char);
741 else /* CLEANUP_SPACE, that is. */
742 status_printf(s, GIT_COLOR_NORMAL,
743 _("Please enter the commit message for your changes."
744 " Lines starting\n"
745 "with '%c' will be kept; you may remove them"
746 " yourself if you want to.\n"
747 "An empty message aborts the commit.\n"), comment_line_char);
748 if (only_include_assumed)
749 status_printf_ln(s, GIT_COLOR_NORMAL,
750 "%s", only_include_assumed);
752 ai_tmp = cut_ident_timestamp_part(author_ident->buf);
753 ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
754 if (strcmp(author_ident->buf, committer_ident.buf))
755 status_printf_ln(s, GIT_COLOR_NORMAL,
756 _("%s"
757 "Author: %s"),
758 ident_shown++ ? "" : "\n",
759 author_ident->buf);
761 if (!committer_ident_sufficiently_given())
762 status_printf_ln(s, GIT_COLOR_NORMAL,
763 _("%s"
764 "Committer: %s"),
765 ident_shown++ ? "" : "\n",
766 committer_ident.buf);
768 if (ident_shown)
769 status_printf_ln(s, GIT_COLOR_NORMAL, "");
771 saved_color_setting = s->use_color;
772 s->use_color = 0;
773 commitable = run_status(s->fp, index_file, prefix, 1, s);
774 s->use_color = saved_color_setting;
776 *ai_tmp = ' ';
777 *ci_tmp = ' ';
778 } else {
779 unsigned char sha1[20];
780 const char *parent = "HEAD";
782 if (!active_nr && read_cache() < 0)
783 die(_("Cannot read index"));
785 if (amend)
786 parent = "HEAD^1";
788 if (get_sha1(parent, sha1))
789 commitable = !!active_nr;
790 else
791 commitable = index_differs_from(parent, 0);
793 strbuf_release(&committer_ident);
795 fclose(s->fp);
798 * Reject an attempt to record a non-merge empty commit without
799 * explicit --allow-empty. In the cherry-pick case, it may be
800 * empty due to conflict resolution, which the user should okay.
802 if (!commitable && whence != FROM_MERGE && !allow_empty &&
803 !(amend && is_a_merge(current_head))) {
804 run_status(stdout, index_file, prefix, 0, s);
805 if (amend)
806 fputs(_(empty_amend_advice), stderr);
807 else if (whence == FROM_CHERRY_PICK)
808 fputs(_(empty_cherry_pick_advice), stderr);
809 return 0;
813 * Re-read the index as pre-commit hook could have updated it,
814 * and write it out as a tree. We must do this before we invoke
815 * the editor and after we invoke run_status above.
817 discard_cache();
818 read_cache_from(index_file);
819 if (update_main_cache_tree(0)) {
820 error(_("Error building trees"));
821 return 0;
824 if (run_hook(index_file, "prepare-commit-msg",
825 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
826 return 0;
828 if (use_editor) {
829 char index[PATH_MAX];
830 const char *env[2] = { NULL };
831 env[0] = index;
832 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
833 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
834 fprintf(stderr,
835 _("Please supply the message using either -m or -F option.\n"));
836 exit(1);
840 if (!no_verify &&
841 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
842 return 0;
845 return 1;
848 static int rest_is_empty(struct strbuf *sb, int start)
850 int i, eol;
851 const char *nl;
853 /* Check if the rest is just whitespace and Signed-of-by's. */
854 for (i = start; i < sb->len; i++) {
855 nl = memchr(sb->buf + i, '\n', sb->len - i);
856 if (nl)
857 eol = nl - sb->buf;
858 else
859 eol = sb->len;
861 if (strlen(sign_off_header) <= eol - i &&
862 !prefixcmp(sb->buf + i, sign_off_header)) {
863 i = eol;
864 continue;
866 while (i < eol)
867 if (!isspace(sb->buf[i++]))
868 return 0;
871 return 1;
875 * Find out if the message in the strbuf contains only whitespace and
876 * Signed-off-by lines.
878 static int message_is_empty(struct strbuf *sb)
880 if (cleanup_mode == CLEANUP_NONE && sb->len)
881 return 0;
882 return rest_is_empty(sb, 0);
886 * See if the user edited the message in the editor or left what
887 * was in the template intact
889 static int template_untouched(struct strbuf *sb)
891 struct strbuf tmpl = STRBUF_INIT;
892 char *start;
894 if (cleanup_mode == CLEANUP_NONE && sb->len)
895 return 0;
897 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
898 return 0;
900 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
901 start = (char *)skip_prefix(sb->buf, tmpl.buf);
902 if (!start)
903 start = sb->buf;
904 strbuf_release(&tmpl);
905 return rest_is_empty(sb, start - sb->buf);
908 static const char *find_author_by_nickname(const char *name)
910 struct rev_info revs;
911 struct commit *commit;
912 struct strbuf buf = STRBUF_INIT;
913 const char *av[20];
914 int ac = 0;
916 init_revisions(&revs, NULL);
917 strbuf_addf(&buf, "--author=%s", name);
918 av[++ac] = "--all";
919 av[++ac] = "-i";
920 av[++ac] = buf.buf;
921 av[++ac] = NULL;
922 setup_revisions(ac, av, &revs, NULL);
923 prepare_revision_walk(&revs);
924 commit = get_revision(&revs);
925 if (commit) {
926 struct pretty_print_context ctx = {0};
927 ctx.date_mode = DATE_NORMAL;
928 strbuf_release(&buf);
929 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
930 return strbuf_detach(&buf, NULL);
932 die(_("No existing author found with '%s'"), name);
936 static void handle_untracked_files_arg(struct wt_status *s)
938 if (!untracked_files_arg)
939 ; /* default already initialized */
940 else if (!strcmp(untracked_files_arg, "no"))
941 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
942 else if (!strcmp(untracked_files_arg, "normal"))
943 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
944 else if (!strcmp(untracked_files_arg, "all"))
945 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
946 else
947 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
950 static const char *read_commit_message(const char *name)
952 const char *out_enc;
953 struct commit *commit;
955 commit = lookup_commit_reference_by_name(name);
956 if (!commit)
957 die(_("could not lookup commit %s"), name);
958 out_enc = get_commit_output_encoding();
959 return logmsg_reencode(commit, NULL, out_enc);
962 static int parse_and_validate_options(int argc, const char *argv[],
963 const struct option *options,
964 const char * const usage[],
965 const char *prefix,
966 struct commit *current_head,
967 struct wt_status *s)
969 int f = 0;
971 argc = parse_options(argc, argv, prefix, options, usage, 0);
973 if (force_author && !strchr(force_author, '>'))
974 force_author = find_author_by_nickname(force_author);
976 if (force_author && renew_authorship)
977 die(_("Using both --reset-author and --author does not make sense"));
979 if (logfile || message.len || use_message || fixup_message)
980 use_editor = 0;
981 if (0 <= edit_flag)
982 use_editor = edit_flag;
983 if (!use_editor)
984 setenv("GIT_EDITOR", ":", 1);
986 /* Sanity check options */
987 if (amend && !current_head)
988 die(_("You have nothing to amend."));
989 if (amend && whence != FROM_COMMIT) {
990 if (whence == FROM_MERGE)
991 die(_("You are in the middle of a merge -- cannot amend."));
992 else if (whence == FROM_CHERRY_PICK)
993 die(_("You are in the middle of a cherry-pick -- cannot amend."));
995 if (fixup_message && squash_message)
996 die(_("Options --squash and --fixup cannot be used together"));
997 if (use_message)
998 f++;
999 if (edit_message)
1000 f++;
1001 if (fixup_message)
1002 f++;
1003 if (logfile)
1004 f++;
1005 if (f > 1)
1006 die(_("Only one of -c/-C/-F/--fixup can be used."));
1007 if (message.len && f > 0)
1008 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1009 if (f || message.len)
1010 template_file = NULL;
1011 if (edit_message)
1012 use_message = edit_message;
1013 if (amend && !use_message && !fixup_message)
1014 use_message = "HEAD";
1015 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1016 die(_("--reset-author can be used only with -C, -c or --amend."));
1017 if (use_message) {
1018 use_message_buffer = read_commit_message(use_message);
1019 if (!renew_authorship) {
1020 author_message = use_message;
1021 author_message_buffer = use_message_buffer;
1024 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1025 author_message = "CHERRY_PICK_HEAD";
1026 author_message_buffer = read_commit_message(author_message);
1029 if (patch_interactive)
1030 interactive = 1;
1032 if (!!also + !!only + !!all + !!interactive > 1)
1033 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1034 if (argc == 0 && (also || (only && !amend)))
1035 die(_("No paths with --include/--only does not make sense."));
1036 if (argc == 0 && only && amend)
1037 only_include_assumed = _("Clever... amending the last one with dirty index.");
1038 if (argc > 0 && !also && !only)
1039 only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1040 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1041 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1042 else if (!strcmp(cleanup_arg, "verbatim"))
1043 cleanup_mode = CLEANUP_NONE;
1044 else if (!strcmp(cleanup_arg, "whitespace"))
1045 cleanup_mode = CLEANUP_SPACE;
1046 else if (!strcmp(cleanup_arg, "strip"))
1047 cleanup_mode = CLEANUP_ALL;
1048 else
1049 die(_("Invalid cleanup mode %s"), cleanup_arg);
1051 handle_untracked_files_arg(s);
1053 if (all && argc > 0)
1054 die(_("Paths with -a does not make sense."));
1056 if (s->null_termination) {
1057 if (status_format == STATUS_FORMAT_NONE)
1058 status_format = STATUS_FORMAT_PORCELAIN;
1059 else if (status_format == STATUS_FORMAT_LONG)
1060 die(_("--long and -z are incompatible"));
1062 if (status_format != STATUS_FORMAT_NONE)
1063 dry_run = 1;
1065 return argc;
1068 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1069 const struct commit *current_head, struct wt_status *s)
1071 int commitable;
1072 const char *index_file;
1074 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1075 commitable = run_status(stdout, index_file, prefix, 0, s);
1076 rollback_index_files();
1078 return commitable ? 0 : 1;
1081 static int parse_status_slot(const char *var, int offset)
1083 if (!strcasecmp(var+offset, "header"))
1084 return WT_STATUS_HEADER;
1085 if (!strcasecmp(var+offset, "branch"))
1086 return WT_STATUS_ONBRANCH;
1087 if (!strcasecmp(var+offset, "updated")
1088 || !strcasecmp(var+offset, "added"))
1089 return WT_STATUS_UPDATED;
1090 if (!strcasecmp(var+offset, "changed"))
1091 return WT_STATUS_CHANGED;
1092 if (!strcasecmp(var+offset, "untracked"))
1093 return WT_STATUS_UNTRACKED;
1094 if (!strcasecmp(var+offset, "nobranch"))
1095 return WT_STATUS_NOBRANCH;
1096 if (!strcasecmp(var+offset, "unmerged"))
1097 return WT_STATUS_UNMERGED;
1098 return -1;
1101 static int git_status_config(const char *k, const char *v, void *cb)
1103 struct wt_status *s = cb;
1105 if (!prefixcmp(k, "column."))
1106 return git_column_config(k, v, "status", &s->colopts);
1107 if (!strcmp(k, "status.submodulesummary")) {
1108 int is_bool;
1109 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1110 if (is_bool && s->submodule_summary)
1111 s->submodule_summary = -1;
1112 return 0;
1114 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1115 s->use_color = git_config_colorbool(k, v);
1116 return 0;
1118 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1119 int slot = parse_status_slot(k, 13);
1120 if (slot < 0)
1121 return 0;
1122 if (!v)
1123 return config_error_nonbool(k);
1124 color_parse(v, k, s->color_palette[slot]);
1125 return 0;
1127 if (!strcmp(k, "status.relativepaths")) {
1128 s->relative_paths = git_config_bool(k, v);
1129 return 0;
1131 if (!strcmp(k, "status.showuntrackedfiles")) {
1132 if (!v)
1133 return config_error_nonbool(k);
1134 else if (!strcmp(v, "no"))
1135 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1136 else if (!strcmp(v, "normal"))
1137 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1138 else if (!strcmp(v, "all"))
1139 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1140 else
1141 return error(_("Invalid untracked files mode '%s'"), v);
1142 return 0;
1144 return git_diff_ui_config(k, v, NULL);
1147 int cmd_status(int argc, const char **argv, const char *prefix)
1149 static struct wt_status s;
1150 int fd;
1151 unsigned char sha1[20];
1152 static struct option builtin_status_options[] = {
1153 OPT__VERBOSE(&verbose, N_("be verbose")),
1154 OPT_SET_INT('s', "short", &status_format,
1155 N_("show status concisely"), STATUS_FORMAT_SHORT),
1156 OPT_BOOLEAN('b', "branch", &s.show_branch,
1157 N_("show branch information")),
1158 OPT_SET_INT(0, "porcelain", &status_format,
1159 N_("machine-readable output"),
1160 STATUS_FORMAT_PORCELAIN),
1161 OPT_SET_INT(0, "long", &status_format,
1162 N_("show status in long format (default)"),
1163 STATUS_FORMAT_LONG),
1164 OPT_BOOLEAN('z', "null", &s.null_termination,
1165 N_("terminate entries with NUL")),
1166 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1167 N_("mode"),
1168 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1169 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1170 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1171 N_("show ignored files")),
1172 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1173 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1174 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1175 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1176 OPT_END(),
1179 if (argc == 2 && !strcmp(argv[1], "-h"))
1180 usage_with_options(builtin_status_usage, builtin_status_options);
1182 wt_status_prepare(&s);
1183 gitmodules_config();
1184 git_config(git_status_config, &s);
1185 determine_whence(&s);
1186 argc = parse_options(argc, argv, prefix,
1187 builtin_status_options,
1188 builtin_status_usage, 0);
1189 finalize_colopts(&s.colopts, -1);
1191 if (s.null_termination) {
1192 if (status_format == STATUS_FORMAT_NONE)
1193 status_format = STATUS_FORMAT_PORCELAIN;
1194 else if (status_format == STATUS_FORMAT_LONG)
1195 die(_("--long and -z are incompatible"));
1198 handle_untracked_files_arg(&s);
1199 if (show_ignored_in_status)
1200 s.show_ignored_files = 1;
1201 if (*argv)
1202 s.pathspec = get_pathspec(prefix, argv);
1204 read_cache_preload(s.pathspec);
1205 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1207 fd = hold_locked_index(&index_lock, 0);
1208 if (0 <= fd)
1209 update_index_if_able(&the_index, &index_lock);
1211 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1212 s.ignore_submodule_arg = ignore_submodule_arg;
1213 wt_status_collect(&s);
1215 if (s.relative_paths)
1216 s.prefix = prefix;
1218 switch (status_format) {
1219 case STATUS_FORMAT_SHORT:
1220 wt_shortstatus_print(&s);
1221 break;
1222 case STATUS_FORMAT_PORCELAIN:
1223 wt_porcelain_print(&s);
1224 break;
1225 case STATUS_FORMAT_NONE:
1226 case STATUS_FORMAT_LONG:
1227 s.verbose = verbose;
1228 s.ignore_submodule_arg = ignore_submodule_arg;
1229 wt_status_print(&s);
1230 break;
1232 return 0;
1235 static void print_summary(const char *prefix, const unsigned char *sha1,
1236 int initial_commit)
1238 struct rev_info rev;
1239 struct commit *commit;
1240 struct strbuf format = STRBUF_INIT;
1241 unsigned char junk_sha1[20];
1242 const char *head;
1243 struct pretty_print_context pctx = {0};
1244 struct strbuf author_ident = STRBUF_INIT;
1245 struct strbuf committer_ident = STRBUF_INIT;
1247 commit = lookup_commit(sha1);
1248 if (!commit)
1249 die(_("couldn't look up newly created commit"));
1250 if (!commit || parse_commit(commit))
1251 die(_("could not parse newly created commit"));
1253 strbuf_addstr(&format, "format:%h] %s");
1255 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1256 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1257 if (strbuf_cmp(&author_ident, &committer_ident)) {
1258 strbuf_addstr(&format, "\n Author: ");
1259 strbuf_addbuf_percentquote(&format, &author_ident);
1261 if (!committer_ident_sufficiently_given()) {
1262 strbuf_addstr(&format, "\n Committer: ");
1263 strbuf_addbuf_percentquote(&format, &committer_ident);
1264 if (advice_implicit_identity) {
1265 strbuf_addch(&format, '\n');
1266 strbuf_addstr(&format, _(implicit_ident_advice));
1269 strbuf_release(&author_ident);
1270 strbuf_release(&committer_ident);
1272 init_revisions(&rev, prefix);
1273 setup_revisions(0, NULL, &rev, NULL);
1275 rev.diff = 1;
1276 rev.diffopt.output_format =
1277 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1279 rev.verbose_header = 1;
1280 rev.show_root_diff = 1;
1281 get_commit_format(format.buf, &rev);
1282 rev.always_show_header = 0;
1283 rev.diffopt.detect_rename = 1;
1284 rev.diffopt.break_opt = 0;
1285 diff_setup_done(&rev.diffopt);
1287 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1288 printf("[%s%s ",
1289 !prefixcmp(head, "refs/heads/") ?
1290 head + 11 :
1291 !strcmp(head, "HEAD") ?
1292 _("detached HEAD") :
1293 head,
1294 initial_commit ? _(" (root-commit)") : "");
1296 if (!log_tree_commit(&rev, commit)) {
1297 rev.always_show_header = 1;
1298 rev.use_terminator = 1;
1299 log_tree_commit(&rev, commit);
1302 strbuf_release(&format);
1305 static int git_commit_config(const char *k, const char *v, void *cb)
1307 struct wt_status *s = cb;
1308 int status;
1310 if (!strcmp(k, "commit.template"))
1311 return git_config_pathname(&template_file, k, v);
1312 if (!strcmp(k, "commit.status")) {
1313 include_status = git_config_bool(k, v);
1314 return 0;
1316 if (!strcmp(k, "commit.cleanup"))
1317 return git_config_string(&cleanup_arg, k, v);
1319 status = git_gpg_config(k, v, NULL);
1320 if (status)
1321 return status;
1322 return git_status_config(k, v, s);
1325 static int run_rewrite_hook(const unsigned char *oldsha1,
1326 const unsigned char *newsha1)
1328 /* oldsha1 SP newsha1 LF NUL */
1329 static char buf[2*40 + 3];
1330 struct child_process proc;
1331 const char *argv[3];
1332 int code;
1333 size_t n;
1335 argv[0] = find_hook("post-rewrite");
1336 if (!argv[0])
1337 return 0;
1339 argv[1] = "amend";
1340 argv[2] = NULL;
1342 memset(&proc, 0, sizeof(proc));
1343 proc.argv = argv;
1344 proc.in = -1;
1345 proc.stdout_to_stderr = 1;
1347 code = start_command(&proc);
1348 if (code)
1349 return code;
1350 n = snprintf(buf, sizeof(buf), "%s %s\n",
1351 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1352 write_in_full(proc.in, buf, n);
1353 close(proc.in);
1354 return finish_command(&proc);
1357 int cmd_commit(int argc, const char **argv, const char *prefix)
1359 static struct wt_status s;
1360 static struct option builtin_commit_options[] = {
1361 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1362 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1364 OPT_GROUP(N_("Commit message options")),
1365 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1366 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1367 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1368 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1369 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1370 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1371 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1372 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1373 OPT_BOOLEAN(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1374 OPT_BOOLEAN('s', "signoff", &signoff, N_("add Signed-off-by:")),
1375 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1376 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1377 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1378 OPT_BOOLEAN(0, "status", &include_status, N_("include status in commit message template")),
1379 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key id"),
1380 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1381 /* end commit message options */
1383 OPT_GROUP(N_("Commit contents options")),
1384 OPT_BOOLEAN('a', "all", &all, N_("commit all changed files")),
1385 OPT_BOOLEAN('i', "include", &also, N_("add specified files to index for commit")),
1386 OPT_BOOLEAN(0, "interactive", &interactive, N_("interactively add files")),
1387 OPT_BOOLEAN('p', "patch", &patch_interactive, N_("interactively add changes")),
1388 OPT_BOOLEAN('o', "only", &only, N_("commit only specified files")),
1389 OPT_BOOLEAN('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1390 OPT_BOOLEAN(0, "dry-run", &dry_run, N_("show what would be committed")),
1391 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1392 STATUS_FORMAT_SHORT),
1393 OPT_BOOLEAN(0, "branch", &s.show_branch, N_("show branch information")),
1394 OPT_SET_INT(0, "porcelain", &status_format,
1395 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1396 OPT_SET_INT(0, "long", &status_format,
1397 N_("show status in long format (default)"),
1398 STATUS_FORMAT_LONG),
1399 OPT_BOOLEAN('z', "null", &s.null_termination,
1400 N_("terminate entries with NUL")),
1401 OPT_BOOLEAN(0, "amend", &amend, N_("amend previous commit")),
1402 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1403 { 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" },
1404 /* end commit contents options */
1406 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
1407 N_("ok to record an empty change"),
1408 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1409 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
1410 N_("ok to record a change with an empty message"),
1411 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1413 OPT_END()
1416 struct strbuf sb = STRBUF_INIT;
1417 struct strbuf author_ident = STRBUF_INIT;
1418 const char *index_file, *reflog_msg;
1419 char *nl, *p;
1420 unsigned char sha1[20];
1421 struct ref_lock *ref_lock;
1422 struct commit_list *parents = NULL, **pptr = &parents;
1423 struct stat statbuf;
1424 int allow_fast_forward = 1;
1425 struct commit *current_head = NULL;
1426 struct commit_extra_header *extra = NULL;
1428 if (argc == 2 && !strcmp(argv[1], "-h"))
1429 usage_with_options(builtin_commit_usage, builtin_commit_options);
1431 wt_status_prepare(&s);
1432 gitmodules_config();
1433 git_config(git_commit_config, &s);
1434 determine_whence(&s);
1435 s.colopts = 0;
1437 if (get_sha1("HEAD", sha1))
1438 current_head = NULL;
1439 else {
1440 current_head = lookup_commit_or_die(sha1, "HEAD");
1441 if (!current_head || parse_commit(current_head))
1442 die(_("could not parse HEAD commit"));
1444 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1445 builtin_commit_usage,
1446 prefix, current_head, &s);
1447 if (dry_run)
1448 return dry_run_commit(argc, argv, prefix, current_head, &s);
1449 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1451 /* Set up everything for writing the commit object. This includes
1452 running hooks, writing the trees, and interacting with the user. */
1453 if (!prepare_to_commit(index_file, prefix,
1454 current_head, &s, &author_ident)) {
1455 rollback_index_files();
1456 return 1;
1459 /* Determine parents */
1460 reflog_msg = getenv("GIT_REFLOG_ACTION");
1461 if (!current_head) {
1462 if (!reflog_msg)
1463 reflog_msg = "commit (initial)";
1464 } else if (amend) {
1465 struct commit_list *c;
1467 if (!reflog_msg)
1468 reflog_msg = "commit (amend)";
1469 for (c = current_head->parents; c; c = c->next)
1470 pptr = &commit_list_insert(c->item, pptr)->next;
1471 } else if (whence == FROM_MERGE) {
1472 struct strbuf m = STRBUF_INIT;
1473 FILE *fp;
1475 if (!reflog_msg)
1476 reflog_msg = "commit (merge)";
1477 pptr = &commit_list_insert(current_head, pptr)->next;
1478 fp = fopen(git_path("MERGE_HEAD"), "r");
1479 if (fp == NULL)
1480 die_errno(_("could not open '%s' for reading"),
1481 git_path("MERGE_HEAD"));
1482 while (strbuf_getline(&m, fp, '\n') != EOF) {
1483 struct commit *parent;
1485 parent = get_merge_parent(m.buf);
1486 if (!parent)
1487 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1488 pptr = &commit_list_insert(parent, pptr)->next;
1490 fclose(fp);
1491 strbuf_release(&m);
1492 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1493 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1494 die_errno(_("could not read MERGE_MODE"));
1495 if (!strcmp(sb.buf, "no-ff"))
1496 allow_fast_forward = 0;
1498 if (allow_fast_forward)
1499 parents = reduce_heads(parents);
1500 } else {
1501 if (!reflog_msg)
1502 reflog_msg = (whence == FROM_CHERRY_PICK)
1503 ? "commit (cherry-pick)"
1504 : "commit";
1505 pptr = &commit_list_insert(current_head, pptr)->next;
1508 /* Finally, get the commit message */
1509 strbuf_reset(&sb);
1510 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1511 int saved_errno = errno;
1512 rollback_index_files();
1513 die(_("could not read commit message: %s"), strerror(saved_errno));
1516 /* Truncate the message just before the diff, if any. */
1517 if (verbose) {
1518 p = strstr(sb.buf, "\ndiff --git ");
1519 if (p != NULL)
1520 strbuf_setlen(&sb, p - sb.buf + 1);
1523 if (cleanup_mode != CLEANUP_NONE)
1524 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1525 if (template_untouched(&sb) && !allow_empty_message) {
1526 rollback_index_files();
1527 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1528 exit(1);
1530 if (message_is_empty(&sb) && !allow_empty_message) {
1531 rollback_index_files();
1532 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1533 exit(1);
1536 if (amend) {
1537 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1538 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1539 } else {
1540 struct commit_extra_header **tail = &extra;
1541 append_merge_tag_headers(parents, &tail);
1544 if (commit_tree_extended(&sb, active_cache_tree->sha1, parents, sha1,
1545 author_ident.buf, sign_commit, extra)) {
1546 rollback_index_files();
1547 die(_("failed to write commit object"));
1549 strbuf_release(&author_ident);
1550 free_commit_extra_headers(extra);
1552 ref_lock = lock_any_ref_for_update("HEAD",
1553 !current_head
1554 ? NULL
1555 : current_head->object.sha1,
1558 nl = strchr(sb.buf, '\n');
1559 if (nl)
1560 strbuf_setlen(&sb, nl + 1 - sb.buf);
1561 else
1562 strbuf_addch(&sb, '\n');
1563 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1564 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1566 if (!ref_lock) {
1567 rollback_index_files();
1568 die(_("cannot lock HEAD ref"));
1570 if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1571 rollback_index_files();
1572 die(_("cannot update HEAD ref"));
1575 unlink(git_path("CHERRY_PICK_HEAD"));
1576 unlink(git_path("REVERT_HEAD"));
1577 unlink(git_path("MERGE_HEAD"));
1578 unlink(git_path("MERGE_MSG"));
1579 unlink(git_path("MERGE_MODE"));
1580 unlink(git_path("SQUASH_MSG"));
1582 if (commit_index_files())
1583 die (_("Repository has been updated, but unable to write\n"
1584 "new_index file. Check that disk is not full or quota is\n"
1585 "not exceeded, and then \"git reset HEAD\" to recover."));
1587 rerere(0);
1588 run_hook(get_index_file(), "post-commit", NULL);
1589 if (amend && !no_post_rewrite) {
1590 struct notes_rewrite_cfg *cfg;
1591 cfg = init_copy_notes_for_rewrite("amend");
1592 if (cfg) {
1593 /* we are amending, so current_head is not NULL */
1594 copy_note_for_rewrite(cfg, current_head->object.sha1, sha1);
1595 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1597 run_rewrite_hook(current_head->object.sha1, sha1);
1599 if (!quiet)
1600 print_summary(prefix, sha1, !current_head);
1602 return 0;