Merge branch 'rs/date-mode-pass-by-value'
[alt-git.git] / builtin / commit.c
blob6e1484446b0cc2c98ccade5f8285ad81747c6416
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_VARIABLE
9 #include "builtin.h"
10 #include "advice.h"
11 #include "config.h"
12 #include "lockfile.h"
13 #include "cache-tree.h"
14 #include "color.h"
15 #include "dir.h"
16 #include "editor.h"
17 #include "environment.h"
18 #include "diff.h"
19 #include "commit.h"
20 #include "gettext.h"
21 #include "revision.h"
22 #include "wt-status.h"
23 #include "run-command.h"
24 #include "strbuf.h"
25 #include "object-name.h"
26 #include "parse-options.h"
27 #include "path.h"
28 #include "preload-index.h"
29 #include "read-cache.h"
30 #include "string-list.h"
31 #include "rerere.h"
32 #include "unpack-trees.h"
33 #include "column.h"
34 #include "sequencer.h"
35 #include "sparse-index.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 if (parse_tree(tree) < 0)
335 exit(128);
336 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
337 if (unpack_trees(1, &t, &opts))
338 exit(128); /* We've already reported the error, finish dying */
341 static void refresh_cache_or_die(int refresh_flags)
344 * refresh_flags contains REFRESH_QUIET, so the only errors
345 * are for unmerged entries.
347 if (refresh_index(&the_index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
348 die_resolve_conflict("commit");
351 static const char *prepare_index(const char **argv, const char *prefix,
352 const struct commit *current_head, int is_status)
354 struct string_list partial = STRING_LIST_INIT_DUP;
355 struct pathspec pathspec;
356 int refresh_flags = REFRESH_QUIET;
357 const char *ret;
359 if (is_status)
360 refresh_flags |= REFRESH_UNMERGED;
361 parse_pathspec(&pathspec, 0,
362 PATHSPEC_PREFER_FULL,
363 prefix, argv);
365 if (pathspec_from_file) {
366 if (interactive)
367 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
369 if (all)
370 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
372 if (pathspec.nr)
373 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
375 parse_pathspec_file(&pathspec, 0,
376 PATHSPEC_PREFER_FULL,
377 prefix, pathspec_from_file, pathspec_file_nul);
378 } else if (pathspec_file_nul) {
379 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
382 if (!pathspec.nr && (also || (only && !allow_empty &&
383 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
384 die(_("No paths with --include/--only does not make sense."));
386 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
387 die(_("index file corrupt"));
389 if (interactive) {
390 char *old_index_env = NULL, *old_repo_index_file;
391 repo_hold_locked_index(the_repository, &index_lock,
392 LOCK_DIE_ON_ERROR);
394 refresh_cache_or_die(refresh_flags);
396 if (write_locked_index(&the_index, &index_lock, 0))
397 die(_("unable to create temporary index"));
399 old_repo_index_file = the_repository->index_file;
400 the_repository->index_file =
401 (char *)get_lock_file_path(&index_lock);
402 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
403 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
405 if (interactive_add(argv, prefix, patch_interactive) != 0)
406 die(_("interactive add failed"));
408 the_repository->index_file = old_repo_index_file;
409 if (old_index_env && *old_index_env)
410 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
411 else
412 unsetenv(INDEX_ENVIRONMENT);
413 FREE_AND_NULL(old_index_env);
415 discard_index(&the_index);
416 read_index_from(&the_index, get_lock_file_path(&index_lock),
417 get_git_dir());
418 if (cache_tree_update(&the_index, WRITE_TREE_SILENT) == 0) {
419 if (reopen_lock_file(&index_lock) < 0)
420 die(_("unable to write index file"));
421 if (write_locked_index(&the_index, &index_lock, 0))
422 die(_("unable to update temporary index"));
423 } else
424 warning(_("Failed to update main cache tree"));
426 commit_style = COMMIT_NORMAL;
427 ret = get_lock_file_path(&index_lock);
428 goto out;
432 * Non partial, non as-is commit.
434 * (1) get the real index;
435 * (2) update the_index as necessary;
436 * (3) write the_index out to the real index (still locked);
437 * (4) return the name of the locked index file.
439 * The caller should run hooks on the locked real index, and
440 * (A) if all goes well, commit the real index;
441 * (B) on failure, rollback the real index.
443 if (all || (also && pathspec.nr)) {
444 char *ps_matched = xcalloc(pathspec.nr, 1);
445 repo_hold_locked_index(the_repository, &index_lock,
446 LOCK_DIE_ON_ERROR);
447 add_files_to_cache(the_repository, also ? prefix : NULL,
448 &pathspec, ps_matched, 0, 0);
449 if (!all && report_path_error(ps_matched, &pathspec))
450 exit(128);
452 refresh_cache_or_die(refresh_flags);
453 cache_tree_update(&the_index, WRITE_TREE_SILENT);
454 if (write_locked_index(&the_index, &index_lock, 0))
455 die(_("unable to write new index file"));
456 commit_style = COMMIT_NORMAL;
457 ret = get_lock_file_path(&index_lock);
458 free(ps_matched);
459 goto out;
463 * As-is commit.
465 * (1) return the name of the real index file.
467 * The caller should run hooks on the real index,
468 * and create commit from the_index.
469 * We still need to refresh the index here.
471 if (!only && !pathspec.nr) {
472 repo_hold_locked_index(the_repository, &index_lock,
473 LOCK_DIE_ON_ERROR);
474 refresh_cache_or_die(refresh_flags);
475 if (the_index.cache_changed
476 || !cache_tree_fully_valid(the_index.cache_tree))
477 cache_tree_update(&the_index, WRITE_TREE_SILENT);
478 if (write_locked_index(&the_index, &index_lock,
479 COMMIT_LOCK | SKIP_IF_UNCHANGED))
480 die(_("unable to write new index file"));
481 commit_style = COMMIT_AS_IS;
482 ret = get_index_file();
483 goto out;
487 * A partial commit.
489 * (0) find the set of affected paths;
490 * (1) get lock on the real index file;
491 * (2) update the_index with the given paths;
492 * (3) write the_index out to the real index (still locked);
493 * (4) get lock on the false index file;
494 * (5) reset the_index from HEAD;
495 * (6) update the_index the same way as (2);
496 * (7) write the_index out to the false index file;
497 * (8) return the name of the false index file (still locked);
499 * The caller should run hooks on the locked false index, and
500 * create commit from it. Then
501 * (A) if all goes well, commit the real index;
502 * (B) on failure, rollback the real index;
503 * In either case, rollback the false index.
505 commit_style = COMMIT_PARTIAL;
507 if (whence != FROM_COMMIT) {
508 if (whence == FROM_MERGE)
509 die(_("cannot do a partial commit during a merge."));
510 else if (is_from_cherry_pick(whence))
511 die(_("cannot do a partial commit during a cherry-pick."));
512 else if (is_from_rebase(whence))
513 die(_("cannot do a partial commit during a rebase."));
516 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
517 exit(1);
519 discard_index(&the_index);
520 if (repo_read_index(the_repository) < 0)
521 die(_("cannot read the index"));
523 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
524 add_remove_files(&partial);
525 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
526 cache_tree_update(&the_index, WRITE_TREE_SILENT);
527 if (write_locked_index(&the_index, &index_lock, 0))
528 die(_("unable to write new index file"));
530 hold_lock_file_for_update(&false_lock,
531 git_path("next-index-%"PRIuMAX,
532 (uintmax_t) getpid()),
533 LOCK_DIE_ON_ERROR);
535 create_base_index(current_head);
536 add_remove_files(&partial);
537 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
539 if (write_locked_index(&the_index, &false_lock, 0))
540 die(_("unable to write temporary index file"));
542 discard_index(&the_index);
543 ret = get_lock_file_path(&false_lock);
544 read_index_from(&the_index, ret, get_git_dir());
545 out:
546 string_list_clear(&partial, 0);
547 clear_pathspec(&pathspec);
548 return ret;
551 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
552 struct wt_status *s)
554 struct object_id oid;
556 if (s->relative_paths)
557 s->prefix = prefix;
559 if (amend) {
560 s->amend = 1;
561 s->reference = "HEAD^1";
563 s->verbose = verbose;
564 s->index_file = index_file;
565 s->fp = fp;
566 s->nowarn = nowarn;
567 s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
568 if (!s->is_initial)
569 oidcpy(&s->oid_commit, &oid);
570 s->status_format = status_format;
571 s->ignore_submodule_arg = ignore_submodule_arg;
573 wt_status_collect(s);
574 wt_status_print(s);
575 wt_status_collect_free_buffers(s);
577 return s->committable;
580 static int is_a_merge(const struct commit *current_head)
582 return !!(current_head->parents && current_head->parents->next);
585 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
587 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
588 BUG("unable to parse our own ident: %s", buf->buf);
591 static void export_one(const char *var, const char *s, const char *e, int hack)
593 struct strbuf buf = STRBUF_INIT;
594 if (hack)
595 strbuf_addch(&buf, hack);
596 strbuf_add(&buf, s, e - s);
597 setenv(var, buf.buf, 1);
598 strbuf_release(&buf);
601 static int parse_force_date(const char *in, struct strbuf *out)
603 strbuf_addch(out, '@');
605 if (parse_date(in, out) < 0) {
606 int errors = 0;
607 unsigned long t = approxidate_careful(in, &errors);
608 if (errors)
609 return -1;
610 strbuf_addf(out, "%lu", t);
613 return 0;
616 static void set_ident_var(char **buf, char *val)
618 free(*buf);
619 *buf = val;
622 static void determine_author_info(struct strbuf *author_ident)
624 char *name, *email, *date;
625 struct ident_split author;
627 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
628 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
629 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
631 if (author_message) {
632 struct ident_split ident;
633 size_t len;
634 const char *a;
636 a = find_commit_header(author_message_buffer, "author", &len);
637 if (!a)
638 die(_("commit '%s' lacks author header"), author_message);
639 if (split_ident_line(&ident, a, len) < 0)
640 die(_("commit '%s' has malformed author line"), author_message);
642 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
643 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
645 if (ident.date_begin) {
646 struct strbuf date_buf = STRBUF_INIT;
647 strbuf_addch(&date_buf, '@');
648 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
649 strbuf_addch(&date_buf, ' ');
650 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
651 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
655 if (force_author) {
656 struct ident_split ident;
658 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
659 die(_("malformed --author parameter"));
660 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
661 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
664 if (force_date) {
665 struct strbuf date_buf = STRBUF_INIT;
666 if (parse_force_date(force_date, &date_buf))
667 die(_("invalid date format: %s"), force_date);
668 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
671 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
672 IDENT_STRICT));
673 assert_split_ident(&author, author_ident);
674 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
675 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
676 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
677 free(name);
678 free(email);
679 free(date);
682 static int author_date_is_interesting(void)
684 return author_message || force_date;
687 static void adjust_comment_line_char(const struct strbuf *sb)
689 char candidates[] = "#;@!$%^&|:";
690 char *candidate;
691 const char *p;
693 if (!memchr(sb->buf, candidates[0], sb->len)) {
694 comment_line_str = xstrfmt("%c", candidates[0]);
695 return;
698 p = sb->buf;
699 candidate = strchr(candidates, *p);
700 if (candidate)
701 *candidate = ' ';
702 for (p = sb->buf; *p; p++) {
703 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
704 candidate = strchr(candidates, p[1]);
705 if (candidate)
706 *candidate = ' ';
710 for (p = candidates; *p == ' '; p++)
712 if (!*p)
713 die(_("unable to select a comment character that is not used\n"
714 "in the current commit message"));
715 comment_line_str = xstrfmt("%c", *p);
718 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
719 struct pretty_print_context *ctx)
721 const char *buffer, *subject, *fmt;
723 buffer = repo_get_commit_buffer(the_repository, commit, NULL);
724 find_commit_subject(buffer, &subject);
726 * If we amend the 'amend!' commit then we don't want to
727 * duplicate the subject line.
729 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
730 repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
731 repo_unuse_commit_buffer(the_repository, commit, buffer);
734 static int prepare_to_commit(const char *index_file, const char *prefix,
735 struct commit *current_head,
736 struct wt_status *s,
737 struct strbuf *author_ident)
739 struct stat statbuf;
740 struct strbuf committer_ident = STRBUF_INIT;
741 int committable;
742 struct strbuf sb = STRBUF_INIT;
743 const char *hook_arg1 = NULL;
744 const char *hook_arg2 = NULL;
745 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
746 int old_display_comment_prefix;
747 int invoked_hook;
749 /* This checks and barfs if author is badly specified */
750 determine_author_info(author_ident);
752 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
753 "pre-commit", NULL))
754 return 0;
756 if (squash_message) {
758 * Insert the proper subject line before other commit
759 * message options add their content.
761 if (use_message && !strcmp(use_message, squash_message))
762 strbuf_addstr(&sb, "squash! ");
763 else {
764 struct pretty_print_context ctx = {0};
765 struct commit *c;
766 c = lookup_commit_reference_by_name(squash_message);
767 if (!c)
768 die(_("could not lookup commit '%s'"), squash_message);
769 ctx.output_encoding = get_commit_output_encoding();
770 repo_format_commit_message(the_repository, c,
771 "squash! %s\n\n", &sb,
772 &ctx);
776 if (have_option_m && !fixup_message) {
777 strbuf_addbuf(&sb, &message);
778 hook_arg1 = "message";
779 } else if (logfile && !strcmp(logfile, "-")) {
780 if (isatty(0))
781 fprintf(stderr, _("(reading log message from standard input)\n"));
782 if (strbuf_read(&sb, 0, 0) < 0)
783 die_errno(_("could not read log from standard input"));
784 hook_arg1 = "message";
785 } else if (logfile) {
786 if (strbuf_read_file(&sb, logfile, 0) < 0)
787 die_errno(_("could not read log file '%s'"),
788 logfile);
789 hook_arg1 = "message";
790 } else if (use_message) {
791 char *buffer;
792 buffer = strstr(use_message_buffer, "\n\n");
793 if (buffer)
794 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
795 hook_arg1 = "commit";
796 hook_arg2 = use_message;
797 } else if (fixup_message) {
798 struct pretty_print_context ctx = {0};
799 struct commit *commit;
800 char *fmt;
801 commit = lookup_commit_reference_by_name(fixup_commit);
802 if (!commit)
803 die(_("could not lookup commit '%s'"), fixup_commit);
804 ctx.output_encoding = get_commit_output_encoding();
805 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
806 repo_format_commit_message(the_repository, commit, fmt, &sb,
807 &ctx);
808 free(fmt);
809 hook_arg1 = "message";
812 * Only `-m` commit message option is checked here, as
813 * it supports `--fixup` to append the commit message.
815 * The other commit message options `-c`/`-C`/`-F` are
816 * incompatible with all the forms of `--fixup` and
817 * have already errored out while parsing the `git commit`
818 * options.
820 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
821 strbuf_addbuf(&sb, &message);
823 if (!strcmp(fixup_prefix, "amend")) {
824 if (have_option_m)
825 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
826 prepare_amend_commit(commit, &sb, &ctx);
828 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
829 size_t merge_msg_start;
832 * prepend SQUASH_MSG here if it exists and a
833 * "merge --squash" was originally performed
835 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
836 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
837 die_errno(_("could not read SQUASH_MSG"));
838 hook_arg1 = "squash";
839 } else
840 hook_arg1 = "merge";
842 merge_msg_start = sb.len;
843 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
844 die_errno(_("could not read MERGE_MSG"));
846 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
847 wt_status_locate_end(sb.buf + merge_msg_start,
848 sb.len - merge_msg_start) <
849 sb.len - merge_msg_start)
850 s->added_cut_line = 1;
851 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
852 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
853 die_errno(_("could not read SQUASH_MSG"));
854 hook_arg1 = "squash";
855 } else if (template_file) {
856 if (strbuf_read_file(&sb, template_file, 0) < 0)
857 die_errno(_("could not read '%s'"), template_file);
858 hook_arg1 = "template";
859 clean_message_contents = 0;
863 * The remaining cases don't modify the template message, but
864 * just set the argument(s) to the prepare-commit-msg hook.
866 else if (whence == FROM_MERGE)
867 hook_arg1 = "merge";
868 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
869 hook_arg1 = "commit";
870 hook_arg2 = "CHERRY_PICK_HEAD";
873 if (squash_message) {
875 * If squash_commit was used for the commit subject,
876 * then we're possibly hijacking other commit log options.
877 * Reset the hook args to tell the real story.
879 hook_arg1 = "message";
880 hook_arg2 = "";
883 s->fp = fopen_for_writing(git_path_commit_editmsg());
884 if (!s->fp)
885 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
887 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
888 old_display_comment_prefix = s->display_comment_prefix;
889 s->display_comment_prefix = 1;
892 * Most hints are counter-productive when the commit has
893 * already started.
895 s->hints = 0;
897 if (clean_message_contents)
898 strbuf_stripspace(&sb, NULL);
900 if (signoff)
901 append_signoff(&sb, ignored_log_message_bytes(sb.buf, sb.len), 0);
903 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
904 die_errno(_("could not write commit template"));
906 if (auto_comment_line_char)
907 adjust_comment_line_char(&sb);
908 strbuf_release(&sb);
910 /* This checks if committer ident is explicitly given */
911 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
912 if (use_editor && include_status) {
913 int ident_shown = 0;
914 int saved_color_setting;
915 struct ident_split ci, ai;
916 const char *hint_cleanup_all = allow_empty_message ?
917 _("Please enter the commit message for your changes."
918 " Lines starting\nwith '%s' will be ignored.\n") :
919 _("Please enter the commit message for your changes."
920 " Lines starting\nwith '%s' will be ignored, and an empty"
921 " message aborts the commit.\n");
922 const char *hint_cleanup_space = allow_empty_message ?
923 _("Please enter the commit message for your changes."
924 " Lines starting\n"
925 "with '%s' will be kept; you may remove them"
926 " yourself if you want to.\n") :
927 _("Please enter the commit message for your changes."
928 " Lines starting\n"
929 "with '%s' will be kept; you may remove them"
930 " yourself if you want to.\n"
931 "An empty message aborts the commit.\n");
932 if (whence != FROM_COMMIT) {
933 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
934 wt_status_add_cut_line(s);
935 status_printf_ln(
936 s, GIT_COLOR_NORMAL,
937 whence == FROM_MERGE ?
938 _("\n"
939 "It looks like you may be committing a merge.\n"
940 "If this is not correct, please run\n"
941 " git update-ref -d MERGE_HEAD\n"
942 "and try again.\n") :
943 _("\n"
944 "It looks like you may be committing a cherry-pick.\n"
945 "If this is not correct, please run\n"
946 " git update-ref -d CHERRY_PICK_HEAD\n"
947 "and try again.\n"));
950 fprintf(s->fp, "\n");
951 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
952 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_str);
953 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
954 if (whence == FROM_COMMIT)
955 wt_status_add_cut_line(s);
956 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
957 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_str);
960 * These should never fail because they come from our own
961 * fmt_ident. They may fail the sane_ident test, but we know
962 * that the name and mail pointers will at least be valid,
963 * which is enough for our tests and printing here.
965 assert_split_ident(&ai, author_ident);
966 assert_split_ident(&ci, &committer_ident);
968 if (ident_cmp(&ai, &ci))
969 status_printf_ln(s, GIT_COLOR_NORMAL,
970 _("%s"
971 "Author: %.*s <%.*s>"),
972 ident_shown++ ? "" : "\n",
973 (int)(ai.name_end - ai.name_begin), ai.name_begin,
974 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
976 if (author_date_is_interesting())
977 status_printf_ln(s, GIT_COLOR_NORMAL,
978 _("%s"
979 "Date: %s"),
980 ident_shown++ ? "" : "\n",
981 show_ident_date(&ai, DATE_MODE(NORMAL)));
983 if (!committer_ident_sufficiently_given())
984 status_printf_ln(s, GIT_COLOR_NORMAL,
985 _("%s"
986 "Committer: %.*s <%.*s>"),
987 ident_shown++ ? "" : "\n",
988 (int)(ci.name_end - ci.name_begin), ci.name_begin,
989 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
991 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
993 saved_color_setting = s->use_color;
994 s->use_color = 0;
995 committable = run_status(s->fp, index_file, prefix, 1, s);
996 s->use_color = saved_color_setting;
997 string_list_clear(&s->change, 1);
998 } else {
999 struct object_id oid;
1000 const char *parent = "HEAD";
1002 if (!the_index.initialized && repo_read_index(the_repository) < 0)
1003 die(_("Cannot read index"));
1005 if (amend)
1006 parent = "HEAD^1";
1008 if (repo_get_oid(the_repository, parent, &oid)) {
1009 int i, ita_nr = 0;
1011 /* TODO: audit for interaction with sparse-index. */
1012 ensure_full_index(&the_index);
1013 for (i = 0; i < the_index.cache_nr; i++)
1014 if (ce_intent_to_add(the_index.cache[i]))
1015 ita_nr++;
1016 committable = the_index.cache_nr - ita_nr > 0;
1017 } else {
1019 * Unless the user did explicitly request a submodule
1020 * ignore mode by passing a command line option we do
1021 * not ignore any changed submodule SHA-1s when
1022 * comparing index and parent, no matter what is
1023 * configured. Otherwise we won't commit any
1024 * submodules which were manually staged, which would
1025 * be really confusing.
1027 struct diff_flags flags = DIFF_FLAGS_INIT;
1028 flags.override_submodule_config = 1;
1029 if (ignore_submodule_arg &&
1030 !strcmp(ignore_submodule_arg, "all"))
1031 flags.ignore_submodules = 1;
1032 committable = index_differs_from(the_repository,
1033 parent, &flags, 1);
1036 strbuf_release(&committer_ident);
1038 fclose(s->fp);
1040 if (trailer_args.nr) {
1041 struct child_process run_trailer = CHILD_PROCESS_INIT;
1043 strvec_pushl(&run_trailer.args, "interpret-trailers",
1044 "--in-place", "--no-divider",
1045 git_path_commit_editmsg(), NULL);
1046 strvec_pushv(&run_trailer.args, trailer_args.v);
1047 run_trailer.git_cmd = 1;
1048 if (run_command(&run_trailer))
1049 die(_("unable to pass trailers to --trailers"));
1050 strvec_clear(&trailer_args);
1054 * Reject an attempt to record a non-merge empty commit without
1055 * explicit --allow-empty. In the cherry-pick case, it may be
1056 * empty due to conflict resolution, which the user should okay.
1058 if (!committable && whence != FROM_MERGE && !allow_empty &&
1059 !(amend && is_a_merge(current_head))) {
1060 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1061 s->display_comment_prefix = old_display_comment_prefix;
1062 run_status(stdout, index_file, prefix, 0, s);
1063 if (amend)
1064 fputs(_(empty_amend_advice), stderr);
1065 else if (is_from_cherry_pick(whence) ||
1066 whence == FROM_REBASE_PICK) {
1067 fputs(_(empty_cherry_pick_advice), stderr);
1068 if (whence == FROM_CHERRY_PICK_SINGLE)
1069 fputs(_(empty_cherry_pick_advice_single), stderr);
1070 else if (whence == FROM_CHERRY_PICK_MULTI)
1071 fputs(_(empty_cherry_pick_advice_multi), stderr);
1072 else
1073 fputs(_(empty_rebase_pick_advice), stderr);
1075 return 0;
1078 if (!no_verify && invoked_hook) {
1080 * Re-read the index as the pre-commit-commit hook was invoked
1081 * and could have updated it. We must do this before we invoke
1082 * the editor and after we invoke run_status above.
1084 discard_index(&the_index);
1086 read_index_from(&the_index, index_file, get_git_dir());
1088 if (cache_tree_update(&the_index, 0)) {
1089 error(_("Error building trees"));
1090 return 0;
1093 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1094 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1095 return 0;
1097 if (use_editor) {
1098 struct strvec env = STRVEC_INIT;
1100 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1101 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1102 fprintf(stderr,
1103 _("Please supply the message using either -m or -F option.\n"));
1104 exit(1);
1106 strvec_clear(&env);
1109 if (!no_verify &&
1110 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1111 git_path_commit_editmsg(), NULL)) {
1112 return 0;
1115 return 1;
1118 static const char *find_author_by_nickname(const char *name)
1120 struct rev_info revs;
1121 struct commit *commit;
1122 struct strbuf buf = STRBUF_INIT;
1123 const char *av[20];
1124 int ac = 0;
1126 repo_init_revisions(the_repository, &revs, NULL);
1127 strbuf_addf(&buf, "--author=%s", name);
1128 av[++ac] = "--all";
1129 av[++ac] = "-i";
1130 av[++ac] = buf.buf;
1131 av[++ac] = NULL;
1132 setup_revisions(ac, av, &revs, NULL);
1133 revs.mailmap = xmalloc(sizeof(struct string_list));
1134 string_list_init_nodup(revs.mailmap);
1135 read_mailmap(revs.mailmap);
1137 if (prepare_revision_walk(&revs))
1138 die(_("revision walk setup failed"));
1139 commit = get_revision(&revs);
1140 if (commit) {
1141 struct pretty_print_context ctx = {0};
1142 ctx.date_mode.type = DATE_NORMAL;
1143 strbuf_release(&buf);
1144 repo_format_commit_message(the_repository, commit,
1145 "%aN <%aE>", &buf, &ctx);
1146 release_revisions(&revs);
1147 return strbuf_detach(&buf, NULL);
1149 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1152 static void handle_ignored_arg(struct wt_status *s)
1154 if (!ignored_arg)
1155 ; /* default already initialized */
1156 else if (!strcmp(ignored_arg, "traditional"))
1157 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1158 else if (!strcmp(ignored_arg, "no"))
1159 s->show_ignored_mode = SHOW_NO_IGNORED;
1160 else if (!strcmp(ignored_arg, "matching"))
1161 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1162 else
1163 die(_("Invalid ignored mode '%s'"), ignored_arg);
1166 static enum untracked_status_type parse_untracked_setting_name(const char *u)
1169 * Please update $__git_untracked_file_modes in
1170 * git-completion.bash when you add new options
1172 switch (git_parse_maybe_bool(u)) {
1173 case 0:
1174 u = "no";
1175 break;
1176 case 1:
1177 u = "normal";
1178 break;
1179 default:
1180 break;
1183 if (!strcmp(u, "no"))
1184 return SHOW_NO_UNTRACKED_FILES;
1185 else if (!strcmp(u, "normal"))
1186 return SHOW_NORMAL_UNTRACKED_FILES;
1187 else if (!strcmp(u, "all"))
1188 return SHOW_ALL_UNTRACKED_FILES;
1189 else
1190 return SHOW_UNTRACKED_FILES_ERROR;
1193 static void handle_untracked_files_arg(struct wt_status *s)
1195 enum untracked_status_type u;
1197 if (!untracked_files_arg)
1198 return; /* default already initialized */
1200 u = parse_untracked_setting_name(untracked_files_arg);
1201 if (u == SHOW_UNTRACKED_FILES_ERROR)
1202 die(_("Invalid untracked files mode '%s'"),
1203 untracked_files_arg);
1204 s->show_untracked_files = u;
1207 static const char *read_commit_message(const char *name)
1209 const char *out_enc;
1210 struct commit *commit;
1212 commit = lookup_commit_reference_by_name(name);
1213 if (!commit)
1214 die(_("could not lookup commit '%s'"), name);
1215 out_enc = get_commit_output_encoding();
1216 return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1220 * Enumerate what needs to be propagated when --porcelain
1221 * is not in effect here.
1223 static struct status_deferred_config {
1224 enum wt_status_format status_format;
1225 int show_branch;
1226 enum ahead_behind_flags ahead_behind;
1227 } status_deferred_config = {
1228 STATUS_FORMAT_UNSPECIFIED,
1229 -1, /* unspecified */
1230 AHEAD_BEHIND_UNSPECIFIED,
1233 static void finalize_deferred_config(struct wt_status *s)
1235 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1236 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1237 !s->null_termination);
1239 if (s->null_termination) {
1240 if (status_format == STATUS_FORMAT_NONE ||
1241 status_format == STATUS_FORMAT_UNSPECIFIED)
1242 status_format = STATUS_FORMAT_PORCELAIN;
1243 else if (status_format == STATUS_FORMAT_LONG)
1244 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1247 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1248 status_format = status_deferred_config.status_format;
1249 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1250 status_format = STATUS_FORMAT_NONE;
1252 if (use_deferred_config && s->show_branch < 0)
1253 s->show_branch = status_deferred_config.show_branch;
1254 if (s->show_branch < 0)
1255 s->show_branch = 0;
1258 * If the user did not give a "--[no]-ahead-behind" command
1259 * line argument *AND* we will print in a human-readable format
1260 * (short, long etc.) then we inherit from the status.aheadbehind
1261 * config setting. In all other cases (and porcelain V[12] formats
1262 * in particular), we inherit _FULL for backwards compatibility.
1264 if (use_deferred_config &&
1265 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1266 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1268 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1269 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1272 static void check_fixup_reword_options(int argc, const char *argv[]) {
1273 if (whence != FROM_COMMIT) {
1274 if (whence == FROM_MERGE)
1275 die(_("You are in the middle of a merge -- cannot reword."));
1276 else if (is_from_cherry_pick(whence))
1277 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1279 if (argc)
1280 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1281 if (patch_interactive || interactive || all || also || only)
1282 die(_("reword option of '%s' and '%s' cannot be used together"),
1283 "--fixup", "--patch/--interactive/--all/--include/--only");
1286 static int parse_and_validate_options(int argc, const char *argv[],
1287 const struct option *options,
1288 const char * const usage[],
1289 const char *prefix,
1290 struct commit *current_head,
1291 struct wt_status *s)
1293 argc = parse_options(argc, argv, prefix, options, usage, 0);
1294 finalize_deferred_config(s);
1296 if (force_author && !strchr(force_author, '>'))
1297 force_author = find_author_by_nickname(force_author);
1299 if (force_author && renew_authorship)
1300 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1302 if (logfile || have_option_m || use_message)
1303 use_editor = 0;
1305 /* Sanity check options */
1306 if (amend && !current_head)
1307 die(_("You have nothing to amend."));
1308 if (amend && whence != FROM_COMMIT) {
1309 if (whence == FROM_MERGE)
1310 die(_("You are in the middle of a merge -- cannot amend."));
1311 else if (is_from_cherry_pick(whence))
1312 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1313 else if (whence == FROM_REBASE_PICK)
1314 die(_("You are in the middle of a rebase -- cannot amend."));
1316 if (fixup_message && squash_message)
1317 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1318 die_for_incompatible_opt4(!!use_message, "-C",
1319 !!edit_message, "-c",
1320 !!logfile, "-F",
1321 !!fixup_message, "--fixup");
1322 die_for_incompatible_opt4(have_option_m, "-m",
1323 !!edit_message, "-c",
1324 !!use_message, "-C",
1325 !!logfile, "-F");
1326 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1327 template_file = NULL;
1328 if (edit_message)
1329 use_message = edit_message;
1330 if (amend && !use_message && !fixup_message)
1331 use_message = "HEAD";
1332 if (!use_message && !is_from_cherry_pick(whence) &&
1333 !is_from_rebase(whence) && renew_authorship)
1334 die(_("--reset-author can be used only with -C, -c or --amend."));
1335 if (use_message) {
1336 use_message_buffer = read_commit_message(use_message);
1337 if (!renew_authorship) {
1338 author_message = use_message;
1339 author_message_buffer = use_message_buffer;
1342 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1343 !renew_authorship) {
1344 author_message = "CHERRY_PICK_HEAD";
1345 author_message_buffer = read_commit_message(author_message);
1348 if (patch_interactive)
1349 interactive = 1;
1351 die_for_incompatible_opt4(also, "-i/--include",
1352 only, "-o/--only",
1353 all, "-a/--all",
1354 interactive, "--interactive/-p/--patch");
1355 if (fixup_message) {
1357 * We limit --fixup's suboptions to only alpha characters.
1358 * If the first character after a run of alpha is colon,
1359 * then the part before the colon may be a known suboption
1360 * name like `amend` or `reword`, or a misspelt suboption
1361 * name. In either case, we treat it as
1362 * --fixup=<suboption>:<arg>.
1364 * Otherwise, we are dealing with --fixup=<commit>.
1366 char *p = fixup_message;
1367 while (isalpha(*p))
1368 p++;
1369 if (p > fixup_message && *p == ':') {
1370 *p = '\0';
1371 fixup_commit = p + 1;
1372 if (!strcmp("amend", fixup_message) ||
1373 !strcmp("reword", fixup_message)) {
1374 fixup_prefix = "amend";
1375 allow_empty = 1;
1376 if (*fixup_message == 'r') {
1377 check_fixup_reword_options(argc, argv);
1378 only = 1;
1380 } else {
1381 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1383 } else {
1384 fixup_commit = fixup_message;
1385 fixup_prefix = "fixup";
1386 use_editor = 0;
1390 if (0 <= edit_flag)
1391 use_editor = edit_flag;
1393 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1395 handle_untracked_files_arg(s);
1397 if (all && argc > 0)
1398 die(_("paths '%s ...' with -a does not make sense"),
1399 argv[0]);
1401 if (status_format != STATUS_FORMAT_NONE)
1402 dry_run = 1;
1404 return argc;
1407 static int dry_run_commit(const char **argv, const char *prefix,
1408 const struct commit *current_head, struct wt_status *s)
1410 int committable;
1411 const char *index_file;
1413 index_file = prepare_index(argv, prefix, current_head, 1);
1414 committable = run_status(stdout, index_file, prefix, 0, s);
1415 rollback_index_files();
1417 return committable ? 0 : 1;
1420 define_list_config_array_extra(color_status_slots, {"added"});
1422 static int parse_status_slot(const char *slot)
1424 if (!strcasecmp(slot, "added"))
1425 return WT_STATUS_UPDATED;
1427 return LOOKUP_CONFIG(color_status_slots, slot);
1430 static int git_status_config(const char *k, const char *v,
1431 const struct config_context *ctx, void *cb)
1433 struct wt_status *s = cb;
1434 const char *slot_name;
1436 if (starts_with(k, "column."))
1437 return git_column_config(k, v, "status", &s->colopts);
1438 if (!strcmp(k, "status.submodulesummary")) {
1439 int is_bool;
1440 s->submodule_summary = git_config_bool_or_int(k, v, ctx->kvi,
1441 &is_bool);
1442 if (is_bool && s->submodule_summary)
1443 s->submodule_summary = -1;
1444 return 0;
1446 if (!strcmp(k, "status.short")) {
1447 if (git_config_bool(k, v))
1448 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1449 else
1450 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1451 return 0;
1453 if (!strcmp(k, "status.branch")) {
1454 status_deferred_config.show_branch = git_config_bool(k, v);
1455 return 0;
1457 if (!strcmp(k, "status.aheadbehind")) {
1458 status_deferred_config.ahead_behind = git_config_bool(k, v);
1459 return 0;
1461 if (!strcmp(k, "status.showstash")) {
1462 s->show_stash = git_config_bool(k, v);
1463 return 0;
1465 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1466 s->use_color = git_config_colorbool(k, v);
1467 return 0;
1469 if (!strcmp(k, "status.displaycommentprefix")) {
1470 s->display_comment_prefix = git_config_bool(k, v);
1471 return 0;
1473 if (skip_prefix(k, "status.color.", &slot_name) ||
1474 skip_prefix(k, "color.status.", &slot_name)) {
1475 int slot = parse_status_slot(slot_name);
1476 if (slot < 0)
1477 return 0;
1478 if (!v)
1479 return config_error_nonbool(k);
1480 return color_parse(v, s->color_palette[slot]);
1482 if (!strcmp(k, "status.relativepaths")) {
1483 s->relative_paths = git_config_bool(k, v);
1484 return 0;
1486 if (!strcmp(k, "status.showuntrackedfiles")) {
1487 enum untracked_status_type u;
1489 u = parse_untracked_setting_name(v);
1490 if (u == SHOW_UNTRACKED_FILES_ERROR)
1491 return error(_("Invalid untracked files mode '%s'"), v);
1492 s->show_untracked_files = u;
1493 return 0;
1495 if (!strcmp(k, "diff.renamelimit")) {
1496 if (s->rename_limit == -1)
1497 s->rename_limit = git_config_int(k, v, ctx->kvi);
1498 return 0;
1500 if (!strcmp(k, "status.renamelimit")) {
1501 s->rename_limit = git_config_int(k, v, ctx->kvi);
1502 return 0;
1504 if (!strcmp(k, "diff.renames")) {
1505 if (s->detect_rename == -1)
1506 s->detect_rename = git_config_rename(k, v);
1507 return 0;
1509 if (!strcmp(k, "status.renames")) {
1510 s->detect_rename = git_config_rename(k, v);
1511 return 0;
1513 return git_diff_ui_config(k, v, ctx, NULL);
1516 int cmd_status(int argc, const char **argv, const char *prefix)
1518 static int no_renames = -1;
1519 static const char *rename_score_arg = (const char *)-1;
1520 static struct wt_status s;
1521 unsigned int progress_flag = 0;
1522 int fd;
1523 struct object_id oid;
1524 static struct option builtin_status_options[] = {
1525 OPT__VERBOSE(&verbose, N_("be verbose")),
1526 OPT_SET_INT('s', "short", &status_format,
1527 N_("show status concisely"), STATUS_FORMAT_SHORT),
1528 OPT_BOOL('b', "branch", &s.show_branch,
1529 N_("show branch information")),
1530 OPT_BOOL(0, "show-stash", &s.show_stash,
1531 N_("show stash information")),
1532 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1533 N_("compute full ahead/behind values")),
1534 OPT_CALLBACK_F(0, "porcelain", &status_format,
1535 N_("version"), N_("machine-readable output"),
1536 PARSE_OPT_OPTARG, opt_parse_porcelain),
1537 OPT_SET_INT(0, "long", &status_format,
1538 N_("show status in long format (default)"),
1539 STATUS_FORMAT_LONG),
1540 OPT_BOOL('z', "null", &s.null_termination,
1541 N_("terminate entries with NUL")),
1542 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1543 N_("mode"),
1544 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1545 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1546 { OPTION_STRING, 0, "ignored", &ignored_arg,
1547 N_("mode"),
1548 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1549 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1550 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1551 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1552 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1553 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1554 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1555 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1556 N_("n"), N_("detect renames, optionally set similarity index"),
1557 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1558 OPT_END(),
1561 if (argc == 2 && !strcmp(argv[1], "-h"))
1562 usage_with_options(builtin_status_usage, builtin_status_options);
1564 prepare_repo_settings(the_repository);
1565 the_repository->settings.command_requires_full_index = 0;
1567 status_init_config(&s, git_status_config);
1568 argc = parse_options(argc, argv, prefix,
1569 builtin_status_options,
1570 builtin_status_usage, 0);
1571 finalize_colopts(&s.colopts, -1);
1572 finalize_deferred_config(&s);
1574 handle_untracked_files_arg(&s);
1575 handle_ignored_arg(&s);
1577 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1578 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1579 die(_("Unsupported combination of ignored and untracked-files arguments"));
1581 parse_pathspec(&s.pathspec, 0,
1582 PATHSPEC_PREFER_FULL,
1583 prefix, argv);
1585 if (status_format != STATUS_FORMAT_PORCELAIN &&
1586 status_format != STATUS_FORMAT_PORCELAIN_V2)
1587 progress_flag = REFRESH_PROGRESS;
1588 repo_read_index(the_repository);
1589 refresh_index(&the_index,
1590 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1591 &s.pathspec, NULL, NULL);
1593 if (use_optional_locks())
1594 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1595 else
1596 fd = -1;
1598 s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1599 if (!s.is_initial)
1600 oidcpy(&s.oid_commit, &oid);
1602 s.ignore_submodule_arg = ignore_submodule_arg;
1603 s.status_format = status_format;
1604 s.verbose = verbose;
1605 if (no_renames != -1)
1606 s.detect_rename = !no_renames;
1607 if ((intptr_t)rename_score_arg != -1) {
1608 if (s.detect_rename < DIFF_DETECT_RENAME)
1609 s.detect_rename = DIFF_DETECT_RENAME;
1610 if (rename_score_arg)
1611 s.rename_score = parse_rename_score(&rename_score_arg);
1614 wt_status_collect(&s);
1616 if (0 <= fd)
1617 repo_update_index_if_able(the_repository, &index_lock);
1619 if (s.relative_paths)
1620 s.prefix = prefix;
1622 wt_status_print(&s);
1623 wt_status_collect_free_buffers(&s);
1625 return 0;
1628 static int git_commit_config(const char *k, const char *v,
1629 const struct config_context *ctx, void *cb)
1631 struct wt_status *s = cb;
1633 if (!strcmp(k, "commit.template"))
1634 return git_config_pathname(&template_file, k, v);
1635 if (!strcmp(k, "commit.status")) {
1636 include_status = git_config_bool(k, v);
1637 return 0;
1639 if (!strcmp(k, "commit.cleanup"))
1640 return git_config_string(&cleanup_arg, k, v);
1641 if (!strcmp(k, "commit.gpgsign")) {
1642 sign_commit = git_config_bool(k, v) ? "" : NULL;
1643 return 0;
1645 if (!strcmp(k, "commit.verbose")) {
1646 int is_bool;
1647 config_commit_verbose = git_config_bool_or_int(k, v, ctx->kvi,
1648 &is_bool);
1649 return 0;
1652 return git_status_config(k, v, ctx, s);
1655 int cmd_commit(int argc, const char **argv, const char *prefix)
1657 static struct wt_status s;
1658 static struct option builtin_commit_options[] = {
1659 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1660 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1662 OPT_GROUP(N_("Commit message options")),
1663 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1664 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1665 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1666 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1667 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1668 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1670 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1671 * and only translate <commit>.
1673 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1674 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1675 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1676 OPT_CALLBACK_F(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG, opt_pass_trailer),
1677 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1678 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1679 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1680 OPT_CLEANUP(&cleanup_arg),
1681 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1682 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1683 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1684 /* end commit message options */
1686 OPT_GROUP(N_("Commit contents options")),
1687 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1688 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1689 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1690 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1691 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1692 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1693 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1694 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1695 STATUS_FORMAT_SHORT),
1696 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1697 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1698 N_("compute full ahead/behind values")),
1699 OPT_SET_INT(0, "porcelain", &status_format,
1700 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1701 OPT_SET_INT(0, "long", &status_format,
1702 N_("show status in long format (default)"),
1703 STATUS_FORMAT_LONG),
1704 OPT_BOOL('z', "null", &s.null_termination,
1705 N_("terminate entries with NUL")),
1706 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1707 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1708 { 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" },
1709 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1710 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1711 /* end commit contents options */
1713 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1714 N_("ok to record an empty change")),
1715 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1716 N_("ok to record a change with an empty message")),
1718 OPT_END()
1721 struct strbuf sb = STRBUF_INIT;
1722 struct strbuf author_ident = STRBUF_INIT;
1723 const char *index_file, *reflog_msg;
1724 struct object_id oid;
1725 struct commit_list *parents = NULL;
1726 struct stat statbuf;
1727 struct commit *current_head = NULL;
1728 struct commit_extra_header *extra = NULL;
1729 struct strbuf err = STRBUF_INIT;
1730 int ret = 0;
1732 if (argc == 2 && !strcmp(argv[1], "-h"))
1733 usage_with_options(builtin_commit_usage, builtin_commit_options);
1735 prepare_repo_settings(the_repository);
1736 the_repository->settings.command_requires_full_index = 0;
1738 status_init_config(&s, git_commit_config);
1739 s.commit_template = 1;
1740 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1741 s.colopts = 0;
1743 if (repo_get_oid(the_repository, "HEAD", &oid))
1744 current_head = NULL;
1745 else {
1746 current_head = lookup_commit_or_die(&oid, "HEAD");
1747 if (repo_parse_commit(the_repository, current_head))
1748 die(_("could not parse HEAD commit"));
1750 verbose = -1; /* unspecified */
1751 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1752 builtin_commit_usage,
1753 prefix, current_head, &s);
1754 if (verbose == -1)
1755 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1757 if (dry_run)
1758 return dry_run_commit(argv, prefix, current_head, &s);
1759 index_file = prepare_index(argv, prefix, current_head, 0);
1761 /* Set up everything for writing the commit object. This includes
1762 running hooks, writing the trees, and interacting with the user. */
1763 if (!prepare_to_commit(index_file, prefix,
1764 current_head, &s, &author_ident)) {
1765 ret = 1;
1766 rollback_index_files();
1767 goto cleanup;
1770 /* Determine parents */
1771 reflog_msg = getenv("GIT_REFLOG_ACTION");
1772 if (!current_head) {
1773 if (!reflog_msg)
1774 reflog_msg = "commit (initial)";
1775 } else if (amend) {
1776 if (!reflog_msg)
1777 reflog_msg = "commit (amend)";
1778 parents = copy_commit_list(current_head->parents);
1779 } else if (whence == FROM_MERGE) {
1780 struct strbuf m = STRBUF_INIT;
1781 FILE *fp;
1782 int allow_fast_forward = 1;
1783 struct commit_list **pptr = &parents;
1785 if (!reflog_msg)
1786 reflog_msg = "commit (merge)";
1787 pptr = commit_list_append(current_head, pptr);
1788 fp = xfopen(git_path_merge_head(the_repository), "r");
1789 while (strbuf_getline_lf(&m, fp) != EOF) {
1790 struct commit *parent;
1792 parent = get_merge_parent(m.buf);
1793 if (!parent)
1794 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1795 pptr = commit_list_append(parent, pptr);
1797 fclose(fp);
1798 strbuf_release(&m);
1799 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1800 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1801 die_errno(_("could not read MERGE_MODE"));
1802 if (!strcmp(sb.buf, "no-ff"))
1803 allow_fast_forward = 0;
1805 if (allow_fast_forward)
1806 reduce_heads_replace(&parents);
1807 } else {
1808 if (!reflog_msg)
1809 reflog_msg = is_from_cherry_pick(whence)
1810 ? "commit (cherry-pick)"
1811 : is_from_rebase(whence)
1812 ? "commit (rebase)"
1813 : "commit";
1814 commit_list_insert(current_head, &parents);
1817 /* Finally, get the commit message */
1818 strbuf_reset(&sb);
1819 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1820 int saved_errno = errno;
1821 rollback_index_files();
1822 die(_("could not read commit message: %s"), strerror(saved_errno));
1825 cleanup_message(&sb, cleanup_mode, verbose);
1827 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1828 rollback_index_files();
1829 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1830 exit(1);
1832 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1833 rollback_index_files();
1834 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1835 exit(1);
1838 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1839 !allow_empty_message) {
1840 struct strbuf body = STRBUF_INIT;
1841 size_t len = commit_subject_length(sb.buf);
1842 strbuf_addstr(&body, sb.buf + len);
1843 if (message_is_empty(&body, cleanup_mode)) {
1844 rollback_index_files();
1845 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1846 exit(1);
1848 strbuf_release(&body);
1851 if (amend) {
1852 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1853 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1854 } else {
1855 struct commit_extra_header **tail = &extra;
1856 append_merge_tag_headers(parents, &tail);
1859 if (commit_tree_extended(sb.buf, sb.len, &the_index.cache_tree->oid,
1860 parents, &oid, author_ident.buf, NULL,
1861 sign_commit, extra)) {
1862 rollback_index_files();
1863 die(_("failed to write commit object"));
1865 free_commit_extra_headers(extra);
1867 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1868 &err)) {
1869 rollback_index_files();
1870 die("%s", err.buf);
1873 sequencer_post_commit_cleanup(the_repository, 0);
1874 unlink(git_path_merge_head(the_repository));
1875 unlink(git_path_merge_msg(the_repository));
1876 unlink(git_path_merge_mode(the_repository));
1877 unlink(git_path_squash_msg(the_repository));
1879 if (commit_index_files())
1880 die(_("repository has been updated, but unable to write\n"
1881 "new index file. Check that disk is not full and quota is\n"
1882 "not exceeded, and then \"git restore --staged :/\" to recover."));
1884 git_test_write_commit_graph_or_die();
1886 repo_rerere(the_repository, 0);
1887 run_auto_maintenance(quiet);
1888 run_commit_hook(use_editor, get_index_file(), NULL, "post-commit",
1889 NULL);
1890 if (amend && !no_post_rewrite) {
1891 commit_post_rewrite(the_repository, current_head, &oid);
1893 if (!quiet) {
1894 unsigned int flags = 0;
1896 if (!current_head)
1897 flags |= SUMMARY_INITIAL_COMMIT;
1898 if (author_date_is_interesting())
1899 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1900 print_commit_summary(the_repository, prefix,
1901 &oid, flags);
1904 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1906 cleanup:
1907 strbuf_release(&author_ident);
1908 strbuf_release(&err);
1909 strbuf_release(&sb);
1910 return ret;