trace.c, git.c: remove unnecessary parameter to trace_repo_setup()
[git/debian.git] / builtin / commit.c
blob44b763d7cd025db45581d60902502ae2a2a9fe11
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 "hook.h"
23 #include "refs.h"
24 #include "log-tree.h"
25 #include "strbuf.h"
26 #include "utf8.h"
27 #include "parse-options.h"
28 #include "string-list.h"
29 #include "rerere.h"
30 #include "unpack-trees.h"
31 #include "quote.h"
32 #include "submodule.h"
33 #include "gpg-interface.h"
34 #include "column.h"
35 #include "sequencer.h"
36 #include "mailmap.h"
37 #include "help.h"
38 #include "commit-reach.h"
39 #include "commit-graph.h"
40 #include "pretty.h"
42 static const char * const builtin_commit_usage[] = {
43 N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]\n"
44 " [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>)]\n"
45 " [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
46 " [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
47 " [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
48 " [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
49 " [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
50 " [--] [<pathspec>...]"),
51 NULL
54 static const char * const builtin_status_usage[] = {
55 N_("git status [<options>] [--] [<pathspec>...]"),
56 NULL
59 static const char empty_amend_advice[] =
60 N_("You asked to amend the most recent commit, but doing so would make\n"
61 "it empty. You can repeat your command with --allow-empty, or you can\n"
62 "remove the commit entirely with \"git reset HEAD^\".\n");
64 static const char empty_cherry_pick_advice[] =
65 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
66 "If you wish to commit it anyway, use:\n"
67 "\n"
68 " git commit --allow-empty\n"
69 "\n");
71 static const char empty_rebase_pick_advice[] =
72 N_("Otherwise, please use 'git rebase --skip'\n");
74 static const char empty_cherry_pick_advice_single[] =
75 N_("Otherwise, please use 'git cherry-pick --skip'\n");
77 static const char empty_cherry_pick_advice_multi[] =
78 N_("and then use:\n"
79 "\n"
80 " git cherry-pick --continue\n"
81 "\n"
82 "to resume cherry-picking the remaining commits.\n"
83 "If you wish to skip this commit, use:\n"
84 "\n"
85 " git cherry-pick --skip\n"
86 "\n");
88 static const char *color_status_slots[] = {
89 [WT_STATUS_HEADER] = "header",
90 [WT_STATUS_UPDATED] = "updated",
91 [WT_STATUS_CHANGED] = "changed",
92 [WT_STATUS_UNTRACKED] = "untracked",
93 [WT_STATUS_NOBRANCH] = "noBranch",
94 [WT_STATUS_UNMERGED] = "unmerged",
95 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
96 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
97 [WT_STATUS_ONBRANCH] = "branch",
100 static const char *use_message_buffer;
101 static struct lock_file index_lock; /* real index */
102 static struct lock_file false_lock; /* used only for partial commits */
103 static enum {
104 COMMIT_AS_IS = 1,
105 COMMIT_NORMAL,
106 COMMIT_PARTIAL
107 } commit_style;
109 static const char *logfile, *force_author;
110 static const char *template_file;
112 * The _message variables are commit names from which to take
113 * the commit message and/or authorship.
115 static const char *author_message, *author_message_buffer;
116 static char *edit_message, *use_message;
117 static char *fixup_message, *fixup_commit, *squash_message;
118 static const char *fixup_prefix;
119 static int all, also, interactive, patch_interactive, only, amend, signoff;
120 static int edit_flag = -1; /* unspecified */
121 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
122 static int config_commit_verbose = -1; /* unspecified */
123 static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
124 static char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
125 static char *sign_commit, *pathspec_from_file;
126 static struct strvec trailer_args = STRVEC_INIT;
129 * The default commit message cleanup mode will remove the lines
130 * beginning with # (shell comments) and leading and trailing
131 * whitespaces (empty lines or containing only whitespaces)
132 * if editor is used, and only the whitespaces if the message
133 * is specified explicitly.
135 static enum commit_msg_cleanup_mode cleanup_mode;
136 static const char *cleanup_arg;
138 static enum commit_whence whence;
139 static int use_editor = 1, include_status = 1;
140 static int have_option_m;
141 static struct strbuf message = STRBUF_INIT;
143 static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
145 static int opt_pass_trailer(const struct option *opt, const char *arg, int unset)
147 BUG_ON_OPT_NEG(unset);
149 strvec_pushl(opt->value, "--trailer", arg, NULL);
150 return 0;
153 static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
155 enum wt_status_format *value = (enum wt_status_format *)opt->value;
156 if (unset)
157 *value = STATUS_FORMAT_NONE;
158 else if (!arg)
159 *value = STATUS_FORMAT_PORCELAIN;
160 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
161 *value = STATUS_FORMAT_PORCELAIN;
162 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
163 *value = STATUS_FORMAT_PORCELAIN_V2;
164 else
165 die("unsupported porcelain version '%s'", arg);
167 return 0;
170 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
172 struct strbuf *buf = opt->value;
173 if (unset) {
174 have_option_m = 0;
175 strbuf_setlen(buf, 0);
176 } else {
177 have_option_m = 1;
178 if (buf->len)
179 strbuf_addch(buf, '\n');
180 strbuf_addstr(buf, arg);
181 strbuf_complete_line(buf);
183 return 0;
186 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
188 const char **value = opt->value;
190 BUG_ON_OPT_NEG(unset);
192 if (arg != NULL && *arg == '=')
193 arg = arg + 1;
195 *value = arg;
196 return 0;
199 static void determine_whence(struct wt_status *s)
201 if (file_exists(git_path_merge_head(the_repository)))
202 whence = FROM_MERGE;
203 else if (!sequencer_determine_whence(the_repository, &whence))
204 whence = FROM_COMMIT;
205 if (s)
206 s->whence = whence;
209 static void status_init_config(struct wt_status *s, config_fn_t fn)
211 wt_status_prepare(the_repository, s);
212 init_diff_ui_defaults();
213 git_config(fn, s);
214 determine_whence(s);
215 s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after git_config() */
218 static void rollback_index_files(void)
220 switch (commit_style) {
221 case COMMIT_AS_IS:
222 break; /* nothing to do */
223 case COMMIT_NORMAL:
224 rollback_lock_file(&index_lock);
225 break;
226 case COMMIT_PARTIAL:
227 rollback_lock_file(&index_lock);
228 rollback_lock_file(&false_lock);
229 break;
233 static int commit_index_files(void)
235 int err = 0;
237 switch (commit_style) {
238 case COMMIT_AS_IS:
239 break; /* nothing to do */
240 case COMMIT_NORMAL:
241 err = commit_lock_file(&index_lock);
242 break;
243 case COMMIT_PARTIAL:
244 err = commit_lock_file(&index_lock);
245 rollback_lock_file(&false_lock);
246 break;
249 return err;
253 * Take a union of paths in the index and the named tree (typically, "HEAD"),
254 * and return the paths that match the given pattern in list.
256 static int list_paths(struct string_list *list, const char *with_tree,
257 const struct pathspec *pattern)
259 int i, ret;
260 char *m;
262 if (!pattern->nr)
263 return 0;
265 m = xcalloc(1, pattern->nr);
267 if (with_tree) {
268 char *max_prefix = common_prefix(pattern);
269 overlay_tree_on_index(&the_index, with_tree, max_prefix);
270 free(max_prefix);
273 /* TODO: audit for interaction with sparse-index. */
274 ensure_full_index(&the_index);
275 for (i = 0; i < the_index.cache_nr; i++) {
276 const struct cache_entry *ce = the_index.cache[i];
277 struct string_list_item *item;
279 if (ce->ce_flags & CE_UPDATE)
280 continue;
281 if (!ce_path_match(&the_index, ce, pattern, m))
282 continue;
283 item = string_list_insert(list, ce->name);
284 if (ce_skip_worktree(ce))
285 item->util = item; /* better a valid pointer than a fake one */
288 ret = report_path_error(m, pattern);
289 free(m);
290 return ret;
293 static void add_remove_files(struct string_list *list)
295 int i;
296 for (i = 0; i < list->nr; i++) {
297 struct stat st;
298 struct string_list_item *p = &(list->items[i]);
300 /* p->util is skip-worktree */
301 if (p->util)
302 continue;
304 if (!lstat(p->string, &st)) {
305 if (add_to_index(&the_index, p->string, &st, 0))
306 die(_("updating files failed"));
307 } else
308 remove_file_from_index(&the_index, p->string);
312 static void create_base_index(const struct commit *current_head)
314 struct tree *tree;
315 struct unpack_trees_options opts;
316 struct tree_desc t;
318 if (!current_head) {
319 discard_index(&the_index);
320 return;
323 memset(&opts, 0, sizeof(opts));
324 opts.head_idx = 1;
325 opts.index_only = 1;
326 opts.merge = 1;
327 opts.src_index = &the_index;
328 opts.dst_index = &the_index;
330 opts.fn = oneway_merge;
331 tree = parse_tree_indirect(&current_head->object.oid);
332 if (!tree)
333 die(_("failed to unpack HEAD tree object"));
334 parse_tree(tree);
335 init_tree_desc(&t, tree->buffer, tree->size);
336 if (unpack_trees(1, &t, &opts))
337 exit(128); /* We've already reported the error, finish dying */
340 static void refresh_cache_or_die(int refresh_flags)
343 * refresh_flags contains REFRESH_QUIET, so the only errors
344 * are for unmerged entries.
346 if (refresh_index(&the_index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
347 die_resolve_conflict("commit");
350 static const char *prepare_index(const char **argv, const char *prefix,
351 const struct commit *current_head, int is_status)
353 struct string_list partial = STRING_LIST_INIT_DUP;
354 struct pathspec pathspec;
355 int refresh_flags = REFRESH_QUIET;
356 const char *ret;
358 if (is_status)
359 refresh_flags |= REFRESH_UNMERGED;
360 parse_pathspec(&pathspec, 0,
361 PATHSPEC_PREFER_FULL,
362 prefix, argv);
364 if (pathspec_from_file) {
365 if (interactive)
366 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
368 if (all)
369 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
371 if (pathspec.nr)
372 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
374 parse_pathspec_file(&pathspec, 0,
375 PATHSPEC_PREFER_FULL,
376 prefix, pathspec_from_file, pathspec_file_nul);
377 } else if (pathspec_file_nul) {
378 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
381 if (!pathspec.nr && (also || (only && !allow_empty &&
382 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
383 die(_("No paths with --include/--only does not make sense."));
385 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
386 die(_("index file corrupt"));
388 if (interactive) {
389 char *old_index_env = NULL, *old_repo_index_file;
390 repo_hold_locked_index(the_repository, &index_lock,
391 LOCK_DIE_ON_ERROR);
393 refresh_cache_or_die(refresh_flags);
395 if (write_locked_index(&the_index, &index_lock, 0))
396 die(_("unable to create temporary index"));
398 old_repo_index_file = the_repository->index_file;
399 the_repository->index_file =
400 (char *)get_lock_file_path(&index_lock);
401 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
402 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
404 if (interactive_add(argv, prefix, patch_interactive) != 0)
405 die(_("interactive add failed"));
407 the_repository->index_file = old_repo_index_file;
408 if (old_index_env && *old_index_env)
409 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
410 else
411 unsetenv(INDEX_ENVIRONMENT);
412 FREE_AND_NULL(old_index_env);
414 discard_index(&the_index);
415 read_index_from(&the_index, get_lock_file_path(&index_lock),
416 get_git_dir());
417 if (update_main_cache_tree(WRITE_TREE_SILENT) == 0) {
418 if (reopen_lock_file(&index_lock) < 0)
419 die(_("unable to write index file"));
420 if (write_locked_index(&the_index, &index_lock, 0))
421 die(_("unable to update temporary index"));
422 } else
423 warning(_("Failed to update main cache tree"));
425 commit_style = COMMIT_NORMAL;
426 ret = get_lock_file_path(&index_lock);
427 goto out;
431 * Non partial, non as-is commit.
433 * (1) get the real index;
434 * (2) update the_index as necessary;
435 * (3) write the_index out to the real index (still locked);
436 * (4) return the name of the locked index file.
438 * The caller should run hooks on the locked real index, and
439 * (A) if all goes well, commit the real index;
440 * (B) on failure, rollback the real index.
442 if (all || (also && pathspec.nr)) {
443 repo_hold_locked_index(the_repository, &index_lock,
444 LOCK_DIE_ON_ERROR);
445 add_files_to_cache(also ? prefix : NULL, &pathspec, 0);
446 refresh_cache_or_die(refresh_flags);
447 update_main_cache_tree(WRITE_TREE_SILENT);
448 if (write_locked_index(&the_index, &index_lock, 0))
449 die(_("unable to write new_index file"));
450 commit_style = COMMIT_NORMAL;
451 ret = get_lock_file_path(&index_lock);
452 goto out;
456 * As-is commit.
458 * (1) return the name of the real index file.
460 * The caller should run hooks on the real index,
461 * and create commit from the_index.
462 * We still need to refresh the index here.
464 if (!only && !pathspec.nr) {
465 repo_hold_locked_index(the_repository, &index_lock,
466 LOCK_DIE_ON_ERROR);
467 refresh_cache_or_die(refresh_flags);
468 if (the_index.cache_changed
469 || !cache_tree_fully_valid(the_index.cache_tree))
470 update_main_cache_tree(WRITE_TREE_SILENT);
471 if (write_locked_index(&the_index, &index_lock,
472 COMMIT_LOCK | SKIP_IF_UNCHANGED))
473 die(_("unable to write new_index file"));
474 commit_style = COMMIT_AS_IS;
475 ret = get_index_file();
476 goto out;
480 * A partial commit.
482 * (0) find the set of affected paths;
483 * (1) get lock on the real index file;
484 * (2) update the_index with the given paths;
485 * (3) write the_index out to the real index (still locked);
486 * (4) get lock on the false index file;
487 * (5) reset the_index from HEAD;
488 * (6) update the_index the same way as (2);
489 * (7) write the_index out to the false index file;
490 * (8) return the name of the false index file (still locked);
492 * The caller should run hooks on the locked false index, and
493 * create commit from it. Then
494 * (A) if all goes well, commit the real index;
495 * (B) on failure, rollback the real index;
496 * In either case, rollback the false index.
498 commit_style = COMMIT_PARTIAL;
500 if (whence != FROM_COMMIT) {
501 if (whence == FROM_MERGE)
502 die(_("cannot do a partial commit during a merge."));
503 else if (is_from_cherry_pick(whence))
504 die(_("cannot do a partial commit during a cherry-pick."));
505 else if (is_from_rebase(whence))
506 die(_("cannot do a partial commit during a rebase."));
509 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
510 exit(1);
512 discard_index(&the_index);
513 if (repo_read_index(the_repository) < 0)
514 die(_("cannot read the index"));
516 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
517 add_remove_files(&partial);
518 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
519 update_main_cache_tree(WRITE_TREE_SILENT);
520 if (write_locked_index(&the_index, &index_lock, 0))
521 die(_("unable to write new_index file"));
523 hold_lock_file_for_update(&false_lock,
524 git_path("next-index-%"PRIuMAX,
525 (uintmax_t) getpid()),
526 LOCK_DIE_ON_ERROR);
528 create_base_index(current_head);
529 add_remove_files(&partial);
530 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
532 if (write_locked_index(&the_index, &false_lock, 0))
533 die(_("unable to write temporary index file"));
535 discard_index(&the_index);
536 ret = get_lock_file_path(&false_lock);
537 read_index_from(&the_index, ret, get_git_dir());
538 out:
539 string_list_clear(&partial, 0);
540 clear_pathspec(&pathspec);
541 return ret;
544 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
545 struct wt_status *s)
547 struct object_id oid;
549 if (s->relative_paths)
550 s->prefix = prefix;
552 if (amend) {
553 s->amend = 1;
554 s->reference = "HEAD^1";
556 s->verbose = verbose;
557 s->index_file = index_file;
558 s->fp = fp;
559 s->nowarn = nowarn;
560 s->is_initial = get_oid(s->reference, &oid) ? 1 : 0;
561 if (!s->is_initial)
562 oidcpy(&s->oid_commit, &oid);
563 s->status_format = status_format;
564 s->ignore_submodule_arg = ignore_submodule_arg;
566 wt_status_collect(s);
567 wt_status_print(s);
568 wt_status_collect_free_buffers(s);
570 return s->committable;
573 static int is_a_merge(const struct commit *current_head)
575 return !!(current_head->parents && current_head->parents->next);
578 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
580 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
581 BUG("unable to parse our own ident: %s", buf->buf);
584 static void export_one(const char *var, const char *s, const char *e, int hack)
586 struct strbuf buf = STRBUF_INIT;
587 if (hack)
588 strbuf_addch(&buf, hack);
589 strbuf_add(&buf, s, e - s);
590 setenv(var, buf.buf, 1);
591 strbuf_release(&buf);
594 static int parse_force_date(const char *in, struct strbuf *out)
596 strbuf_addch(out, '@');
598 if (parse_date(in, out) < 0) {
599 int errors = 0;
600 unsigned long t = approxidate_careful(in, &errors);
601 if (errors)
602 return -1;
603 strbuf_addf(out, "%lu", t);
606 return 0;
609 static void set_ident_var(char **buf, char *val)
611 free(*buf);
612 *buf = val;
615 static void determine_author_info(struct strbuf *author_ident)
617 char *name, *email, *date;
618 struct ident_split author;
620 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
621 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
622 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
624 if (author_message) {
625 struct ident_split ident;
626 size_t len;
627 const char *a;
629 a = find_commit_header(author_message_buffer, "author", &len);
630 if (!a)
631 die(_("commit '%s' lacks author header"), author_message);
632 if (split_ident_line(&ident, a, len) < 0)
633 die(_("commit '%s' has malformed author line"), author_message);
635 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
636 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
638 if (ident.date_begin) {
639 struct strbuf date_buf = STRBUF_INIT;
640 strbuf_addch(&date_buf, '@');
641 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
642 strbuf_addch(&date_buf, ' ');
643 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
644 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
648 if (force_author) {
649 struct ident_split ident;
651 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
652 die(_("malformed --author parameter"));
653 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
654 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
657 if (force_date) {
658 struct strbuf date_buf = STRBUF_INIT;
659 if (parse_force_date(force_date, &date_buf))
660 die(_("invalid date format: %s"), force_date);
661 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
664 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
665 IDENT_STRICT));
666 assert_split_ident(&author, author_ident);
667 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
668 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
669 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
670 free(name);
671 free(email);
672 free(date);
675 static int author_date_is_interesting(void)
677 return author_message || force_date;
680 static void adjust_comment_line_char(const struct strbuf *sb)
682 char candidates[] = "#;@!$%^&|:";
683 char *candidate;
684 const char *p;
686 comment_line_char = candidates[0];
687 if (!memchr(sb->buf, comment_line_char, sb->len))
688 return;
690 p = sb->buf;
691 candidate = strchr(candidates, *p);
692 if (candidate)
693 *candidate = ' ';
694 for (p = sb->buf; *p; p++) {
695 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
696 candidate = strchr(candidates, p[1]);
697 if (candidate)
698 *candidate = ' ';
702 for (p = candidates; *p == ' '; p++)
704 if (!*p)
705 die(_("unable to select a comment character that is not used\n"
706 "in the current commit message"));
707 comment_line_char = *p;
710 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
711 struct pretty_print_context *ctx)
713 const char *buffer, *subject, *fmt;
715 buffer = get_commit_buffer(commit, NULL);
716 find_commit_subject(buffer, &subject);
718 * If we amend the 'amend!' commit then we don't want to
719 * duplicate the subject line.
721 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
722 format_commit_message(commit, fmt, sb, ctx);
723 unuse_commit_buffer(commit, buffer);
726 static int prepare_to_commit(const char *index_file, const char *prefix,
727 struct commit *current_head,
728 struct wt_status *s,
729 struct strbuf *author_ident)
731 struct stat statbuf;
732 struct strbuf committer_ident = STRBUF_INIT;
733 int committable;
734 struct strbuf sb = STRBUF_INIT;
735 const char *hook_arg1 = NULL;
736 const char *hook_arg2 = NULL;
737 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
738 int old_display_comment_prefix;
739 int merge_contains_scissors = 0;
740 int invoked_hook;
742 /* This checks and barfs if author is badly specified */
743 determine_author_info(author_ident);
745 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
746 "pre-commit", NULL))
747 return 0;
749 if (squash_message) {
751 * Insert the proper subject line before other commit
752 * message options add their content.
754 if (use_message && !strcmp(use_message, squash_message))
755 strbuf_addstr(&sb, "squash! ");
756 else {
757 struct pretty_print_context ctx = {0};
758 struct commit *c;
759 c = lookup_commit_reference_by_name(squash_message);
760 if (!c)
761 die(_("could not lookup commit %s"), squash_message);
762 ctx.output_encoding = get_commit_output_encoding();
763 format_commit_message(c, "squash! %s\n\n", &sb,
764 &ctx);
768 if (have_option_m && !fixup_message) {
769 strbuf_addbuf(&sb, &message);
770 hook_arg1 = "message";
771 } else if (logfile && !strcmp(logfile, "-")) {
772 if (isatty(0))
773 fprintf(stderr, _("(reading log message from standard input)\n"));
774 if (strbuf_read(&sb, 0, 0) < 0)
775 die_errno(_("could not read log from standard input"));
776 hook_arg1 = "message";
777 } else if (logfile) {
778 if (strbuf_read_file(&sb, logfile, 0) < 0)
779 die_errno(_("could not read log file '%s'"),
780 logfile);
781 hook_arg1 = "message";
782 } else if (use_message) {
783 char *buffer;
784 buffer = strstr(use_message_buffer, "\n\n");
785 if (buffer)
786 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
787 hook_arg1 = "commit";
788 hook_arg2 = use_message;
789 } else if (fixup_message) {
790 struct pretty_print_context ctx = {0};
791 struct commit *commit;
792 char *fmt;
793 commit = lookup_commit_reference_by_name(fixup_commit);
794 if (!commit)
795 die(_("could not lookup commit %s"), fixup_commit);
796 ctx.output_encoding = get_commit_output_encoding();
797 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
798 format_commit_message(commit, fmt, &sb, &ctx);
799 free(fmt);
800 hook_arg1 = "message";
803 * Only `-m` commit message option is checked here, as
804 * it supports `--fixup` to append the commit message.
806 * The other commit message options `-c`/`-C`/`-F` are
807 * incompatible with all the forms of `--fixup` and
808 * have already errored out while parsing the `git commit`
809 * options.
811 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
812 strbuf_addbuf(&sb, &message);
814 if (!strcmp(fixup_prefix, "amend")) {
815 if (have_option_m)
816 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
817 prepare_amend_commit(commit, &sb, &ctx);
819 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
820 size_t merge_msg_start;
823 * prepend SQUASH_MSG here if it exists and a
824 * "merge --squash" was originally performed
826 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
827 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
828 die_errno(_("could not read SQUASH_MSG"));
829 hook_arg1 = "squash";
830 } else
831 hook_arg1 = "merge";
833 merge_msg_start = sb.len;
834 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
835 die_errno(_("could not read MERGE_MSG"));
837 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
838 wt_status_locate_end(sb.buf + merge_msg_start,
839 sb.len - merge_msg_start) <
840 sb.len - merge_msg_start)
841 merge_contains_scissors = 1;
842 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
843 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
844 die_errno(_("could not read SQUASH_MSG"));
845 hook_arg1 = "squash";
846 } else if (template_file) {
847 if (strbuf_read_file(&sb, template_file, 0) < 0)
848 die_errno(_("could not read '%s'"), template_file);
849 hook_arg1 = "template";
850 clean_message_contents = 0;
854 * The remaining cases don't modify the template message, but
855 * just set the argument(s) to the prepare-commit-msg hook.
857 else if (whence == FROM_MERGE)
858 hook_arg1 = "merge";
859 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
860 hook_arg1 = "commit";
861 hook_arg2 = "CHERRY_PICK_HEAD";
864 if (squash_message) {
866 * If squash_commit was used for the commit subject,
867 * then we're possibly hijacking other commit log options.
868 * Reset the hook args to tell the real story.
870 hook_arg1 = "message";
871 hook_arg2 = "";
874 s->fp = fopen_for_writing(git_path_commit_editmsg());
875 if (!s->fp)
876 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
878 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
879 old_display_comment_prefix = s->display_comment_prefix;
880 s->display_comment_prefix = 1;
883 * Most hints are counter-productive when the commit has
884 * already started.
886 s->hints = 0;
888 if (clean_message_contents)
889 strbuf_stripspace(&sb, 0);
891 if (signoff)
892 append_signoff(&sb, ignore_non_trailer(sb.buf, sb.len), 0);
894 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
895 die_errno(_("could not write commit template"));
897 if (auto_comment_line_char)
898 adjust_comment_line_char(&sb);
899 strbuf_release(&sb);
901 /* This checks if committer ident is explicitly given */
902 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
903 if (use_editor && include_status) {
904 int ident_shown = 0;
905 int saved_color_setting;
906 struct ident_split ci, ai;
907 const char *hint_cleanup_all = allow_empty_message ?
908 _("Please enter the commit message for your changes."
909 " Lines starting\nwith '%c' will be ignored.\n") :
910 _("Please enter the commit message for your changes."
911 " Lines starting\nwith '%c' will be ignored, and an empty"
912 " message aborts the commit.\n");
913 const char *hint_cleanup_space = allow_empty_message ?
914 _("Please enter the commit message for your changes."
915 " Lines starting\n"
916 "with '%c' will be kept; you may remove them"
917 " yourself if you want to.\n") :
918 _("Please enter the commit message for your changes."
919 " Lines starting\n"
920 "with '%c' will be kept; you may remove them"
921 " yourself if you want to.\n"
922 "An empty message aborts the commit.\n");
923 if (whence != FROM_COMMIT) {
924 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
925 !merge_contains_scissors)
926 wt_status_add_cut_line(s->fp);
927 status_printf_ln(
928 s, GIT_COLOR_NORMAL,
929 whence == FROM_MERGE ?
930 _("\n"
931 "It looks like you may be committing a merge.\n"
932 "If this is not correct, please run\n"
933 " git update-ref -d MERGE_HEAD\n"
934 "and try again.\n") :
935 _("\n"
936 "It looks like you may be committing a cherry-pick.\n"
937 "If this is not correct, please run\n"
938 " git update-ref -d CHERRY_PICK_HEAD\n"
939 "and try again.\n"));
942 fprintf(s->fp, "\n");
943 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
944 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_char);
945 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
946 if (whence == FROM_COMMIT && !merge_contains_scissors)
947 wt_status_add_cut_line(s->fp);
948 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
949 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_char);
952 * These should never fail because they come from our own
953 * fmt_ident. They may fail the sane_ident test, but we know
954 * that the name and mail pointers will at least be valid,
955 * which is enough for our tests and printing here.
957 assert_split_ident(&ai, author_ident);
958 assert_split_ident(&ci, &committer_ident);
960 if (ident_cmp(&ai, &ci))
961 status_printf_ln(s, GIT_COLOR_NORMAL,
962 _("%s"
963 "Author: %.*s <%.*s>"),
964 ident_shown++ ? "" : "\n",
965 (int)(ai.name_end - ai.name_begin), ai.name_begin,
966 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
968 if (author_date_is_interesting())
969 status_printf_ln(s, GIT_COLOR_NORMAL,
970 _("%s"
971 "Date: %s"),
972 ident_shown++ ? "" : "\n",
973 show_ident_date(&ai, DATE_MODE(NORMAL)));
975 if (!committer_ident_sufficiently_given())
976 status_printf_ln(s, GIT_COLOR_NORMAL,
977 _("%s"
978 "Committer: %.*s <%.*s>"),
979 ident_shown++ ? "" : "\n",
980 (int)(ci.name_end - ci.name_begin), ci.name_begin,
981 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
983 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
985 saved_color_setting = s->use_color;
986 s->use_color = 0;
987 committable = run_status(s->fp, index_file, prefix, 1, s);
988 s->use_color = saved_color_setting;
989 string_list_clear(&s->change, 1);
990 } else {
991 struct object_id oid;
992 const char *parent = "HEAD";
994 if (!active_nr) {
995 discard_cache();
996 if (read_cache() < 0)
997 die(_("Cannot read index"));
1000 if (amend)
1001 parent = "HEAD^1";
1003 if (get_oid(parent, &oid)) {
1004 int i, ita_nr = 0;
1006 /* TODO: audit for interaction with sparse-index. */
1007 ensure_full_index(&the_index);
1008 for (i = 0; i < the_index.cache_nr; i++)
1009 if (ce_intent_to_add(the_index.cache[i]))
1010 ita_nr++;
1011 committable = the_index.cache_nr - ita_nr > 0;
1012 } else {
1014 * Unless the user did explicitly request a submodule
1015 * ignore mode by passing a command line option we do
1016 * not ignore any changed submodule SHA-1s when
1017 * comparing index and parent, no matter what is
1018 * configured. Otherwise we won't commit any
1019 * submodules which were manually staged, which would
1020 * be really confusing.
1022 struct diff_flags flags = DIFF_FLAGS_INIT;
1023 flags.override_submodule_config = 1;
1024 if (ignore_submodule_arg &&
1025 !strcmp(ignore_submodule_arg, "all"))
1026 flags.ignore_submodules = 1;
1027 committable = index_differs_from(the_repository,
1028 parent, &flags, 1);
1031 strbuf_release(&committer_ident);
1033 fclose(s->fp);
1035 if (trailer_args.nr) {
1036 struct child_process run_trailer = CHILD_PROCESS_INIT;
1038 strvec_pushl(&run_trailer.args, "interpret-trailers",
1039 "--in-place", git_path_commit_editmsg(), NULL);
1040 strvec_pushv(&run_trailer.args, trailer_args.v);
1041 run_trailer.git_cmd = 1;
1042 if (run_command(&run_trailer))
1043 die(_("unable to pass trailers to --trailers"));
1044 strvec_clear(&trailer_args);
1048 * Reject an attempt to record a non-merge empty commit without
1049 * explicit --allow-empty. In the cherry-pick case, it may be
1050 * empty due to conflict resolution, which the user should okay.
1052 if (!committable && whence != FROM_MERGE && !allow_empty &&
1053 !(amend && is_a_merge(current_head))) {
1054 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1055 s->display_comment_prefix = old_display_comment_prefix;
1056 run_status(stdout, index_file, prefix, 0, s);
1057 if (amend)
1058 fputs(_(empty_amend_advice), stderr);
1059 else if (is_from_cherry_pick(whence) ||
1060 whence == FROM_REBASE_PICK) {
1061 fputs(_(empty_cherry_pick_advice), stderr);
1062 if (whence == FROM_CHERRY_PICK_SINGLE)
1063 fputs(_(empty_cherry_pick_advice_single), stderr);
1064 else if (whence == FROM_CHERRY_PICK_MULTI)
1065 fputs(_(empty_cherry_pick_advice_multi), stderr);
1066 else
1067 fputs(_(empty_rebase_pick_advice), stderr);
1069 return 0;
1072 if (!no_verify && invoked_hook) {
1074 * Re-read the index as the pre-commit-commit hook was invoked
1075 * and could have updated it. We must do this before we invoke
1076 * the editor and after we invoke run_status above.
1078 discard_index(&the_index);
1080 read_index_from(&the_index, index_file, get_git_dir());
1082 if (update_main_cache_tree(0)) {
1083 error(_("Error building trees"));
1084 return 0;
1087 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1088 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1089 return 0;
1091 if (use_editor) {
1092 struct strvec env = STRVEC_INIT;
1094 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1095 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1096 fprintf(stderr,
1097 _("Please supply the message using either -m or -F option.\n"));
1098 exit(1);
1100 strvec_clear(&env);
1103 if (!no_verify &&
1104 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1105 git_path_commit_editmsg(), NULL)) {
1106 return 0;
1109 return 1;
1112 static const char *find_author_by_nickname(const char *name)
1114 struct rev_info revs;
1115 struct commit *commit;
1116 struct strbuf buf = STRBUF_INIT;
1117 const char *av[20];
1118 int ac = 0;
1120 repo_init_revisions(the_repository, &revs, NULL);
1121 strbuf_addf(&buf, "--author=%s", name);
1122 av[++ac] = "--all";
1123 av[++ac] = "-i";
1124 av[++ac] = buf.buf;
1125 av[++ac] = NULL;
1126 setup_revisions(ac, av, &revs, NULL);
1127 revs.mailmap = xmalloc(sizeof(struct string_list));
1128 string_list_init_nodup(revs.mailmap);
1129 read_mailmap(revs.mailmap);
1131 if (prepare_revision_walk(&revs))
1132 die(_("revision walk setup failed"));
1133 commit = get_revision(&revs);
1134 if (commit) {
1135 struct pretty_print_context ctx = {0};
1136 ctx.date_mode.type = DATE_NORMAL;
1137 strbuf_release(&buf);
1138 format_commit_message(commit, "%aN <%aE>", &buf, &ctx);
1139 release_revisions(&revs);
1140 return strbuf_detach(&buf, NULL);
1142 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1145 static void handle_ignored_arg(struct wt_status *s)
1147 if (!ignored_arg)
1148 ; /* default already initialized */
1149 else if (!strcmp(ignored_arg, "traditional"))
1150 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1151 else if (!strcmp(ignored_arg, "no"))
1152 s->show_ignored_mode = SHOW_NO_IGNORED;
1153 else if (!strcmp(ignored_arg, "matching"))
1154 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1155 else
1156 die(_("Invalid ignored mode '%s'"), ignored_arg);
1159 static void handle_untracked_files_arg(struct wt_status *s)
1161 if (!untracked_files_arg)
1162 ; /* default already initialized */
1163 else if (!strcmp(untracked_files_arg, "no"))
1164 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1165 else if (!strcmp(untracked_files_arg, "normal"))
1166 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1167 else if (!strcmp(untracked_files_arg, "all"))
1168 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1170 * Please update $__git_untracked_file_modes in
1171 * git-completion.bash when you add new options
1173 else
1174 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1177 static const char *read_commit_message(const char *name)
1179 const char *out_enc;
1180 struct commit *commit;
1182 commit = lookup_commit_reference_by_name(name);
1183 if (!commit)
1184 die(_("could not lookup commit %s"), name);
1185 out_enc = get_commit_output_encoding();
1186 return logmsg_reencode(commit, NULL, out_enc);
1190 * Enumerate what needs to be propagated when --porcelain
1191 * is not in effect here.
1193 static struct status_deferred_config {
1194 enum wt_status_format status_format;
1195 int show_branch;
1196 enum ahead_behind_flags ahead_behind;
1197 } status_deferred_config = {
1198 STATUS_FORMAT_UNSPECIFIED,
1199 -1, /* unspecified */
1200 AHEAD_BEHIND_UNSPECIFIED,
1203 static void finalize_deferred_config(struct wt_status *s)
1205 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1206 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1207 !s->null_termination);
1209 if (s->null_termination) {
1210 if (status_format == STATUS_FORMAT_NONE ||
1211 status_format == STATUS_FORMAT_UNSPECIFIED)
1212 status_format = STATUS_FORMAT_PORCELAIN;
1213 else if (status_format == STATUS_FORMAT_LONG)
1214 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1217 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1218 status_format = status_deferred_config.status_format;
1219 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1220 status_format = STATUS_FORMAT_NONE;
1222 if (use_deferred_config && s->show_branch < 0)
1223 s->show_branch = status_deferred_config.show_branch;
1224 if (s->show_branch < 0)
1225 s->show_branch = 0;
1228 * If the user did not give a "--[no]-ahead-behind" command
1229 * line argument *AND* we will print in a human-readable format
1230 * (short, long etc.) then we inherit from the status.aheadbehind
1231 * config setting. In all other cases (and porcelain V[12] formats
1232 * in particular), we inherit _FULL for backwards compatibility.
1234 if (use_deferred_config &&
1235 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1236 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1238 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1239 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1242 static void check_fixup_reword_options(int argc, const char *argv[]) {
1243 if (whence != FROM_COMMIT) {
1244 if (whence == FROM_MERGE)
1245 die(_("You are in the middle of a merge -- cannot reword."));
1246 else if (is_from_cherry_pick(whence))
1247 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1249 if (argc)
1250 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1251 if (patch_interactive || interactive || all || also || only)
1252 die(_("reword option of '%s' and '%s' cannot be used together"),
1253 "--fixup", "--patch/--interactive/--all/--include/--only");
1256 static int parse_and_validate_options(int argc, const char *argv[],
1257 const struct option *options,
1258 const char * const usage[],
1259 const char *prefix,
1260 struct commit *current_head,
1261 struct wt_status *s)
1263 argc = parse_options(argc, argv, prefix, options, usage, 0);
1264 finalize_deferred_config(s);
1266 if (force_author && !strchr(force_author, '>'))
1267 force_author = find_author_by_nickname(force_author);
1269 if (force_author && renew_authorship)
1270 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1272 if (logfile || have_option_m || use_message)
1273 use_editor = 0;
1275 /* Sanity check options */
1276 if (amend && !current_head)
1277 die(_("You have nothing to amend."));
1278 if (amend && whence != FROM_COMMIT) {
1279 if (whence == FROM_MERGE)
1280 die(_("You are in the middle of a merge -- cannot amend."));
1281 else if (is_from_cherry_pick(whence))
1282 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1283 else if (whence == FROM_REBASE_PICK)
1284 die(_("You are in the middle of a rebase -- cannot amend."));
1286 if (fixup_message && squash_message)
1287 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1288 die_for_incompatible_opt4(!!use_message, "-C",
1289 !!edit_message, "-c",
1290 !!logfile, "-F",
1291 !!fixup_message, "--fixup");
1292 die_for_incompatible_opt4(have_option_m, "-m",
1293 !!edit_message, "-c",
1294 !!use_message, "-C",
1295 !!logfile, "-F");
1296 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1297 template_file = NULL;
1298 if (edit_message)
1299 use_message = edit_message;
1300 if (amend && !use_message && !fixup_message)
1301 use_message = "HEAD";
1302 if (!use_message && !is_from_cherry_pick(whence) &&
1303 !is_from_rebase(whence) && renew_authorship)
1304 die(_("--reset-author can be used only with -C, -c or --amend."));
1305 if (use_message) {
1306 use_message_buffer = read_commit_message(use_message);
1307 if (!renew_authorship) {
1308 author_message = use_message;
1309 author_message_buffer = use_message_buffer;
1312 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1313 !renew_authorship) {
1314 author_message = "CHERRY_PICK_HEAD";
1315 author_message_buffer = read_commit_message(author_message);
1318 if (patch_interactive)
1319 interactive = 1;
1321 die_for_incompatible_opt4(also, "-i/--include",
1322 only, "-o/--only",
1323 all, "-a/--all",
1324 interactive, "--interactive/-p/--patch");
1325 if (fixup_message) {
1327 * We limit --fixup's suboptions to only alpha characters.
1328 * If the first character after a run of alpha is colon,
1329 * then the part before the colon may be a known suboption
1330 * name like `amend` or `reword`, or a misspelt suboption
1331 * name. In either case, we treat it as
1332 * --fixup=<suboption>:<arg>.
1334 * Otherwise, we are dealing with --fixup=<commit>.
1336 char *p = fixup_message;
1337 while (isalpha(*p))
1338 p++;
1339 if (p > fixup_message && *p == ':') {
1340 *p = '\0';
1341 fixup_commit = p + 1;
1342 if (!strcmp("amend", fixup_message) ||
1343 !strcmp("reword", fixup_message)) {
1344 fixup_prefix = "amend";
1345 allow_empty = 1;
1346 if (*fixup_message == 'r') {
1347 check_fixup_reword_options(argc, argv);
1348 only = 1;
1350 } else {
1351 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1353 } else {
1354 fixup_commit = fixup_message;
1355 fixup_prefix = "fixup";
1356 use_editor = 0;
1360 if (0 <= edit_flag)
1361 use_editor = edit_flag;
1363 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1365 handle_untracked_files_arg(s);
1367 if (all && argc > 0)
1368 die(_("paths '%s ...' with -a does not make sense"),
1369 argv[0]);
1371 if (status_format != STATUS_FORMAT_NONE)
1372 dry_run = 1;
1374 return argc;
1377 static int dry_run_commit(const char **argv, const char *prefix,
1378 const struct commit *current_head, struct wt_status *s)
1380 int committable;
1381 const char *index_file;
1383 index_file = prepare_index(argv, prefix, current_head, 1);
1384 committable = run_status(stdout, index_file, prefix, 0, s);
1385 rollback_index_files();
1387 return committable ? 0 : 1;
1390 define_list_config_array_extra(color_status_slots, {"added"});
1392 static int parse_status_slot(const char *slot)
1394 if (!strcasecmp(slot, "added"))
1395 return WT_STATUS_UPDATED;
1397 return LOOKUP_CONFIG(color_status_slots, slot);
1400 static int git_status_config(const char *k, const char *v, void *cb)
1402 struct wt_status *s = cb;
1403 const char *slot_name;
1405 if (starts_with(k, "column."))
1406 return git_column_config(k, v, "status", &s->colopts);
1407 if (!strcmp(k, "status.submodulesummary")) {
1408 int is_bool;
1409 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1410 if (is_bool && s->submodule_summary)
1411 s->submodule_summary = -1;
1412 return 0;
1414 if (!strcmp(k, "status.short")) {
1415 if (git_config_bool(k, v))
1416 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1417 else
1418 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1419 return 0;
1421 if (!strcmp(k, "status.branch")) {
1422 status_deferred_config.show_branch = git_config_bool(k, v);
1423 return 0;
1425 if (!strcmp(k, "status.aheadbehind")) {
1426 status_deferred_config.ahead_behind = git_config_bool(k, v);
1427 return 0;
1429 if (!strcmp(k, "status.showstash")) {
1430 s->show_stash = git_config_bool(k, v);
1431 return 0;
1433 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1434 s->use_color = git_config_colorbool(k, v);
1435 return 0;
1437 if (!strcmp(k, "status.displaycommentprefix")) {
1438 s->display_comment_prefix = git_config_bool(k, v);
1439 return 0;
1441 if (skip_prefix(k, "status.color.", &slot_name) ||
1442 skip_prefix(k, "color.status.", &slot_name)) {
1443 int slot = parse_status_slot(slot_name);
1444 if (slot < 0)
1445 return 0;
1446 if (!v)
1447 return config_error_nonbool(k);
1448 return color_parse(v, s->color_palette[slot]);
1450 if (!strcmp(k, "status.relativepaths")) {
1451 s->relative_paths = git_config_bool(k, v);
1452 return 0;
1454 if (!strcmp(k, "status.showuntrackedfiles")) {
1455 if (!v)
1456 return config_error_nonbool(k);
1457 else if (!strcmp(v, "no"))
1458 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1459 else if (!strcmp(v, "normal"))
1460 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1461 else if (!strcmp(v, "all"))
1462 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1463 else
1464 return error(_("Invalid untracked files mode '%s'"), v);
1465 return 0;
1467 if (!strcmp(k, "diff.renamelimit")) {
1468 if (s->rename_limit == -1)
1469 s->rename_limit = git_config_int(k, v);
1470 return 0;
1472 if (!strcmp(k, "status.renamelimit")) {
1473 s->rename_limit = git_config_int(k, v);
1474 return 0;
1476 if (!strcmp(k, "diff.renames")) {
1477 if (s->detect_rename == -1)
1478 s->detect_rename = git_config_rename(k, v);
1479 return 0;
1481 if (!strcmp(k, "status.renames")) {
1482 s->detect_rename = git_config_rename(k, v);
1483 return 0;
1485 return git_diff_ui_config(k, v, NULL);
1488 int cmd_status(int argc, const char **argv, const char *prefix)
1490 static int no_renames = -1;
1491 static const char *rename_score_arg = (const char *)-1;
1492 static struct wt_status s;
1493 unsigned int progress_flag = 0;
1494 int fd;
1495 struct object_id oid;
1496 static struct option builtin_status_options[] = {
1497 OPT__VERBOSE(&verbose, N_("be verbose")),
1498 OPT_SET_INT('s', "short", &status_format,
1499 N_("show status concisely"), STATUS_FORMAT_SHORT),
1500 OPT_BOOL('b', "branch", &s.show_branch,
1501 N_("show branch information")),
1502 OPT_BOOL(0, "show-stash", &s.show_stash,
1503 N_("show stash information")),
1504 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1505 N_("compute full ahead/behind values")),
1506 OPT_CALLBACK_F(0, "porcelain", &status_format,
1507 N_("version"), N_("machine-readable output"),
1508 PARSE_OPT_OPTARG, opt_parse_porcelain),
1509 OPT_SET_INT(0, "long", &status_format,
1510 N_("show status in long format (default)"),
1511 STATUS_FORMAT_LONG),
1512 OPT_BOOL('z', "null", &s.null_termination,
1513 N_("terminate entries with NUL")),
1514 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1515 N_("mode"),
1516 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1517 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1518 { OPTION_STRING, 0, "ignored", &ignored_arg,
1519 N_("mode"),
1520 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1521 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1522 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1523 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1524 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1525 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1526 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1527 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1528 N_("n"), N_("detect renames, optionally set similarity index"),
1529 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1530 OPT_END(),
1533 if (argc == 2 && !strcmp(argv[1], "-h"))
1534 usage_with_options(builtin_status_usage, builtin_status_options);
1536 prepare_repo_settings(the_repository);
1537 the_repository->settings.command_requires_full_index = 0;
1539 status_init_config(&s, git_status_config);
1540 argc = parse_options(argc, argv, prefix,
1541 builtin_status_options,
1542 builtin_status_usage, 0);
1543 finalize_colopts(&s.colopts, -1);
1544 finalize_deferred_config(&s);
1546 handle_untracked_files_arg(&s);
1547 handle_ignored_arg(&s);
1549 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1550 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1551 die(_("Unsupported combination of ignored and untracked-files arguments"));
1553 parse_pathspec(&s.pathspec, 0,
1554 PATHSPEC_PREFER_FULL,
1555 prefix, argv);
1557 if (status_format != STATUS_FORMAT_PORCELAIN &&
1558 status_format != STATUS_FORMAT_PORCELAIN_V2)
1559 progress_flag = REFRESH_PROGRESS;
1560 repo_read_index(the_repository);
1561 refresh_index(&the_index,
1562 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1563 &s.pathspec, NULL, NULL);
1565 if (use_optional_locks())
1566 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1567 else
1568 fd = -1;
1570 s.is_initial = get_oid(s.reference, &oid) ? 1 : 0;
1571 if (!s.is_initial)
1572 oidcpy(&s.oid_commit, &oid);
1574 s.ignore_submodule_arg = ignore_submodule_arg;
1575 s.status_format = status_format;
1576 s.verbose = verbose;
1577 if (no_renames != -1)
1578 s.detect_rename = !no_renames;
1579 if ((intptr_t)rename_score_arg != -1) {
1580 if (s.detect_rename < DIFF_DETECT_RENAME)
1581 s.detect_rename = DIFF_DETECT_RENAME;
1582 if (rename_score_arg)
1583 s.rename_score = parse_rename_score(&rename_score_arg);
1586 wt_status_collect(&s);
1588 if (0 <= fd)
1589 repo_update_index_if_able(the_repository, &index_lock);
1591 if (s.relative_paths)
1592 s.prefix = prefix;
1594 wt_status_print(&s);
1595 wt_status_collect_free_buffers(&s);
1597 return 0;
1600 static int git_commit_config(const char *k, const char *v, void *cb)
1602 struct wt_status *s = cb;
1603 int status;
1605 if (!strcmp(k, "commit.template"))
1606 return git_config_pathname(&template_file, k, v);
1607 if (!strcmp(k, "commit.status")) {
1608 include_status = git_config_bool(k, v);
1609 return 0;
1611 if (!strcmp(k, "commit.cleanup"))
1612 return git_config_string(&cleanup_arg, k, v);
1613 if (!strcmp(k, "commit.gpgsign")) {
1614 sign_commit = git_config_bool(k, v) ? "" : NULL;
1615 return 0;
1617 if (!strcmp(k, "commit.verbose")) {
1618 int is_bool;
1619 config_commit_verbose = git_config_bool_or_int(k, v, &is_bool);
1620 return 0;
1623 status = git_gpg_config(k, v, NULL);
1624 if (status)
1625 return status;
1626 return git_status_config(k, v, s);
1629 int cmd_commit(int argc, const char **argv, const char *prefix)
1631 static struct wt_status s;
1632 static struct option builtin_commit_options[] = {
1633 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1634 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1636 OPT_GROUP(N_("Commit message options")),
1637 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1638 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1639 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1640 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1641 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1642 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1644 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1645 * and only translate <commit>.
1647 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1648 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1649 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1650 OPT_CALLBACK_F(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG, opt_pass_trailer),
1651 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1652 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1653 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1654 OPT_CLEANUP(&cleanup_arg),
1655 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1656 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1657 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1658 /* end commit message options */
1660 OPT_GROUP(N_("Commit contents options")),
1661 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1662 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1663 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1664 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1665 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1666 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1667 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1668 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1669 STATUS_FORMAT_SHORT),
1670 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1671 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1672 N_("compute full ahead/behind values")),
1673 OPT_SET_INT(0, "porcelain", &status_format,
1674 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1675 OPT_SET_INT(0, "long", &status_format,
1676 N_("show status in long format (default)"),
1677 STATUS_FORMAT_LONG),
1678 OPT_BOOL('z', "null", &s.null_termination,
1679 N_("terminate entries with NUL")),
1680 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1681 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1682 { 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" },
1683 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1684 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1685 /* end commit contents options */
1687 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1688 N_("ok to record an empty change")),
1689 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1690 N_("ok to record a change with an empty message")),
1692 OPT_END()
1695 struct strbuf sb = STRBUF_INIT;
1696 struct strbuf author_ident = STRBUF_INIT;
1697 const char *index_file, *reflog_msg;
1698 struct object_id oid;
1699 struct commit_list *parents = NULL;
1700 struct stat statbuf;
1701 struct commit *current_head = NULL;
1702 struct commit_extra_header *extra = NULL;
1703 struct strbuf err = STRBUF_INIT;
1704 int ret = 0;
1706 if (argc == 2 && !strcmp(argv[1], "-h"))
1707 usage_with_options(builtin_commit_usage, builtin_commit_options);
1709 prepare_repo_settings(the_repository);
1710 the_repository->settings.command_requires_full_index = 0;
1712 status_init_config(&s, git_commit_config);
1713 s.commit_template = 1;
1714 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1715 s.colopts = 0;
1717 if (get_oid("HEAD", &oid))
1718 current_head = NULL;
1719 else {
1720 current_head = lookup_commit_or_die(&oid, "HEAD");
1721 if (parse_commit(current_head))
1722 die(_("could not parse HEAD commit"));
1724 verbose = -1; /* unspecified */
1725 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1726 builtin_commit_usage,
1727 prefix, current_head, &s);
1728 if (verbose == -1)
1729 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1731 if (dry_run)
1732 return dry_run_commit(argv, prefix, current_head, &s);
1733 index_file = prepare_index(argv, prefix, current_head, 0);
1735 /* Set up everything for writing the commit object. This includes
1736 running hooks, writing the trees, and interacting with the user. */
1737 if (!prepare_to_commit(index_file, prefix,
1738 current_head, &s, &author_ident)) {
1739 ret = 1;
1740 rollback_index_files();
1741 goto cleanup;
1744 /* Determine parents */
1745 reflog_msg = getenv("GIT_REFLOG_ACTION");
1746 if (!current_head) {
1747 if (!reflog_msg)
1748 reflog_msg = "commit (initial)";
1749 } else if (amend) {
1750 if (!reflog_msg)
1751 reflog_msg = "commit (amend)";
1752 parents = copy_commit_list(current_head->parents);
1753 } else if (whence == FROM_MERGE) {
1754 struct strbuf m = STRBUF_INIT;
1755 FILE *fp;
1756 int allow_fast_forward = 1;
1757 struct commit_list **pptr = &parents;
1759 if (!reflog_msg)
1760 reflog_msg = "commit (merge)";
1761 pptr = commit_list_append(current_head, pptr);
1762 fp = xfopen(git_path_merge_head(the_repository), "r");
1763 while (strbuf_getline_lf(&m, fp) != EOF) {
1764 struct commit *parent;
1766 parent = get_merge_parent(m.buf);
1767 if (!parent)
1768 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1769 pptr = commit_list_append(parent, pptr);
1771 fclose(fp);
1772 strbuf_release(&m);
1773 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1774 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1775 die_errno(_("could not read MERGE_MODE"));
1776 if (!strcmp(sb.buf, "no-ff"))
1777 allow_fast_forward = 0;
1779 if (allow_fast_forward)
1780 reduce_heads_replace(&parents);
1781 } else {
1782 if (!reflog_msg)
1783 reflog_msg = is_from_cherry_pick(whence)
1784 ? "commit (cherry-pick)"
1785 : is_from_rebase(whence)
1786 ? "commit (rebase)"
1787 : "commit";
1788 commit_list_insert(current_head, &parents);
1791 /* Finally, get the commit message */
1792 strbuf_reset(&sb);
1793 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1794 int saved_errno = errno;
1795 rollback_index_files();
1796 die(_("could not read commit message: %s"), strerror(saved_errno));
1799 cleanup_message(&sb, cleanup_mode, verbose);
1801 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1802 rollback_index_files();
1803 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1804 exit(1);
1806 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1807 rollback_index_files();
1808 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1809 exit(1);
1812 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1813 !allow_empty_message) {
1814 struct strbuf body = STRBUF_INIT;
1815 size_t len = commit_subject_length(sb.buf);
1816 strbuf_addstr(&body, sb.buf + len);
1817 if (message_is_empty(&body, cleanup_mode)) {
1818 rollback_index_files();
1819 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1820 exit(1);
1822 strbuf_release(&body);
1825 if (amend) {
1826 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1827 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1828 } else {
1829 struct commit_extra_header **tail = &extra;
1830 append_merge_tag_headers(parents, &tail);
1833 if (commit_tree_extended(sb.buf, sb.len, &the_index.cache_tree->oid,
1834 parents, &oid, author_ident.buf, NULL,
1835 sign_commit, extra)) {
1836 rollback_index_files();
1837 die(_("failed to write commit object"));
1839 free_commit_extra_headers(extra);
1841 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1842 &err)) {
1843 rollback_index_files();
1844 die("%s", err.buf);
1847 sequencer_post_commit_cleanup(the_repository, 0);
1848 unlink(git_path_merge_head(the_repository));
1849 unlink(git_path_merge_msg(the_repository));
1850 unlink(git_path_merge_mode(the_repository));
1851 unlink(git_path_squash_msg(the_repository));
1853 if (commit_index_files())
1854 die(_("repository has been updated, but unable to write\n"
1855 "new_index file. Check that disk is not full and quota is\n"
1856 "not exceeded, and then \"git restore --staged :/\" to recover."));
1858 git_test_write_commit_graph_or_die();
1860 repo_rerere(the_repository, 0);
1861 run_auto_maintenance(quiet);
1862 run_commit_hook(use_editor, get_index_file(), NULL, "post-commit",
1863 NULL);
1864 if (amend && !no_post_rewrite) {
1865 commit_post_rewrite(the_repository, current_head, &oid);
1867 if (!quiet) {
1868 unsigned int flags = 0;
1870 if (!current_head)
1871 flags |= SUMMARY_INITIAL_COMMIT;
1872 if (author_date_is_interesting())
1873 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1874 print_commit_summary(the_repository, prefix,
1875 &oid, flags);
1878 apply_autostash(git_path_merge_autostash(the_repository));
1880 cleanup:
1881 strbuf_release(&author_ident);
1882 strbuf_release(&err);
1883 strbuf_release(&sb);
1884 return ret;