oidtree: avoid nested struct oidtree_node
[git/debian.git] / builtin / commit.c
blob190d215d43b37b27f276347eb3bd1010264917f6
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 #define USE_THE_INDEX_COMPATIBILITY_MACROS
9 #include "cache.h"
10 #include "config.h"
11 #include "lockfile.h"
12 #include "cache-tree.h"
13 #include "color.h"
14 #include "dir.h"
15 #include "builtin.h"
16 #include "diff.h"
17 #include "diffcore.h"
18 #include "commit.h"
19 #include "revision.h"
20 #include "wt-status.h"
21 #include "run-command.h"
22 #include "refs.h"
23 #include "log-tree.h"
24 #include "strbuf.h"
25 #include "utf8.h"
26 #include "parse-options.h"
27 #include "string-list.h"
28 #include "rerere.h"
29 #include "unpack-trees.h"
30 #include "quote.h"
31 #include "submodule.h"
32 #include "gpg-interface.h"
33 #include "column.h"
34 #include "sequencer.h"
35 #include "mailmap.h"
36 #include "help.h"
37 #include "commit-reach.h"
38 #include "commit-graph.h"
40 static const char * const builtin_commit_usage[] = {
41 N_("git commit [<options>] [--] <pathspec>..."),
42 NULL
45 static const char * const builtin_status_usage[] = {
46 N_("git status [<options>] [--] <pathspec>..."),
47 NULL
50 static const char empty_amend_advice[] =
51 N_("You asked to amend the most recent commit, but doing so would make\n"
52 "it empty. You can repeat your command with --allow-empty, or you can\n"
53 "remove the commit entirely with \"git reset HEAD^\".\n");
55 static const char empty_cherry_pick_advice[] =
56 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
57 "If you wish to commit it anyway, use:\n"
58 "\n"
59 " git commit --allow-empty\n"
60 "\n");
62 static const char empty_rebase_pick_advice[] =
63 N_("Otherwise, please use 'git rebase --skip'\n");
65 static const char empty_cherry_pick_advice_single[] =
66 N_("Otherwise, please use 'git cherry-pick --skip'\n");
68 static const char empty_cherry_pick_advice_multi[] =
69 N_("and then use:\n"
70 "\n"
71 " git cherry-pick --continue\n"
72 "\n"
73 "to resume cherry-picking the remaining commits.\n"
74 "If you wish to skip this commit, use:\n"
75 "\n"
76 " git cherry-pick --skip\n"
77 "\n");
79 static const char *color_status_slots[] = {
80 [WT_STATUS_HEADER] = "header",
81 [WT_STATUS_UPDATED] = "updated",
82 [WT_STATUS_CHANGED] = "changed",
83 [WT_STATUS_UNTRACKED] = "untracked",
84 [WT_STATUS_NOBRANCH] = "noBranch",
85 [WT_STATUS_UNMERGED] = "unmerged",
86 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
87 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
88 [WT_STATUS_ONBRANCH] = "branch",
91 static const char *use_message_buffer;
92 static struct lock_file index_lock; /* real index */
93 static struct lock_file false_lock; /* used only for partial commits */
94 static enum {
95 COMMIT_AS_IS = 1,
96 COMMIT_NORMAL,
97 COMMIT_PARTIAL
98 } commit_style;
100 static const char *logfile, *force_author;
101 static const char *template_file;
103 * The _message variables are commit names from which to take
104 * the commit message and/or authorship.
106 static const char *author_message, *author_message_buffer;
107 static char *edit_message, *use_message;
108 static char *fixup_message, *fixup_commit, *squash_message;
109 static const char *fixup_prefix;
110 static int all, also, interactive, patch_interactive, only, amend, signoff;
111 static int edit_flag = -1; /* unspecified */
112 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
113 static int config_commit_verbose = -1; /* unspecified */
114 static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
115 static char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
116 static char *sign_commit, *pathspec_from_file;
117 static struct strvec trailer_args = STRVEC_INIT;
120 * The default commit message cleanup mode will remove the lines
121 * beginning with # (shell comments) and leading and trailing
122 * whitespaces (empty lines or containing only whitespaces)
123 * if editor is used, and only the whitespaces if the message
124 * is specified explicitly.
126 static enum commit_msg_cleanup_mode cleanup_mode;
127 static const char *cleanup_arg;
129 static enum commit_whence whence;
130 static int use_editor = 1, include_status = 1;
131 static int have_option_m;
132 static struct strbuf message = STRBUF_INIT;
134 static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
136 static int opt_pass_trailer(const struct option *opt, const char *arg, int unset)
138 BUG_ON_OPT_NEG(unset);
140 strvec_pushl(&trailer_args, "--trailer", arg, NULL);
141 return 0;
144 static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
146 enum wt_status_format *value = (enum wt_status_format *)opt->value;
147 if (unset)
148 *value = STATUS_FORMAT_NONE;
149 else if (!arg)
150 *value = STATUS_FORMAT_PORCELAIN;
151 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
152 *value = STATUS_FORMAT_PORCELAIN;
153 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
154 *value = STATUS_FORMAT_PORCELAIN_V2;
155 else
156 die("unsupported porcelain version '%s'", arg);
158 return 0;
161 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
163 struct strbuf *buf = opt->value;
164 if (unset) {
165 have_option_m = 0;
166 strbuf_setlen(buf, 0);
167 } else {
168 have_option_m = 1;
169 if (buf->len)
170 strbuf_addch(buf, '\n');
171 strbuf_addstr(buf, arg);
172 strbuf_complete_line(buf);
174 return 0;
177 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
179 const char **value = opt->value;
181 BUG_ON_OPT_NEG(unset);
183 if (arg != NULL && *arg == '=')
184 arg = arg + 1;
186 *value = arg;
187 return 0;
190 static void determine_whence(struct wt_status *s)
192 if (file_exists(git_path_merge_head(the_repository)))
193 whence = FROM_MERGE;
194 else if (!sequencer_determine_whence(the_repository, &whence))
195 whence = FROM_COMMIT;
196 if (s)
197 s->whence = whence;
200 static void status_init_config(struct wt_status *s, config_fn_t fn)
202 wt_status_prepare(the_repository, s);
203 init_diff_ui_defaults();
204 git_config(fn, s);
205 determine_whence(s);
206 s->hints = advice_status_hints; /* must come after git_config() */
209 static void rollback_index_files(void)
211 switch (commit_style) {
212 case COMMIT_AS_IS:
213 break; /* nothing to do */
214 case COMMIT_NORMAL:
215 rollback_lock_file(&index_lock);
216 break;
217 case COMMIT_PARTIAL:
218 rollback_lock_file(&index_lock);
219 rollback_lock_file(&false_lock);
220 break;
224 static int commit_index_files(void)
226 int err = 0;
228 switch (commit_style) {
229 case COMMIT_AS_IS:
230 break; /* nothing to do */
231 case COMMIT_NORMAL:
232 err = commit_lock_file(&index_lock);
233 break;
234 case COMMIT_PARTIAL:
235 err = commit_lock_file(&index_lock);
236 rollback_lock_file(&false_lock);
237 break;
240 return err;
244 * Take a union of paths in the index and the named tree (typically, "HEAD"),
245 * and return the paths that match the given pattern in list.
247 static int list_paths(struct string_list *list, const char *with_tree,
248 const struct pathspec *pattern)
250 int i, ret;
251 char *m;
253 if (!pattern->nr)
254 return 0;
256 m = xcalloc(1, pattern->nr);
258 if (with_tree) {
259 char *max_prefix = common_prefix(pattern);
260 overlay_tree_on_index(&the_index, with_tree, max_prefix);
261 free(max_prefix);
264 /* TODO: audit for interaction with sparse-index. */
265 ensure_full_index(&the_index);
266 for (i = 0; i < active_nr; i++) {
267 const struct cache_entry *ce = active_cache[i];
268 struct string_list_item *item;
270 if (ce->ce_flags & CE_UPDATE)
271 continue;
272 if (!ce_path_match(&the_index, ce, pattern, m))
273 continue;
274 item = string_list_insert(list, ce->name);
275 if (ce_skip_worktree(ce))
276 item->util = item; /* better a valid pointer than a fake one */
279 ret = report_path_error(m, pattern);
280 free(m);
281 return ret;
284 static void add_remove_files(struct string_list *list)
286 int i;
287 for (i = 0; i < list->nr; i++) {
288 struct stat st;
289 struct string_list_item *p = &(list->items[i]);
291 /* p->util is skip-worktree */
292 if (p->util)
293 continue;
295 if (!lstat(p->string, &st)) {
296 if (add_to_cache(p->string, &st, 0))
297 die(_("updating files failed"));
298 } else
299 remove_file_from_cache(p->string);
303 static void create_base_index(const struct commit *current_head)
305 struct tree *tree;
306 struct unpack_trees_options opts;
307 struct tree_desc t;
309 if (!current_head) {
310 discard_cache();
311 return;
314 memset(&opts, 0, sizeof(opts));
315 opts.head_idx = 1;
316 opts.index_only = 1;
317 opts.merge = 1;
318 opts.src_index = &the_index;
319 opts.dst_index = &the_index;
321 opts.fn = oneway_merge;
322 tree = parse_tree_indirect(&current_head->object.oid);
323 if (!tree)
324 die(_("failed to unpack HEAD tree object"));
325 parse_tree(tree);
326 init_tree_desc(&t, tree->buffer, tree->size);
327 if (unpack_trees(1, &t, &opts))
328 exit(128); /* We've already reported the error, finish dying */
331 static void refresh_cache_or_die(int refresh_flags)
334 * refresh_flags contains REFRESH_QUIET, so the only errors
335 * are for unmerged entries.
337 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
338 die_resolve_conflict("commit");
341 static const char *prepare_index(const char **argv, const char *prefix,
342 const struct commit *current_head, int is_status)
344 struct string_list partial = STRING_LIST_INIT_DUP;
345 struct pathspec pathspec;
346 int refresh_flags = REFRESH_QUIET;
347 const char *ret;
349 if (is_status)
350 refresh_flags |= REFRESH_UNMERGED;
351 parse_pathspec(&pathspec, 0,
352 PATHSPEC_PREFER_FULL,
353 prefix, argv);
355 if (pathspec_from_file) {
356 if (interactive)
357 die(_("--pathspec-from-file is incompatible with --interactive/--patch"));
359 if (all)
360 die(_("--pathspec-from-file with -a does not make sense"));
362 if (pathspec.nr)
363 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
365 parse_pathspec_file(&pathspec, 0,
366 PATHSPEC_PREFER_FULL,
367 prefix, pathspec_from_file, pathspec_file_nul);
368 } else if (pathspec_file_nul) {
369 die(_("--pathspec-file-nul requires --pathspec-from-file"));
372 if (!pathspec.nr && (also || (only && !allow_empty &&
373 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
374 die(_("No paths with --include/--only does not make sense."));
376 if (read_cache_preload(&pathspec) < 0)
377 die(_("index file corrupt"));
379 if (interactive) {
380 char *old_index_env = NULL, *old_repo_index_file;
381 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
383 refresh_cache_or_die(refresh_flags);
385 if (write_locked_index(&the_index, &index_lock, 0))
386 die(_("unable to create temporary index"));
388 old_repo_index_file = the_repository->index_file;
389 the_repository->index_file =
390 (char *)get_lock_file_path(&index_lock);
391 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
392 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
394 if (interactive_add(argv, prefix, patch_interactive) != 0)
395 die(_("interactive add failed"));
397 the_repository->index_file = old_repo_index_file;
398 if (old_index_env && *old_index_env)
399 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
400 else
401 unsetenv(INDEX_ENVIRONMENT);
402 FREE_AND_NULL(old_index_env);
404 discard_cache();
405 read_cache_from(get_lock_file_path(&index_lock));
406 if (update_main_cache_tree(WRITE_TREE_SILENT) == 0) {
407 if (reopen_lock_file(&index_lock) < 0)
408 die(_("unable to write index file"));
409 if (write_locked_index(&the_index, &index_lock, 0))
410 die(_("unable to update temporary index"));
411 } else
412 warning(_("Failed to update main cache tree"));
414 commit_style = COMMIT_NORMAL;
415 ret = get_lock_file_path(&index_lock);
416 goto out;
420 * Non partial, non as-is commit.
422 * (1) get the real index;
423 * (2) update the_index as necessary;
424 * (3) write the_index out to the real index (still locked);
425 * (4) return the name of the locked index file.
427 * The caller should run hooks on the locked real index, and
428 * (A) if all goes well, commit the real index;
429 * (B) on failure, rollback the real index.
431 if (all || (also && pathspec.nr)) {
432 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
433 add_files_to_cache(also ? prefix : NULL, &pathspec, 0);
434 refresh_cache_or_die(refresh_flags);
435 update_main_cache_tree(WRITE_TREE_SILENT);
436 if (write_locked_index(&the_index, &index_lock, 0))
437 die(_("unable to write new_index file"));
438 commit_style = COMMIT_NORMAL;
439 ret = get_lock_file_path(&index_lock);
440 goto out;
444 * As-is commit.
446 * (1) return the name of the real index file.
448 * The caller should run hooks on the real index,
449 * and create commit from the_index.
450 * We still need to refresh the index here.
452 if (!only && !pathspec.nr) {
453 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
454 refresh_cache_or_die(refresh_flags);
455 if (active_cache_changed
456 || !cache_tree_fully_valid(active_cache_tree))
457 update_main_cache_tree(WRITE_TREE_SILENT);
458 if (write_locked_index(&the_index, &index_lock,
459 COMMIT_LOCK | SKIP_IF_UNCHANGED))
460 die(_("unable to write new_index file"));
461 commit_style = COMMIT_AS_IS;
462 ret = get_index_file();
463 goto out;
467 * A partial commit.
469 * (0) find the set of affected paths;
470 * (1) get lock on the real index file;
471 * (2) update the_index with the given paths;
472 * (3) write the_index out to the real index (still locked);
473 * (4) get lock on the false index file;
474 * (5) reset the_index from HEAD;
475 * (6) update the_index the same way as (2);
476 * (7) write the_index out to the false index file;
477 * (8) return the name of the false index file (still locked);
479 * The caller should run hooks on the locked false index, and
480 * create commit from it. Then
481 * (A) if all goes well, commit the real index;
482 * (B) on failure, rollback the real index;
483 * In either case, rollback the false index.
485 commit_style = COMMIT_PARTIAL;
487 if (whence != FROM_COMMIT) {
488 if (whence == FROM_MERGE)
489 die(_("cannot do a partial commit during a merge."));
490 else if (is_from_cherry_pick(whence))
491 die(_("cannot do a partial commit during a cherry-pick."));
492 else if (is_from_rebase(whence))
493 die(_("cannot do a partial commit during a rebase."));
496 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
497 exit(1);
499 discard_cache();
500 if (read_cache() < 0)
501 die(_("cannot read the index"));
503 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
504 add_remove_files(&partial);
505 refresh_cache(REFRESH_QUIET);
506 update_main_cache_tree(WRITE_TREE_SILENT);
507 if (write_locked_index(&the_index, &index_lock, 0))
508 die(_("unable to write new_index file"));
510 hold_lock_file_for_update(&false_lock,
511 git_path("next-index-%"PRIuMAX,
512 (uintmax_t) getpid()),
513 LOCK_DIE_ON_ERROR);
515 create_base_index(current_head);
516 add_remove_files(&partial);
517 refresh_cache(REFRESH_QUIET);
519 if (write_locked_index(&the_index, &false_lock, 0))
520 die(_("unable to write temporary index file"));
522 discard_cache();
523 ret = get_lock_file_path(&false_lock);
524 read_cache_from(ret);
525 out:
526 string_list_clear(&partial, 0);
527 clear_pathspec(&pathspec);
528 return ret;
531 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
532 struct wt_status *s)
534 struct object_id oid;
536 if (s->relative_paths)
537 s->prefix = prefix;
539 if (amend) {
540 s->amend = 1;
541 s->reference = "HEAD^1";
543 s->verbose = verbose;
544 s->index_file = index_file;
545 s->fp = fp;
546 s->nowarn = nowarn;
547 s->is_initial = get_oid(s->reference, &oid) ? 1 : 0;
548 if (!s->is_initial)
549 oidcpy(&s->oid_commit, &oid);
550 s->status_format = status_format;
551 s->ignore_submodule_arg = ignore_submodule_arg;
553 wt_status_collect(s);
554 wt_status_print(s);
555 wt_status_collect_free_buffers(s);
557 return s->committable;
560 static int is_a_merge(const struct commit *current_head)
562 return !!(current_head->parents && current_head->parents->next);
565 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
567 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
568 BUG("unable to parse our own ident: %s", buf->buf);
571 static void export_one(const char *var, const char *s, const char *e, int hack)
573 struct strbuf buf = STRBUF_INIT;
574 if (hack)
575 strbuf_addch(&buf, hack);
576 strbuf_add(&buf, s, e - s);
577 setenv(var, buf.buf, 1);
578 strbuf_release(&buf);
581 static int parse_force_date(const char *in, struct strbuf *out)
583 strbuf_addch(out, '@');
585 if (parse_date(in, out) < 0) {
586 int errors = 0;
587 unsigned long t = approxidate_careful(in, &errors);
588 if (errors)
589 return -1;
590 strbuf_addf(out, "%lu", t);
593 return 0;
596 static void set_ident_var(char **buf, char *val)
598 free(*buf);
599 *buf = val;
602 static void determine_author_info(struct strbuf *author_ident)
604 char *name, *email, *date;
605 struct ident_split author;
607 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
608 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
609 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
611 if (author_message) {
612 struct ident_split ident;
613 size_t len;
614 const char *a;
616 a = find_commit_header(author_message_buffer, "author", &len);
617 if (!a)
618 die(_("commit '%s' lacks author header"), author_message);
619 if (split_ident_line(&ident, a, len) < 0)
620 die(_("commit '%s' has malformed author line"), author_message);
622 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
623 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
625 if (ident.date_begin) {
626 struct strbuf date_buf = STRBUF_INIT;
627 strbuf_addch(&date_buf, '@');
628 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
629 strbuf_addch(&date_buf, ' ');
630 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
631 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
635 if (force_author) {
636 struct ident_split ident;
638 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
639 die(_("malformed --author parameter"));
640 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
641 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
644 if (force_date) {
645 struct strbuf date_buf = STRBUF_INIT;
646 if (parse_force_date(force_date, &date_buf))
647 die(_("invalid date format: %s"), force_date);
648 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
651 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
652 IDENT_STRICT));
653 assert_split_ident(&author, author_ident);
654 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
655 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
656 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
657 free(name);
658 free(email);
659 free(date);
662 static int author_date_is_interesting(void)
664 return author_message || force_date;
667 static void adjust_comment_line_char(const struct strbuf *sb)
669 char candidates[] = "#;@!$%^&|:";
670 char *candidate;
671 const char *p;
673 comment_line_char = candidates[0];
674 if (!memchr(sb->buf, comment_line_char, sb->len))
675 return;
677 p = sb->buf;
678 candidate = strchr(candidates, *p);
679 if (candidate)
680 *candidate = ' ';
681 for (p = sb->buf; *p; p++) {
682 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
683 candidate = strchr(candidates, p[1]);
684 if (candidate)
685 *candidate = ' ';
689 for (p = candidates; *p == ' '; p++)
691 if (!*p)
692 die(_("unable to select a comment character that is not used\n"
693 "in the current commit message"));
694 comment_line_char = *p;
697 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
698 struct pretty_print_context *ctx)
700 const char *buffer, *subject, *fmt;
702 buffer = get_commit_buffer(commit, NULL);
703 find_commit_subject(buffer, &subject);
705 * If we amend the 'amend!' commit then we don't want to
706 * duplicate the subject line.
708 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
709 format_commit_message(commit, fmt, sb, ctx);
710 unuse_commit_buffer(commit, buffer);
713 static int prepare_to_commit(const char *index_file, const char *prefix,
714 struct commit *current_head,
715 struct wt_status *s,
716 struct strbuf *author_ident)
718 struct stat statbuf;
719 struct strbuf committer_ident = STRBUF_INIT;
720 int committable;
721 struct strbuf sb = STRBUF_INIT;
722 const char *hook_arg1 = NULL;
723 const char *hook_arg2 = NULL;
724 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
725 int old_display_comment_prefix;
726 int merge_contains_scissors = 0;
728 /* This checks and barfs if author is badly specified */
729 determine_author_info(author_ident);
731 if (!no_verify && run_commit_hook(use_editor, index_file, "pre-commit", NULL))
732 return 0;
734 if (squash_message) {
736 * Insert the proper subject line before other commit
737 * message options add their content.
739 if (use_message && !strcmp(use_message, squash_message))
740 strbuf_addstr(&sb, "squash! ");
741 else {
742 struct pretty_print_context ctx = {0};
743 struct commit *c;
744 c = lookup_commit_reference_by_name(squash_message);
745 if (!c)
746 die(_("could not lookup commit %s"), squash_message);
747 ctx.output_encoding = get_commit_output_encoding();
748 format_commit_message(c, "squash! %s\n\n", &sb,
749 &ctx);
753 if (have_option_m && !fixup_message) {
754 strbuf_addbuf(&sb, &message);
755 hook_arg1 = "message";
756 } else if (logfile && !strcmp(logfile, "-")) {
757 if (isatty(0))
758 fprintf(stderr, _("(reading log message from standard input)\n"));
759 if (strbuf_read(&sb, 0, 0) < 0)
760 die_errno(_("could not read log from standard input"));
761 hook_arg1 = "message";
762 } else if (logfile) {
763 if (strbuf_read_file(&sb, logfile, 0) < 0)
764 die_errno(_("could not read log file '%s'"),
765 logfile);
766 hook_arg1 = "message";
767 } else if (use_message) {
768 char *buffer;
769 buffer = strstr(use_message_buffer, "\n\n");
770 if (buffer)
771 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
772 hook_arg1 = "commit";
773 hook_arg2 = use_message;
774 } else if (fixup_message) {
775 struct pretty_print_context ctx = {0};
776 struct commit *commit;
777 char *fmt;
778 commit = lookup_commit_reference_by_name(fixup_commit);
779 if (!commit)
780 die(_("could not lookup commit %s"), fixup_commit);
781 ctx.output_encoding = get_commit_output_encoding();
782 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
783 format_commit_message(commit, fmt, &sb, &ctx);
784 free(fmt);
785 hook_arg1 = "message";
788 * Only `-m` commit message option is checked here, as
789 * it supports `--fixup` to append the commit message.
791 * The other commit message options `-c`/`-C`/`-F` are
792 * incompatible with all the forms of `--fixup` and
793 * have already errored out while parsing the `git commit`
794 * options.
796 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
797 strbuf_addbuf(&sb, &message);
799 if (!strcmp(fixup_prefix, "amend")) {
800 if (have_option_m)
801 die(_("cannot combine -m with --fixup:%s"), fixup_message);
802 prepare_amend_commit(commit, &sb, &ctx);
804 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
805 size_t merge_msg_start;
808 * prepend SQUASH_MSG here if it exists and a
809 * "merge --squash" was originally performed
811 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
812 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
813 die_errno(_("could not read SQUASH_MSG"));
814 hook_arg1 = "squash";
815 } else
816 hook_arg1 = "merge";
818 merge_msg_start = sb.len;
819 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
820 die_errno(_("could not read MERGE_MSG"));
822 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
823 wt_status_locate_end(sb.buf + merge_msg_start,
824 sb.len - merge_msg_start) <
825 sb.len - merge_msg_start)
826 merge_contains_scissors = 1;
827 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
828 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
829 die_errno(_("could not read SQUASH_MSG"));
830 hook_arg1 = "squash";
831 } else if (template_file) {
832 if (strbuf_read_file(&sb, template_file, 0) < 0)
833 die_errno(_("could not read '%s'"), template_file);
834 hook_arg1 = "template";
835 clean_message_contents = 0;
839 * The remaining cases don't modify the template message, but
840 * just set the argument(s) to the prepare-commit-msg hook.
842 else if (whence == FROM_MERGE)
843 hook_arg1 = "merge";
844 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
845 hook_arg1 = "commit";
846 hook_arg2 = "CHERRY_PICK_HEAD";
849 if (squash_message) {
851 * If squash_commit was used for the commit subject,
852 * then we're possibly hijacking other commit log options.
853 * Reset the hook args to tell the real story.
855 hook_arg1 = "message";
856 hook_arg2 = "";
859 s->fp = fopen_for_writing(git_path_commit_editmsg());
860 if (s->fp == NULL)
861 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
863 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
864 old_display_comment_prefix = s->display_comment_prefix;
865 s->display_comment_prefix = 1;
868 * Most hints are counter-productive when the commit has
869 * already started.
871 s->hints = 0;
873 if (clean_message_contents)
874 strbuf_stripspace(&sb, 0);
876 if (signoff)
877 append_signoff(&sb, ignore_non_trailer(sb.buf, sb.len), 0);
879 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
880 die_errno(_("could not write commit template"));
882 if (auto_comment_line_char)
883 adjust_comment_line_char(&sb);
884 strbuf_release(&sb);
886 /* This checks if committer ident is explicitly given */
887 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
888 if (use_editor && include_status) {
889 int ident_shown = 0;
890 int saved_color_setting;
891 struct ident_split ci, ai;
893 if (whence != FROM_COMMIT) {
894 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
895 !merge_contains_scissors)
896 wt_status_add_cut_line(s->fp);
897 status_printf_ln(
898 s, GIT_COLOR_NORMAL,
899 whence == FROM_MERGE ?
900 _("\n"
901 "It looks like you may be committing a merge.\n"
902 "If this is not correct, please run\n"
903 " git update-ref -d MERGE_HEAD\n"
904 "and try again.\n") :
905 _("\n"
906 "It looks like you may be committing a cherry-pick.\n"
907 "If this is not correct, please run\n"
908 " git update-ref -d CHERRY_PICK_HEAD\n"
909 "and try again.\n"));
912 fprintf(s->fp, "\n");
913 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
914 status_printf(s, GIT_COLOR_NORMAL,
915 _("Please enter the commit message for your changes."
916 " Lines starting\nwith '%c' will be ignored, and an empty"
917 " message aborts the commit.\n"), comment_line_char);
918 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
919 if (whence == FROM_COMMIT && !merge_contains_scissors)
920 wt_status_add_cut_line(s->fp);
921 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
922 status_printf(s, GIT_COLOR_NORMAL,
923 _("Please enter the commit message for your changes."
924 " Lines starting\n"
925 "with '%c' will be kept; you may remove them"
926 " yourself if you want to.\n"
927 "An empty message aborts the commit.\n"), comment_line_char);
930 * These should never fail because they come from our own
931 * fmt_ident. They may fail the sane_ident test, but we know
932 * that the name and mail pointers will at least be valid,
933 * which is enough for our tests and printing here.
935 assert_split_ident(&ai, author_ident);
936 assert_split_ident(&ci, &committer_ident);
938 if (ident_cmp(&ai, &ci))
939 status_printf_ln(s, GIT_COLOR_NORMAL,
940 _("%s"
941 "Author: %.*s <%.*s>"),
942 ident_shown++ ? "" : "\n",
943 (int)(ai.name_end - ai.name_begin), ai.name_begin,
944 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
946 if (author_date_is_interesting())
947 status_printf_ln(s, GIT_COLOR_NORMAL,
948 _("%s"
949 "Date: %s"),
950 ident_shown++ ? "" : "\n",
951 show_ident_date(&ai, DATE_MODE(NORMAL)));
953 if (!committer_ident_sufficiently_given())
954 status_printf_ln(s, GIT_COLOR_NORMAL,
955 _("%s"
956 "Committer: %.*s <%.*s>"),
957 ident_shown++ ? "" : "\n",
958 (int)(ci.name_end - ci.name_begin), ci.name_begin,
959 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
961 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
963 saved_color_setting = s->use_color;
964 s->use_color = 0;
965 committable = run_status(s->fp, index_file, prefix, 1, s);
966 s->use_color = saved_color_setting;
967 string_list_clear(&s->change, 1);
968 } else {
969 struct object_id oid;
970 const char *parent = "HEAD";
972 if (!active_nr && read_cache() < 0)
973 die(_("Cannot read index"));
975 if (amend)
976 parent = "HEAD^1";
978 if (get_oid(parent, &oid)) {
979 int i, ita_nr = 0;
981 /* TODO: audit for interaction with sparse-index. */
982 ensure_full_index(&the_index);
983 for (i = 0; i < active_nr; i++)
984 if (ce_intent_to_add(active_cache[i]))
985 ita_nr++;
986 committable = active_nr - ita_nr > 0;
987 } else {
989 * Unless the user did explicitly request a submodule
990 * ignore mode by passing a command line option we do
991 * not ignore any changed submodule SHA-1s when
992 * comparing index and parent, no matter what is
993 * configured. Otherwise we won't commit any
994 * submodules which were manually staged, which would
995 * be really confusing.
997 struct diff_flags flags = DIFF_FLAGS_INIT;
998 flags.override_submodule_config = 1;
999 if (ignore_submodule_arg &&
1000 !strcmp(ignore_submodule_arg, "all"))
1001 flags.ignore_submodules = 1;
1002 committable = index_differs_from(the_repository,
1003 parent, &flags, 1);
1006 strbuf_release(&committer_ident);
1008 fclose(s->fp);
1010 if (trailer_args.nr) {
1011 struct child_process run_trailer = CHILD_PROCESS_INIT;
1013 strvec_pushl(&run_trailer.args, "interpret-trailers",
1014 "--in-place", git_path_commit_editmsg(), NULL);
1015 strvec_pushv(&run_trailer.args, trailer_args.v);
1016 run_trailer.git_cmd = 1;
1017 if (run_command(&run_trailer))
1018 die(_("unable to pass trailers to --trailers"));
1019 strvec_clear(&trailer_args);
1023 * Reject an attempt to record a non-merge empty commit without
1024 * explicit --allow-empty. In the cherry-pick case, it may be
1025 * empty due to conflict resolution, which the user should okay.
1027 if (!committable && whence != FROM_MERGE && !allow_empty &&
1028 !(amend && is_a_merge(current_head))) {
1029 s->hints = advice_status_hints;
1030 s->display_comment_prefix = old_display_comment_prefix;
1031 run_status(stdout, index_file, prefix, 0, s);
1032 if (amend)
1033 fputs(_(empty_amend_advice), stderr);
1034 else if (is_from_cherry_pick(whence) ||
1035 whence == FROM_REBASE_PICK) {
1036 fputs(_(empty_cherry_pick_advice), stderr);
1037 if (whence == FROM_CHERRY_PICK_SINGLE)
1038 fputs(_(empty_cherry_pick_advice_single), stderr);
1039 else if (whence == FROM_CHERRY_PICK_MULTI)
1040 fputs(_(empty_cherry_pick_advice_multi), stderr);
1041 else
1042 fputs(_(empty_rebase_pick_advice), stderr);
1044 return 0;
1047 if (!no_verify && find_hook("pre-commit")) {
1049 * Re-read the index as pre-commit hook could have updated it,
1050 * and write it out as a tree. We must do this before we invoke
1051 * the editor and after we invoke run_status above.
1053 discard_cache();
1055 read_cache_from(index_file);
1057 if (update_main_cache_tree(0)) {
1058 error(_("Error building trees"));
1059 return 0;
1062 if (run_commit_hook(use_editor, index_file, "prepare-commit-msg",
1063 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1064 return 0;
1066 if (use_editor) {
1067 struct strvec env = STRVEC_INIT;
1069 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1070 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1071 fprintf(stderr,
1072 _("Please supply the message using either -m or -F option.\n"));
1073 exit(1);
1075 strvec_clear(&env);
1078 if (!no_verify &&
1079 run_commit_hook(use_editor, index_file, "commit-msg", git_path_commit_editmsg(), NULL)) {
1080 return 0;
1083 return 1;
1086 static const char *find_author_by_nickname(const char *name)
1088 struct rev_info revs;
1089 struct commit *commit;
1090 struct strbuf buf = STRBUF_INIT;
1091 struct string_list mailmap = STRING_LIST_INIT_NODUP;
1092 const char *av[20];
1093 int ac = 0;
1095 repo_init_revisions(the_repository, &revs, NULL);
1096 strbuf_addf(&buf, "--author=%s", name);
1097 av[++ac] = "--all";
1098 av[++ac] = "-i";
1099 av[++ac] = buf.buf;
1100 av[++ac] = NULL;
1101 setup_revisions(ac, av, &revs, NULL);
1102 revs.mailmap = &mailmap;
1103 read_mailmap(revs.mailmap);
1105 if (prepare_revision_walk(&revs))
1106 die(_("revision walk setup failed"));
1107 commit = get_revision(&revs);
1108 if (commit) {
1109 struct pretty_print_context ctx = {0};
1110 ctx.date_mode.type = DATE_NORMAL;
1111 strbuf_release(&buf);
1112 format_commit_message(commit, "%aN <%aE>", &buf, &ctx);
1113 clear_mailmap(&mailmap);
1114 return strbuf_detach(&buf, NULL);
1116 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1119 static void handle_ignored_arg(struct wt_status *s)
1121 if (!ignored_arg)
1122 ; /* default already initialized */
1123 else if (!strcmp(ignored_arg, "traditional"))
1124 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1125 else if (!strcmp(ignored_arg, "no"))
1126 s->show_ignored_mode = SHOW_NO_IGNORED;
1127 else if (!strcmp(ignored_arg, "matching"))
1128 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1129 else
1130 die(_("Invalid ignored mode '%s'"), ignored_arg);
1133 static void handle_untracked_files_arg(struct wt_status *s)
1135 if (!untracked_files_arg)
1136 ; /* default already initialized */
1137 else if (!strcmp(untracked_files_arg, "no"))
1138 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1139 else if (!strcmp(untracked_files_arg, "normal"))
1140 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1141 else if (!strcmp(untracked_files_arg, "all"))
1142 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1144 * Please update $__git_untracked_file_modes in
1145 * git-completion.bash when you add new options
1147 else
1148 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1151 static const char *read_commit_message(const char *name)
1153 const char *out_enc;
1154 struct commit *commit;
1156 commit = lookup_commit_reference_by_name(name);
1157 if (!commit)
1158 die(_("could not lookup commit %s"), name);
1159 out_enc = get_commit_output_encoding();
1160 return logmsg_reencode(commit, NULL, out_enc);
1164 * Enumerate what needs to be propagated when --porcelain
1165 * is not in effect here.
1167 static struct status_deferred_config {
1168 enum wt_status_format status_format;
1169 int show_branch;
1170 enum ahead_behind_flags ahead_behind;
1171 } status_deferred_config = {
1172 STATUS_FORMAT_UNSPECIFIED,
1173 -1, /* unspecified */
1174 AHEAD_BEHIND_UNSPECIFIED,
1177 static void finalize_deferred_config(struct wt_status *s)
1179 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1180 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1181 !s->null_termination);
1183 if (s->null_termination) {
1184 if (status_format == STATUS_FORMAT_NONE ||
1185 status_format == STATUS_FORMAT_UNSPECIFIED)
1186 status_format = STATUS_FORMAT_PORCELAIN;
1187 else if (status_format == STATUS_FORMAT_LONG)
1188 die(_("--long and -z are incompatible"));
1191 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1192 status_format = status_deferred_config.status_format;
1193 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1194 status_format = STATUS_FORMAT_NONE;
1196 if (use_deferred_config && s->show_branch < 0)
1197 s->show_branch = status_deferred_config.show_branch;
1198 if (s->show_branch < 0)
1199 s->show_branch = 0;
1202 * If the user did not give a "--[no]-ahead-behind" command
1203 * line argument *AND* we will print in a human-readable format
1204 * (short, long etc.) then we inherit from the status.aheadbehind
1205 * config setting. In all other cases (and porcelain V[12] formats
1206 * in particular), we inherit _FULL for backwards compatibility.
1208 if (use_deferred_config &&
1209 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1210 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1212 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1213 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1216 static void check_fixup_reword_options(int argc, const char *argv[]) {
1217 if (whence != FROM_COMMIT) {
1218 if (whence == FROM_MERGE)
1219 die(_("You are in the middle of a merge -- cannot reword."));
1220 else if (is_from_cherry_pick(whence))
1221 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1223 if (argc)
1224 die(_("cannot combine reword option of --fixup with path '%s'"), *argv);
1225 if (patch_interactive || interactive || all || also || only)
1226 die(_("reword option of --fixup is mutually exclusive with --patch/--interactive/--all/--include/--only"));
1229 static int parse_and_validate_options(int argc, const char *argv[],
1230 const struct option *options,
1231 const char * const usage[],
1232 const char *prefix,
1233 struct commit *current_head,
1234 struct wt_status *s)
1236 int f = 0;
1238 argc = parse_options(argc, argv, prefix, options, usage, 0);
1239 finalize_deferred_config(s);
1241 if (force_author && !strchr(force_author, '>'))
1242 force_author = find_author_by_nickname(force_author);
1244 if (force_author && renew_authorship)
1245 die(_("Using both --reset-author and --author does not make sense"));
1247 if (logfile || have_option_m || use_message)
1248 use_editor = 0;
1249 if (0 <= edit_flag)
1250 use_editor = edit_flag;
1252 /* Sanity check options */
1253 if (amend && !current_head)
1254 die(_("You have nothing to amend."));
1255 if (amend && whence != FROM_COMMIT) {
1256 if (whence == FROM_MERGE)
1257 die(_("You are in the middle of a merge -- cannot amend."));
1258 else if (is_from_cherry_pick(whence))
1259 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1260 else if (whence == FROM_REBASE_PICK)
1261 die(_("You are in the middle of a rebase -- cannot amend."));
1263 if (fixup_message && squash_message)
1264 die(_("Options --squash and --fixup cannot be used together"));
1265 if (use_message)
1266 f++;
1267 if (edit_message)
1268 f++;
1269 if (fixup_message)
1270 f++;
1271 if (logfile)
1272 f++;
1273 if (f > 1)
1274 die(_("Only one of -c/-C/-F/--fixup can be used."));
1275 if (have_option_m && (edit_message || use_message || logfile))
1276 die((_("Option -m cannot be combined with -c/-C/-F.")));
1277 if (f || have_option_m)
1278 template_file = NULL;
1279 if (edit_message)
1280 use_message = edit_message;
1281 if (amend && !use_message && !fixup_message)
1282 use_message = "HEAD";
1283 if (!use_message && !is_from_cherry_pick(whence) &&
1284 !is_from_rebase(whence) && renew_authorship)
1285 die(_("--reset-author can be used only with -C, -c or --amend."));
1286 if (use_message) {
1287 use_message_buffer = read_commit_message(use_message);
1288 if (!renew_authorship) {
1289 author_message = use_message;
1290 author_message_buffer = use_message_buffer;
1293 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1294 !renew_authorship) {
1295 author_message = "CHERRY_PICK_HEAD";
1296 author_message_buffer = read_commit_message(author_message);
1299 if (patch_interactive)
1300 interactive = 1;
1302 if (also + only + all + interactive > 1)
1303 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1305 if (fixup_message) {
1307 * We limit --fixup's suboptions to only alpha characters.
1308 * If the first character after a run of alpha is colon,
1309 * then the part before the colon may be a known suboption
1310 * name like `amend` or `reword`, or a misspelt suboption
1311 * name. In either case, we treat it as
1312 * --fixup=<suboption>:<arg>.
1314 * Otherwise, we are dealing with --fixup=<commit>.
1316 char *p = fixup_message;
1317 while (isalpha(*p))
1318 p++;
1319 if (p > fixup_message && *p == ':') {
1320 *p = '\0';
1321 fixup_commit = p + 1;
1322 if (!strcmp("amend", fixup_message) ||
1323 !strcmp("reword", fixup_message)) {
1324 fixup_prefix = "amend";
1325 allow_empty = 1;
1326 if (*fixup_message == 'r') {
1327 check_fixup_reword_options(argc, argv);
1328 only = 1;
1330 } else {
1331 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1333 } else {
1334 fixup_commit = fixup_message;
1335 fixup_prefix = "fixup";
1336 use_editor = 0;
1340 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1342 handle_untracked_files_arg(s);
1344 if (all && argc > 0)
1345 die(_("paths '%s ...' with -a does not make sense"),
1346 argv[0]);
1348 if (status_format != STATUS_FORMAT_NONE)
1349 dry_run = 1;
1351 return argc;
1354 static int dry_run_commit(const char **argv, const char *prefix,
1355 const struct commit *current_head, struct wt_status *s)
1357 int committable;
1358 const char *index_file;
1360 index_file = prepare_index(argv, prefix, current_head, 1);
1361 committable = run_status(stdout, index_file, prefix, 0, s);
1362 rollback_index_files();
1364 return committable ? 0 : 1;
1367 define_list_config_array_extra(color_status_slots, {"added"});
1369 static int parse_status_slot(const char *slot)
1371 if (!strcasecmp(slot, "added"))
1372 return WT_STATUS_UPDATED;
1374 return LOOKUP_CONFIG(color_status_slots, slot);
1377 static int git_status_config(const char *k, const char *v, void *cb)
1379 struct wt_status *s = cb;
1380 const char *slot_name;
1382 if (starts_with(k, "column."))
1383 return git_column_config(k, v, "status", &s->colopts);
1384 if (!strcmp(k, "status.submodulesummary")) {
1385 int is_bool;
1386 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1387 if (is_bool && s->submodule_summary)
1388 s->submodule_summary = -1;
1389 return 0;
1391 if (!strcmp(k, "status.short")) {
1392 if (git_config_bool(k, v))
1393 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1394 else
1395 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1396 return 0;
1398 if (!strcmp(k, "status.branch")) {
1399 status_deferred_config.show_branch = git_config_bool(k, v);
1400 return 0;
1402 if (!strcmp(k, "status.aheadbehind")) {
1403 status_deferred_config.ahead_behind = git_config_bool(k, v);
1404 return 0;
1406 if (!strcmp(k, "status.showstash")) {
1407 s->show_stash = git_config_bool(k, v);
1408 return 0;
1410 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1411 s->use_color = git_config_colorbool(k, v);
1412 return 0;
1414 if (!strcmp(k, "status.displaycommentprefix")) {
1415 s->display_comment_prefix = git_config_bool(k, v);
1416 return 0;
1418 if (skip_prefix(k, "status.color.", &slot_name) ||
1419 skip_prefix(k, "color.status.", &slot_name)) {
1420 int slot = parse_status_slot(slot_name);
1421 if (slot < 0)
1422 return 0;
1423 if (!v)
1424 return config_error_nonbool(k);
1425 return color_parse(v, s->color_palette[slot]);
1427 if (!strcmp(k, "status.relativepaths")) {
1428 s->relative_paths = git_config_bool(k, v);
1429 return 0;
1431 if (!strcmp(k, "status.showuntrackedfiles")) {
1432 if (!v)
1433 return config_error_nonbool(k);
1434 else if (!strcmp(v, "no"))
1435 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1436 else if (!strcmp(v, "normal"))
1437 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1438 else if (!strcmp(v, "all"))
1439 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1440 else
1441 return error(_("Invalid untracked files mode '%s'"), v);
1442 return 0;
1444 if (!strcmp(k, "diff.renamelimit")) {
1445 if (s->rename_limit == -1)
1446 s->rename_limit = git_config_int(k, v);
1447 return 0;
1449 if (!strcmp(k, "status.renamelimit")) {
1450 s->rename_limit = git_config_int(k, v);
1451 return 0;
1453 if (!strcmp(k, "diff.renames")) {
1454 if (s->detect_rename == -1)
1455 s->detect_rename = git_config_rename(k, v);
1456 return 0;
1458 if (!strcmp(k, "status.renames")) {
1459 s->detect_rename = git_config_rename(k, v);
1460 return 0;
1462 return git_diff_ui_config(k, v, NULL);
1465 int cmd_status(int argc, const char **argv, const char *prefix)
1467 static int no_renames = -1;
1468 static const char *rename_score_arg = (const char *)-1;
1469 static struct wt_status s;
1470 unsigned int progress_flag = 0;
1471 int fd;
1472 struct object_id oid;
1473 static struct option builtin_status_options[] = {
1474 OPT__VERBOSE(&verbose, N_("be verbose")),
1475 OPT_SET_INT('s', "short", &status_format,
1476 N_("show status concisely"), STATUS_FORMAT_SHORT),
1477 OPT_BOOL('b', "branch", &s.show_branch,
1478 N_("show branch information")),
1479 OPT_BOOL(0, "show-stash", &s.show_stash,
1480 N_("show stash information")),
1481 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1482 N_("compute full ahead/behind values")),
1483 OPT_CALLBACK_F(0, "porcelain", &status_format,
1484 N_("version"), N_("machine-readable output"),
1485 PARSE_OPT_OPTARG, opt_parse_porcelain),
1486 OPT_SET_INT(0, "long", &status_format,
1487 N_("show status in long format (default)"),
1488 STATUS_FORMAT_LONG),
1489 OPT_BOOL('z', "null", &s.null_termination,
1490 N_("terminate entries with NUL")),
1491 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1492 N_("mode"),
1493 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1494 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1495 { OPTION_STRING, 0, "ignored", &ignored_arg,
1496 N_("mode"),
1497 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1498 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1499 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1500 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1501 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1502 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1503 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1504 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1505 N_("n"), N_("detect renames, optionally set similarity index"),
1506 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1507 OPT_END(),
1510 if (argc == 2 && !strcmp(argv[1], "-h"))
1511 usage_with_options(builtin_status_usage, builtin_status_options);
1513 status_init_config(&s, git_status_config);
1514 argc = parse_options(argc, argv, prefix,
1515 builtin_status_options,
1516 builtin_status_usage, 0);
1517 finalize_colopts(&s.colopts, -1);
1518 finalize_deferred_config(&s);
1520 handle_untracked_files_arg(&s);
1521 handle_ignored_arg(&s);
1523 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1524 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1525 die(_("Unsupported combination of ignored and untracked-files arguments"));
1527 parse_pathspec(&s.pathspec, 0,
1528 PATHSPEC_PREFER_FULL,
1529 prefix, argv);
1531 if (status_format != STATUS_FORMAT_PORCELAIN &&
1532 status_format != STATUS_FORMAT_PORCELAIN_V2)
1533 progress_flag = REFRESH_PROGRESS;
1534 repo_read_index(the_repository);
1535 refresh_index(&the_index,
1536 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1537 &s.pathspec, NULL, NULL);
1539 if (use_optional_locks())
1540 fd = hold_locked_index(&index_lock, 0);
1541 else
1542 fd = -1;
1544 s.is_initial = get_oid(s.reference, &oid) ? 1 : 0;
1545 if (!s.is_initial)
1546 oidcpy(&s.oid_commit, &oid);
1548 s.ignore_submodule_arg = ignore_submodule_arg;
1549 s.status_format = status_format;
1550 s.verbose = verbose;
1551 if (no_renames != -1)
1552 s.detect_rename = !no_renames;
1553 if ((intptr_t)rename_score_arg != -1) {
1554 if (s.detect_rename < DIFF_DETECT_RENAME)
1555 s.detect_rename = DIFF_DETECT_RENAME;
1556 if (rename_score_arg)
1557 s.rename_score = parse_rename_score(&rename_score_arg);
1560 wt_status_collect(&s);
1562 if (0 <= fd)
1563 repo_update_index_if_able(the_repository, &index_lock);
1565 if (s.relative_paths)
1566 s.prefix = prefix;
1568 wt_status_print(&s);
1569 wt_status_collect_free_buffers(&s);
1571 return 0;
1574 static int git_commit_config(const char *k, const char *v, void *cb)
1576 struct wt_status *s = cb;
1577 int status;
1579 if (!strcmp(k, "commit.template"))
1580 return git_config_pathname(&template_file, k, v);
1581 if (!strcmp(k, "commit.status")) {
1582 include_status = git_config_bool(k, v);
1583 return 0;
1585 if (!strcmp(k, "commit.cleanup"))
1586 return git_config_string(&cleanup_arg, k, v);
1587 if (!strcmp(k, "commit.gpgsign")) {
1588 sign_commit = git_config_bool(k, v) ? "" : NULL;
1589 return 0;
1591 if (!strcmp(k, "commit.verbose")) {
1592 int is_bool;
1593 config_commit_verbose = git_config_bool_or_int(k, v, &is_bool);
1594 return 0;
1597 status = git_gpg_config(k, v, NULL);
1598 if (status)
1599 return status;
1600 return git_status_config(k, v, s);
1603 int cmd_commit(int argc, const char **argv, const char *prefix)
1605 static struct wt_status s;
1606 static struct option builtin_commit_options[] = {
1607 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1608 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1610 OPT_GROUP(N_("Commit message options")),
1611 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1612 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1613 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1614 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1615 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1616 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1618 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1619 * and only translate <commit>.
1621 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1622 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1623 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1624 OPT_CALLBACK_F(0, "trailer", NULL, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG, opt_pass_trailer),
1625 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1626 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1627 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1628 OPT_CLEANUP(&cleanup_arg),
1629 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1630 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1631 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1632 /* end commit message options */
1634 OPT_GROUP(N_("Commit contents options")),
1635 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1636 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1637 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1638 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1639 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1640 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1641 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1642 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1643 STATUS_FORMAT_SHORT),
1644 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1645 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1646 N_("compute full ahead/behind values")),
1647 OPT_SET_INT(0, "porcelain", &status_format,
1648 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1649 OPT_SET_INT(0, "long", &status_format,
1650 N_("show status in long format (default)"),
1651 STATUS_FORMAT_LONG),
1652 OPT_BOOL('z', "null", &s.null_termination,
1653 N_("terminate entries with NUL")),
1654 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1655 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1656 { 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" },
1657 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1658 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1659 /* end commit contents options */
1661 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1662 N_("ok to record an empty change")),
1663 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1664 N_("ok to record a change with an empty message")),
1666 OPT_END()
1669 struct strbuf sb = STRBUF_INIT;
1670 struct strbuf author_ident = STRBUF_INIT;
1671 const char *index_file, *reflog_msg;
1672 struct object_id oid;
1673 struct commit_list *parents = NULL;
1674 struct stat statbuf;
1675 struct commit *current_head = NULL;
1676 struct commit_extra_header *extra = NULL;
1677 struct strbuf err = STRBUF_INIT;
1679 if (argc == 2 && !strcmp(argv[1], "-h"))
1680 usage_with_options(builtin_commit_usage, builtin_commit_options);
1682 status_init_config(&s, git_commit_config);
1683 s.commit_template = 1;
1684 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1685 s.colopts = 0;
1687 if (get_oid("HEAD", &oid))
1688 current_head = NULL;
1689 else {
1690 current_head = lookup_commit_or_die(&oid, "HEAD");
1691 if (parse_commit(current_head))
1692 die(_("could not parse HEAD commit"));
1694 verbose = -1; /* unspecified */
1695 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1696 builtin_commit_usage,
1697 prefix, current_head, &s);
1698 if (verbose == -1)
1699 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1701 if (dry_run)
1702 return dry_run_commit(argv, prefix, current_head, &s);
1703 index_file = prepare_index(argv, prefix, current_head, 0);
1705 /* Set up everything for writing the commit object. This includes
1706 running hooks, writing the trees, and interacting with the user. */
1707 if (!prepare_to_commit(index_file, prefix,
1708 current_head, &s, &author_ident)) {
1709 rollback_index_files();
1710 return 1;
1713 /* Determine parents */
1714 reflog_msg = getenv("GIT_REFLOG_ACTION");
1715 if (!current_head) {
1716 if (!reflog_msg)
1717 reflog_msg = "commit (initial)";
1718 } else if (amend) {
1719 if (!reflog_msg)
1720 reflog_msg = "commit (amend)";
1721 parents = copy_commit_list(current_head->parents);
1722 } else if (whence == FROM_MERGE) {
1723 struct strbuf m = STRBUF_INIT;
1724 FILE *fp;
1725 int allow_fast_forward = 1;
1726 struct commit_list **pptr = &parents;
1728 if (!reflog_msg)
1729 reflog_msg = "commit (merge)";
1730 pptr = commit_list_append(current_head, pptr);
1731 fp = xfopen(git_path_merge_head(the_repository), "r");
1732 while (strbuf_getline_lf(&m, fp) != EOF) {
1733 struct commit *parent;
1735 parent = get_merge_parent(m.buf);
1736 if (!parent)
1737 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1738 pptr = commit_list_append(parent, pptr);
1740 fclose(fp);
1741 strbuf_release(&m);
1742 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1743 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1744 die_errno(_("could not read MERGE_MODE"));
1745 if (!strcmp(sb.buf, "no-ff"))
1746 allow_fast_forward = 0;
1748 if (allow_fast_forward)
1749 reduce_heads_replace(&parents);
1750 } else {
1751 if (!reflog_msg)
1752 reflog_msg = is_from_cherry_pick(whence)
1753 ? "commit (cherry-pick)"
1754 : is_from_rebase(whence)
1755 ? "commit (rebase)"
1756 : "commit";
1757 commit_list_insert(current_head, &parents);
1760 /* Finally, get the commit message */
1761 strbuf_reset(&sb);
1762 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1763 int saved_errno = errno;
1764 rollback_index_files();
1765 die(_("could not read commit message: %s"), strerror(saved_errno));
1768 cleanup_message(&sb, cleanup_mode, verbose);
1770 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1771 rollback_index_files();
1772 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1773 exit(1);
1775 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1776 rollback_index_files();
1777 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1778 exit(1);
1781 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1782 !allow_empty_message) {
1783 struct strbuf body = STRBUF_INIT;
1784 size_t len = commit_subject_length(sb.buf);
1785 strbuf_addstr(&body, sb.buf + len);
1786 if (message_is_empty(&body, cleanup_mode)) {
1787 rollback_index_files();
1788 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1789 exit(1);
1791 strbuf_release(&body);
1794 if (amend) {
1795 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1796 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1797 } else {
1798 struct commit_extra_header **tail = &extra;
1799 append_merge_tag_headers(parents, &tail);
1802 if (commit_tree_extended(sb.buf, sb.len, &active_cache_tree->oid,
1803 parents, &oid, author_ident.buf, NULL,
1804 sign_commit, extra)) {
1805 rollback_index_files();
1806 die(_("failed to write commit object"));
1808 strbuf_release(&author_ident);
1809 free_commit_extra_headers(extra);
1811 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1812 &err)) {
1813 rollback_index_files();
1814 die("%s", err.buf);
1817 sequencer_post_commit_cleanup(the_repository, 0);
1818 unlink(git_path_merge_head(the_repository));
1819 unlink(git_path_merge_msg(the_repository));
1820 unlink(git_path_merge_mode(the_repository));
1821 unlink(git_path_squash_msg(the_repository));
1823 if (commit_index_files())
1824 die(_("repository has been updated, but unable to write\n"
1825 "new_index file. Check that disk is not full and quota is\n"
1826 "not exceeded, and then \"git restore --staged :/\" to recover."));
1828 git_test_write_commit_graph_or_die();
1830 repo_rerere(the_repository, 0);
1831 run_auto_maintenance(quiet);
1832 run_commit_hook(use_editor, get_index_file(), "post-commit", NULL);
1833 if (amend && !no_post_rewrite) {
1834 commit_post_rewrite(the_repository, current_head, &oid);
1836 if (!quiet) {
1837 unsigned int flags = 0;
1839 if (!current_head)
1840 flags |= SUMMARY_INITIAL_COMMIT;
1841 if (author_date_is_interesting())
1842 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1843 print_commit_summary(the_repository, prefix,
1844 &oid, flags);
1847 apply_autostash(git_path_merge_autostash(the_repository));
1849 UNLEAK(err);
1850 UNLEAK(sb);
1851 return 0;