Merge branch 'rs/diff-parseopts-cleanup'
[git/gitster.git] / builtin / commit.c
blobc2943055ef75acbf9d8c6842edc66adfa9b865b8
1 /*
2 * Builtin "git commit"
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6 */
8 #include "builtin.h"
9 #include "advice.h"
10 #include "config.h"
11 #include "lockfile.h"
12 #include "cache-tree.h"
13 #include "color.h"
14 #include "dir.h"
15 #include "editor.h"
16 #include "environment.h"
17 #include "diff.h"
18 #include "commit.h"
19 #include "gettext.h"
20 #include "revision.h"
21 #include "wt-status.h"
22 #include "run-command.h"
23 #include "strbuf.h"
24 #include "object-name.h"
25 #include "parse-options.h"
26 #include "path.h"
27 #include "preload-index.h"
28 #include "read-cache.h"
29 #include "string-list.h"
30 #include "rerere.h"
31 #include "unpack-trees.h"
32 #include "column.h"
33 #include "sequencer.h"
34 #include "sparse-index.h"
35 #include "mailmap.h"
36 #include "help.h"
37 #include "commit-reach.h"
38 #include "commit-graph.h"
39 #include "pretty.h"
41 static const char * const builtin_commit_usage[] = {
42 N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]\n"
43 " [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>)]\n"
44 " [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
45 " [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
46 " [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
47 " [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
48 " [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
49 " [--] [<pathspec>...]"),
50 NULL
53 static const char * const builtin_status_usage[] = {
54 N_("git status [<options>] [--] [<pathspec>...]"),
55 NULL
58 static const char empty_amend_advice[] =
59 N_("You asked to amend the most recent commit, but doing so would make\n"
60 "it empty. You can repeat your command with --allow-empty, or you can\n"
61 "remove the commit entirely with \"git reset HEAD^\".\n");
63 static const char empty_cherry_pick_advice[] =
64 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
65 "If you wish to commit it anyway, use:\n"
66 "\n"
67 " git commit --allow-empty\n"
68 "\n");
70 static const char empty_rebase_pick_advice[] =
71 N_("Otherwise, please use 'git rebase --skip'\n");
73 static const char empty_cherry_pick_advice_single[] =
74 N_("Otherwise, please use 'git cherry-pick --skip'\n");
76 static const char empty_cherry_pick_advice_multi[] =
77 N_("and then use:\n"
78 "\n"
79 " git cherry-pick --continue\n"
80 "\n"
81 "to resume cherry-picking the remaining commits.\n"
82 "If you wish to skip this commit, use:\n"
83 "\n"
84 " git cherry-pick --skip\n"
85 "\n");
87 static const char *color_status_slots[] = {
88 [WT_STATUS_HEADER] = "header",
89 [WT_STATUS_UPDATED] = "updated",
90 [WT_STATUS_CHANGED] = "changed",
91 [WT_STATUS_UNTRACKED] = "untracked",
92 [WT_STATUS_NOBRANCH] = "noBranch",
93 [WT_STATUS_UNMERGED] = "unmerged",
94 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
95 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
96 [WT_STATUS_ONBRANCH] = "branch",
99 static const char *use_message_buffer;
100 static struct lock_file index_lock; /* real index */
101 static struct lock_file false_lock; /* used only for partial commits */
102 static enum {
103 COMMIT_AS_IS = 1,
104 COMMIT_NORMAL,
105 COMMIT_PARTIAL
106 } commit_style;
108 static const char *logfile, *force_author;
109 static const char *template_file;
111 * The _message variables are commit names from which to take
112 * the commit message and/or authorship.
114 static const char *author_message, *author_message_buffer;
115 static char *edit_message, *use_message;
116 static char *fixup_message, *fixup_commit, *squash_message;
117 static const char *fixup_prefix;
118 static int all, also, interactive, patch_interactive, only, amend, signoff;
119 static int edit_flag = -1; /* unspecified */
120 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
121 static int config_commit_verbose = -1; /* unspecified */
122 static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
123 static char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
124 static char *sign_commit, *pathspec_from_file;
125 static struct strvec trailer_args = STRVEC_INIT;
128 * The default commit message cleanup mode will remove the lines
129 * beginning with # (shell comments) and leading and trailing
130 * whitespaces (empty lines or containing only whitespaces)
131 * if editor is used, and only the whitespaces if the message
132 * is specified explicitly.
134 static enum commit_msg_cleanup_mode cleanup_mode;
135 static const char *cleanup_arg;
137 static enum commit_whence whence;
138 static int use_editor = 1, include_status = 1;
139 static int have_option_m;
140 static struct strbuf message = STRBUF_INIT;
142 static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
144 static int opt_pass_trailer(const struct option *opt, const char *arg, int unset)
146 BUG_ON_OPT_NEG(unset);
148 strvec_pushl(opt->value, "--trailer", arg, NULL);
149 return 0;
152 static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
154 enum wt_status_format *value = (enum wt_status_format *)opt->value;
155 if (unset)
156 *value = STATUS_FORMAT_NONE;
157 else if (!arg)
158 *value = STATUS_FORMAT_PORCELAIN;
159 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
160 *value = STATUS_FORMAT_PORCELAIN;
161 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
162 *value = STATUS_FORMAT_PORCELAIN_V2;
163 else
164 die("unsupported porcelain version '%s'", arg);
166 return 0;
169 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
171 struct strbuf *buf = opt->value;
172 if (unset) {
173 have_option_m = 0;
174 strbuf_setlen(buf, 0);
175 } else {
176 have_option_m = 1;
177 if (buf->len)
178 strbuf_addch(buf, '\n');
179 strbuf_addstr(buf, arg);
180 strbuf_complete_line(buf);
182 return 0;
185 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
187 const char **value = opt->value;
189 BUG_ON_OPT_NEG(unset);
191 if (arg != NULL && *arg == '=')
192 arg = arg + 1;
194 *value = arg;
195 return 0;
198 static void determine_whence(struct wt_status *s)
200 if (file_exists(git_path_merge_head(the_repository)))
201 whence = FROM_MERGE;
202 else if (!sequencer_determine_whence(the_repository, &whence))
203 whence = FROM_COMMIT;
204 if (s)
205 s->whence = whence;
208 static void status_init_config(struct wt_status *s, config_fn_t fn)
210 wt_status_prepare(the_repository, s);
211 init_diff_ui_defaults();
212 git_config(fn, s);
213 determine_whence(s);
214 s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after git_config() */
217 static void rollback_index_files(void)
219 switch (commit_style) {
220 case COMMIT_AS_IS:
221 break; /* nothing to do */
222 case COMMIT_NORMAL:
223 rollback_lock_file(&index_lock);
224 break;
225 case COMMIT_PARTIAL:
226 rollback_lock_file(&index_lock);
227 rollback_lock_file(&false_lock);
228 break;
232 static int commit_index_files(void)
234 int err = 0;
236 switch (commit_style) {
237 case COMMIT_AS_IS:
238 break; /* nothing to do */
239 case COMMIT_NORMAL:
240 err = commit_lock_file(&index_lock);
241 break;
242 case COMMIT_PARTIAL:
243 err = commit_lock_file(&index_lock);
244 rollback_lock_file(&false_lock);
245 break;
248 return err;
252 * Take a union of paths in the index and the named tree (typically, "HEAD"),
253 * and return the paths that match the given pattern in list.
255 static int list_paths(struct string_list *list, const char *with_tree,
256 const struct pathspec *pattern)
258 int i, ret;
259 char *m;
261 if (!pattern->nr)
262 return 0;
264 m = xcalloc(1, pattern->nr);
266 if (with_tree) {
267 char *max_prefix = common_prefix(pattern);
268 overlay_tree_on_index(the_repository->index, with_tree, max_prefix);
269 free(max_prefix);
272 /* TODO: audit for interaction with sparse-index. */
273 ensure_full_index(the_repository->index);
274 for (i = 0; i < the_repository->index->cache_nr; i++) {
275 const struct cache_entry *ce = the_repository->index->cache[i];
276 struct string_list_item *item;
278 if (ce->ce_flags & CE_UPDATE)
279 continue;
280 if (!ce_path_match(the_repository->index, ce, pattern, m))
281 continue;
282 item = string_list_insert(list, ce->name);
283 if (ce_skip_worktree(ce))
284 item->util = item; /* better a valid pointer than a fake one */
287 ret = report_path_error(m, pattern);
288 free(m);
289 return ret;
292 static void add_remove_files(struct string_list *list)
294 int i;
295 for (i = 0; i < list->nr; i++) {
296 struct stat st;
297 struct string_list_item *p = &(list->items[i]);
299 /* p->util is skip-worktree */
300 if (p->util)
301 continue;
303 if (!lstat(p->string, &st)) {
304 if (add_to_index(the_repository->index, p->string, &st, 0))
305 die(_("updating files failed"));
306 } else
307 remove_file_from_index(the_repository->index, p->string);
311 static void create_base_index(const struct commit *current_head)
313 struct tree *tree;
314 struct unpack_trees_options opts;
315 struct tree_desc t;
317 if (!current_head) {
318 discard_index(the_repository->index);
319 return;
322 memset(&opts, 0, sizeof(opts));
323 opts.head_idx = 1;
324 opts.index_only = 1;
325 opts.merge = 1;
326 opts.src_index = the_repository->index;
327 opts.dst_index = the_repository->index;
329 opts.fn = oneway_merge;
330 tree = parse_tree_indirect(&current_head->object.oid);
331 if (!tree)
332 die(_("failed to unpack HEAD tree object"));
333 if (parse_tree(tree) < 0)
334 exit(128);
335 init_tree_desc(&t, &tree->object.oid, 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_repository->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_repository->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_repository->index);
415 read_index_from(the_repository->index, get_lock_file_path(&index_lock),
416 get_git_dir());
417 if (cache_tree_update(the_repository->index, 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_repository->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 char *ps_matched = xcalloc(pathspec.nr, 1);
444 repo_hold_locked_index(the_repository, &index_lock,
445 LOCK_DIE_ON_ERROR);
446 add_files_to_cache(the_repository, also ? prefix : NULL,
447 &pathspec, ps_matched, 0, 0);
448 if (!all && report_path_error(ps_matched, &pathspec))
449 exit(128);
451 refresh_cache_or_die(refresh_flags);
452 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
453 if (write_locked_index(the_repository->index, &index_lock, 0))
454 die(_("unable to write new index file"));
455 commit_style = COMMIT_NORMAL;
456 ret = get_lock_file_path(&index_lock);
457 free(ps_matched);
458 goto out;
462 * As-is commit.
464 * (1) return the name of the real index file.
466 * The caller should run hooks on the real index,
467 * and create commit from the_index.
468 * We still need to refresh the index here.
470 if (!only && !pathspec.nr) {
471 repo_hold_locked_index(the_repository, &index_lock,
472 LOCK_DIE_ON_ERROR);
473 refresh_cache_or_die(refresh_flags);
474 if (the_repository->index->cache_changed
475 || !cache_tree_fully_valid(the_repository->index->cache_tree))
476 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
477 if (write_locked_index(the_repository->index, &index_lock,
478 COMMIT_LOCK | SKIP_IF_UNCHANGED))
479 die(_("unable to write new index file"));
480 commit_style = COMMIT_AS_IS;
481 ret = get_index_file();
482 goto out;
486 * A partial commit.
488 * (0) find the set of affected paths;
489 * (1) get lock on the real index file;
490 * (2) update the_index with the given paths;
491 * (3) write the_index out to the real index (still locked);
492 * (4) get lock on the false index file;
493 * (5) reset the_index from HEAD;
494 * (6) update the_index the same way as (2);
495 * (7) write the_index out to the false index file;
496 * (8) return the name of the false index file (still locked);
498 * The caller should run hooks on the locked false index, and
499 * create commit from it. Then
500 * (A) if all goes well, commit the real index;
501 * (B) on failure, rollback the real index;
502 * In either case, rollback the false index.
504 commit_style = COMMIT_PARTIAL;
506 if (whence != FROM_COMMIT) {
507 if (whence == FROM_MERGE)
508 die(_("cannot do a partial commit during a merge."));
509 else if (is_from_cherry_pick(whence))
510 die(_("cannot do a partial commit during a cherry-pick."));
511 else if (is_from_rebase(whence))
512 die(_("cannot do a partial commit during a rebase."));
515 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
516 exit(1);
518 discard_index(the_repository->index);
519 if (repo_read_index(the_repository) < 0)
520 die(_("cannot read the index"));
522 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
523 add_remove_files(&partial);
524 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
525 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
526 if (write_locked_index(the_repository->index, &index_lock, 0))
527 die(_("unable to write new index file"));
529 hold_lock_file_for_update(&false_lock,
530 git_path("next-index-%"PRIuMAX,
531 (uintmax_t) getpid()),
532 LOCK_DIE_ON_ERROR);
534 create_base_index(current_head);
535 add_remove_files(&partial);
536 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
538 if (write_locked_index(the_repository->index, &false_lock, 0))
539 die(_("unable to write temporary index file"));
541 discard_index(the_repository->index);
542 ret = get_lock_file_path(&false_lock);
543 read_index_from(the_repository->index, ret, get_git_dir());
544 out:
545 string_list_clear(&partial, 0);
546 clear_pathspec(&pathspec);
547 return ret;
550 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
551 struct wt_status *s)
553 struct object_id oid;
555 if (s->relative_paths)
556 s->prefix = prefix;
558 if (amend) {
559 s->amend = 1;
560 s->reference = "HEAD^1";
562 s->verbose = verbose;
563 s->index_file = index_file;
564 s->fp = fp;
565 s->nowarn = nowarn;
566 s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
567 if (!s->is_initial)
568 oidcpy(&s->oid_commit, &oid);
569 s->status_format = status_format;
570 s->ignore_submodule_arg = ignore_submodule_arg;
572 wt_status_collect(s);
573 wt_status_print(s);
574 wt_status_collect_free_buffers(s);
576 return s->committable;
579 static int is_a_merge(const struct commit *current_head)
581 return !!(current_head->parents && current_head->parents->next);
584 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
586 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
587 BUG("unable to parse our own ident: %s", buf->buf);
590 static void export_one(const char *var, const char *s, const char *e, int hack)
592 struct strbuf buf = STRBUF_INIT;
593 if (hack)
594 strbuf_addch(&buf, hack);
595 strbuf_add(&buf, s, e - s);
596 setenv(var, buf.buf, 1);
597 strbuf_release(&buf);
600 static int parse_force_date(const char *in, struct strbuf *out)
602 strbuf_addch(out, '@');
604 if (parse_date(in, out) < 0) {
605 int errors = 0;
606 unsigned long t = approxidate_careful(in, &errors);
607 if (errors)
608 return -1;
609 strbuf_addf(out, "%lu", t);
612 return 0;
615 static void set_ident_var(char **buf, char *val)
617 free(*buf);
618 *buf = val;
621 static void determine_author_info(struct strbuf *author_ident)
623 char *name, *email, *date;
624 struct ident_split author;
626 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
627 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
628 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
630 if (author_message) {
631 struct ident_split ident;
632 size_t len;
633 const char *a;
635 a = find_commit_header(author_message_buffer, "author", &len);
636 if (!a)
637 die(_("commit '%s' lacks author header"), author_message);
638 if (split_ident_line(&ident, a, len) < 0)
639 die(_("commit '%s' has malformed author line"), author_message);
641 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
642 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
644 if (ident.date_begin) {
645 struct strbuf date_buf = STRBUF_INIT;
646 strbuf_addch(&date_buf, '@');
647 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
648 strbuf_addch(&date_buf, ' ');
649 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
650 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
654 if (force_author) {
655 struct ident_split ident;
657 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
658 die(_("malformed --author parameter"));
659 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
660 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
663 if (force_date) {
664 struct strbuf date_buf = STRBUF_INIT;
665 if (parse_force_date(force_date, &date_buf))
666 die(_("invalid date format: %s"), force_date);
667 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
670 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
671 IDENT_STRICT));
672 assert_split_ident(&author, author_ident);
673 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
674 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
675 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
676 free(name);
677 free(email);
678 free(date);
681 static int author_date_is_interesting(void)
683 return author_message || force_date;
686 static void adjust_comment_line_char(const struct strbuf *sb)
688 char candidates[] = "#;@!$%^&|:";
689 char *candidate;
690 const char *p;
692 if (!memchr(sb->buf, candidates[0], sb->len)) {
693 comment_line_str = xstrfmt("%c", candidates[0]);
694 return;
697 p = sb->buf;
698 candidate = strchr(candidates, *p);
699 if (candidate)
700 *candidate = ' ';
701 for (p = sb->buf; *p; p++) {
702 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
703 candidate = strchr(candidates, p[1]);
704 if (candidate)
705 *candidate = ' ';
709 for (p = candidates; *p == ' '; p++)
711 if (!*p)
712 die(_("unable to select a comment character that is not used\n"
713 "in the current commit message"));
714 comment_line_str = xstrfmt("%c", *p);
717 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
718 struct pretty_print_context *ctx)
720 const char *buffer, *subject, *fmt;
722 buffer = repo_get_commit_buffer(the_repository, commit, NULL);
723 find_commit_subject(buffer, &subject);
725 * If we amend the 'amend!' commit then we don't want to
726 * duplicate the subject line.
728 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
729 repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
730 repo_unuse_commit_buffer(the_repository, commit, buffer);
733 static int prepare_to_commit(const char *index_file, const char *prefix,
734 struct commit *current_head,
735 struct wt_status *s,
736 struct strbuf *author_ident)
738 struct stat statbuf;
739 struct strbuf committer_ident = STRBUF_INIT;
740 int committable;
741 struct strbuf sb = STRBUF_INIT;
742 const char *hook_arg1 = NULL;
743 const char *hook_arg2 = NULL;
744 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
745 int old_display_comment_prefix;
746 int invoked_hook;
748 /* This checks and barfs if author is badly specified */
749 determine_author_info(author_ident);
751 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
752 "pre-commit", NULL))
753 return 0;
755 if (squash_message) {
757 * Insert the proper subject line before other commit
758 * message options add their content.
760 if (use_message && !strcmp(use_message, squash_message))
761 strbuf_addstr(&sb, "squash! ");
762 else {
763 struct pretty_print_context ctx = {0};
764 struct commit *c;
765 c = lookup_commit_reference_by_name(squash_message);
766 if (!c)
767 die(_("could not lookup commit '%s'"), squash_message);
768 ctx.output_encoding = get_commit_output_encoding();
769 repo_format_commit_message(the_repository, c,
770 "squash! %s\n\n", &sb,
771 &ctx);
775 if (have_option_m && !fixup_message) {
776 strbuf_addbuf(&sb, &message);
777 hook_arg1 = "message";
778 } else if (logfile && !strcmp(logfile, "-")) {
779 if (isatty(0))
780 fprintf(stderr, _("(reading log message from standard input)\n"));
781 if (strbuf_read(&sb, 0, 0) < 0)
782 die_errno(_("could not read log from standard input"));
783 hook_arg1 = "message";
784 } else if (logfile) {
785 if (strbuf_read_file(&sb, logfile, 0) < 0)
786 die_errno(_("could not read log file '%s'"),
787 logfile);
788 hook_arg1 = "message";
789 } else if (use_message) {
790 char *buffer;
791 buffer = strstr(use_message_buffer, "\n\n");
792 if (buffer)
793 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
794 hook_arg1 = "commit";
795 hook_arg2 = use_message;
796 } else if (fixup_message) {
797 struct pretty_print_context ctx = {0};
798 struct commit *commit;
799 char *fmt;
800 commit = lookup_commit_reference_by_name(fixup_commit);
801 if (!commit)
802 die(_("could not lookup commit '%s'"), fixup_commit);
803 ctx.output_encoding = get_commit_output_encoding();
804 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
805 repo_format_commit_message(the_repository, commit, fmt, &sb,
806 &ctx);
807 free(fmt);
808 hook_arg1 = "message";
811 * Only `-m` commit message option is checked here, as
812 * it supports `--fixup` to append the commit message.
814 * The other commit message options `-c`/`-C`/`-F` are
815 * incompatible with all the forms of `--fixup` and
816 * have already errored out while parsing the `git commit`
817 * options.
819 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
820 strbuf_addbuf(&sb, &message);
822 if (!strcmp(fixup_prefix, "amend")) {
823 if (have_option_m)
824 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
825 prepare_amend_commit(commit, &sb, &ctx);
827 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
828 size_t merge_msg_start;
831 * prepend SQUASH_MSG here if it exists and a
832 * "merge --squash" was originally performed
834 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
835 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
836 die_errno(_("could not read SQUASH_MSG"));
837 hook_arg1 = "squash";
838 } else
839 hook_arg1 = "merge";
841 merge_msg_start = sb.len;
842 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
843 die_errno(_("could not read MERGE_MSG"));
845 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
846 wt_status_locate_end(sb.buf + merge_msg_start,
847 sb.len - merge_msg_start) <
848 sb.len - merge_msg_start)
849 s->added_cut_line = 1;
850 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
851 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
852 die_errno(_("could not read SQUASH_MSG"));
853 hook_arg1 = "squash";
854 } else if (template_file) {
855 if (strbuf_read_file(&sb, template_file, 0) < 0)
856 die_errno(_("could not read '%s'"), template_file);
857 hook_arg1 = "template";
858 clean_message_contents = 0;
862 * The remaining cases don't modify the template message, but
863 * just set the argument(s) to the prepare-commit-msg hook.
865 else if (whence == FROM_MERGE)
866 hook_arg1 = "merge";
867 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
868 hook_arg1 = "commit";
869 hook_arg2 = "CHERRY_PICK_HEAD";
872 if (squash_message) {
874 * If squash_commit was used for the commit subject,
875 * then we're possibly hijacking other commit log options.
876 * Reset the hook args to tell the real story.
878 hook_arg1 = "message";
879 hook_arg2 = "";
882 s->fp = fopen_for_writing(git_path_commit_editmsg());
883 if (!s->fp)
884 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
886 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
887 old_display_comment_prefix = s->display_comment_prefix;
888 s->display_comment_prefix = 1;
891 * Most hints are counter-productive when the commit has
892 * already started.
894 s->hints = 0;
896 if (clean_message_contents)
897 strbuf_stripspace(&sb, NULL);
899 if (signoff)
900 append_signoff(&sb, ignored_log_message_bytes(sb.buf, sb.len), 0);
902 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
903 die_errno(_("could not write commit template"));
905 if (auto_comment_line_char)
906 adjust_comment_line_char(&sb);
907 strbuf_release(&sb);
909 /* This checks if committer ident is explicitly given */
910 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
911 if (use_editor && include_status) {
912 int ident_shown = 0;
913 int saved_color_setting;
914 struct ident_split ci, ai;
915 const char *hint_cleanup_all = allow_empty_message ?
916 _("Please enter the commit message for your changes."
917 " Lines starting\nwith '%s' will be ignored.\n") :
918 _("Please enter the commit message for your changes."
919 " Lines starting\nwith '%s' will be ignored, and an empty"
920 " message aborts the commit.\n");
921 const char *hint_cleanup_space = allow_empty_message ?
922 _("Please enter the commit message for your changes."
923 " Lines starting\n"
924 "with '%s' will be kept; you may remove them"
925 " yourself if you want to.\n") :
926 _("Please enter the commit message for your changes."
927 " Lines starting\n"
928 "with '%s' will be kept; you may remove them"
929 " yourself if you want to.\n"
930 "An empty message aborts the commit.\n");
931 if (whence != FROM_COMMIT) {
932 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
933 wt_status_add_cut_line(s);
934 status_printf_ln(
935 s, GIT_COLOR_NORMAL,
936 whence == FROM_MERGE ?
937 _("\n"
938 "It looks like you may be committing a merge.\n"
939 "If this is not correct, please run\n"
940 " git update-ref -d MERGE_HEAD\n"
941 "and try again.\n") :
942 _("\n"
943 "It looks like you may be committing a cherry-pick.\n"
944 "If this is not correct, please run\n"
945 " git update-ref -d CHERRY_PICK_HEAD\n"
946 "and try again.\n"));
949 fprintf(s->fp, "\n");
950 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
951 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_str);
952 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
953 if (whence == FROM_COMMIT)
954 wt_status_add_cut_line(s);
955 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
956 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_str);
959 * These should never fail because they come from our own
960 * fmt_ident. They may fail the sane_ident test, but we know
961 * that the name and mail pointers will at least be valid,
962 * which is enough for our tests and printing here.
964 assert_split_ident(&ai, author_ident);
965 assert_split_ident(&ci, &committer_ident);
967 if (ident_cmp(&ai, &ci))
968 status_printf_ln(s, GIT_COLOR_NORMAL,
969 _("%s"
970 "Author: %.*s <%.*s>"),
971 ident_shown++ ? "" : "\n",
972 (int)(ai.name_end - ai.name_begin), ai.name_begin,
973 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
975 if (author_date_is_interesting())
976 status_printf_ln(s, GIT_COLOR_NORMAL,
977 _("%s"
978 "Date: %s"),
979 ident_shown++ ? "" : "\n",
980 show_ident_date(&ai, DATE_MODE(NORMAL)));
982 if (!committer_ident_sufficiently_given())
983 status_printf_ln(s, GIT_COLOR_NORMAL,
984 _("%s"
985 "Committer: %.*s <%.*s>"),
986 ident_shown++ ? "" : "\n",
987 (int)(ci.name_end - ci.name_begin), ci.name_begin,
988 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
990 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
992 saved_color_setting = s->use_color;
993 s->use_color = 0;
994 committable = run_status(s->fp, index_file, prefix, 1, s);
995 s->use_color = saved_color_setting;
996 string_list_clear(&s->change, 1);
997 } else {
998 struct object_id oid;
999 const char *parent = "HEAD";
1001 if (!the_repository->index->initialized && repo_read_index(the_repository) < 0)
1002 die(_("Cannot read index"));
1004 if (amend)
1005 parent = "HEAD^1";
1007 if (repo_get_oid(the_repository, parent, &oid)) {
1008 int i, ita_nr = 0;
1010 /* TODO: audit for interaction with sparse-index. */
1011 ensure_full_index(the_repository->index);
1012 for (i = 0; i < the_repository->index->cache_nr; i++)
1013 if (ce_intent_to_add(the_repository->index->cache[i]))
1014 ita_nr++;
1015 committable = the_repository->index->cache_nr - ita_nr > 0;
1016 } else {
1018 * Unless the user did explicitly request a submodule
1019 * ignore mode by passing a command line option we do
1020 * not ignore any changed submodule SHA-1s when
1021 * comparing index and parent, no matter what is
1022 * configured. Otherwise we won't commit any
1023 * submodules which were manually staged, which would
1024 * be really confusing.
1026 struct diff_flags flags = DIFF_FLAGS_INIT;
1027 flags.override_submodule_config = 1;
1028 if (ignore_submodule_arg &&
1029 !strcmp(ignore_submodule_arg, "all"))
1030 flags.ignore_submodules = 1;
1031 committable = index_differs_from(the_repository,
1032 parent, &flags, 1);
1035 strbuf_release(&committer_ident);
1037 fclose(s->fp);
1039 if (trailer_args.nr) {
1040 struct child_process run_trailer = CHILD_PROCESS_INIT;
1042 strvec_pushl(&run_trailer.args, "interpret-trailers",
1043 "--in-place", "--no-divider",
1044 git_path_commit_editmsg(), NULL);
1045 strvec_pushv(&run_trailer.args, trailer_args.v);
1046 run_trailer.git_cmd = 1;
1047 if (run_command(&run_trailer))
1048 die(_("unable to pass trailers to --trailers"));
1049 strvec_clear(&trailer_args);
1053 * Reject an attempt to record a non-merge empty commit without
1054 * explicit --allow-empty. In the cherry-pick case, it may be
1055 * empty due to conflict resolution, which the user should okay.
1057 if (!committable && whence != FROM_MERGE && !allow_empty &&
1058 !(amend && is_a_merge(current_head))) {
1059 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1060 s->display_comment_prefix = old_display_comment_prefix;
1061 run_status(stdout, index_file, prefix, 0, s);
1062 if (amend)
1063 fputs(_(empty_amend_advice), stderr);
1064 else if (is_from_cherry_pick(whence) ||
1065 whence == FROM_REBASE_PICK) {
1066 fputs(_(empty_cherry_pick_advice), stderr);
1067 if (whence == FROM_CHERRY_PICK_SINGLE)
1068 fputs(_(empty_cherry_pick_advice_single), stderr);
1069 else if (whence == FROM_CHERRY_PICK_MULTI)
1070 fputs(_(empty_cherry_pick_advice_multi), stderr);
1071 else
1072 fputs(_(empty_rebase_pick_advice), stderr);
1074 return 0;
1077 if (!no_verify && invoked_hook) {
1079 * Re-read the index as the pre-commit-commit hook was invoked
1080 * and could have updated it. We must do this before we invoke
1081 * the editor and after we invoke run_status above.
1083 discard_index(the_repository->index);
1085 read_index_from(the_repository->index, index_file, get_git_dir());
1087 if (cache_tree_update(the_repository->index, 0)) {
1088 error(_("Error building trees"));
1089 return 0;
1092 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1093 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1094 return 0;
1096 if (use_editor) {
1097 struct strvec env = STRVEC_INIT;
1099 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1100 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1101 fprintf(stderr,
1102 _("Please supply the message using either -m or -F option.\n"));
1103 exit(1);
1105 strvec_clear(&env);
1108 if (!no_verify &&
1109 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1110 git_path_commit_editmsg(), NULL)) {
1111 return 0;
1114 return 1;
1117 static const char *find_author_by_nickname(const char *name)
1119 struct rev_info revs;
1120 struct commit *commit;
1121 struct strbuf buf = STRBUF_INIT;
1122 const char *av[20];
1123 int ac = 0;
1125 repo_init_revisions(the_repository, &revs, NULL);
1126 strbuf_addf(&buf, "--author=%s", name);
1127 av[++ac] = "--all";
1128 av[++ac] = "-i";
1129 av[++ac] = buf.buf;
1130 av[++ac] = NULL;
1131 setup_revisions(ac, av, &revs, NULL);
1132 revs.mailmap = xmalloc(sizeof(struct string_list));
1133 string_list_init_nodup(revs.mailmap);
1134 read_mailmap(revs.mailmap);
1136 if (prepare_revision_walk(&revs))
1137 die(_("revision walk setup failed"));
1138 commit = get_revision(&revs);
1139 if (commit) {
1140 struct pretty_print_context ctx = {0};
1141 ctx.date_mode.type = DATE_NORMAL;
1142 strbuf_release(&buf);
1143 repo_format_commit_message(the_repository, commit,
1144 "%aN <%aE>", &buf, &ctx);
1145 release_revisions(&revs);
1146 return strbuf_detach(&buf, NULL);
1148 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1151 static void handle_ignored_arg(struct wt_status *s)
1153 if (!ignored_arg)
1154 ; /* default already initialized */
1155 else if (!strcmp(ignored_arg, "traditional"))
1156 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1157 else if (!strcmp(ignored_arg, "no"))
1158 s->show_ignored_mode = SHOW_NO_IGNORED;
1159 else if (!strcmp(ignored_arg, "matching"))
1160 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1161 else
1162 die(_("Invalid ignored mode '%s'"), ignored_arg);
1165 static enum untracked_status_type parse_untracked_setting_name(const char *u)
1168 * Please update $__git_untracked_file_modes in
1169 * git-completion.bash when you add new options
1171 switch (git_parse_maybe_bool(u)) {
1172 case 0:
1173 u = "no";
1174 break;
1175 case 1:
1176 u = "normal";
1177 break;
1178 default:
1179 break;
1182 if (!strcmp(u, "no"))
1183 return SHOW_NO_UNTRACKED_FILES;
1184 else if (!strcmp(u, "normal"))
1185 return SHOW_NORMAL_UNTRACKED_FILES;
1186 else if (!strcmp(u, "all"))
1187 return SHOW_ALL_UNTRACKED_FILES;
1188 else
1189 return SHOW_UNTRACKED_FILES_ERROR;
1192 static void handle_untracked_files_arg(struct wt_status *s)
1194 enum untracked_status_type u;
1196 if (!untracked_files_arg)
1197 return; /* default already initialized */
1199 u = parse_untracked_setting_name(untracked_files_arg);
1200 if (u == SHOW_UNTRACKED_FILES_ERROR)
1201 die(_("Invalid untracked files mode '%s'"),
1202 untracked_files_arg);
1203 s->show_untracked_files = u;
1206 static const char *read_commit_message(const char *name)
1208 const char *out_enc;
1209 struct commit *commit;
1211 commit = lookup_commit_reference_by_name(name);
1212 if (!commit)
1213 die(_("could not lookup commit '%s'"), name);
1214 out_enc = get_commit_output_encoding();
1215 return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1219 * Enumerate what needs to be propagated when --porcelain
1220 * is not in effect here.
1222 static struct status_deferred_config {
1223 enum wt_status_format status_format;
1224 int show_branch;
1225 enum ahead_behind_flags ahead_behind;
1226 } status_deferred_config = {
1227 STATUS_FORMAT_UNSPECIFIED,
1228 -1, /* unspecified */
1229 AHEAD_BEHIND_UNSPECIFIED,
1232 static void finalize_deferred_config(struct wt_status *s)
1234 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1235 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1236 !s->null_termination);
1238 if (s->null_termination) {
1239 if (status_format == STATUS_FORMAT_NONE ||
1240 status_format == STATUS_FORMAT_UNSPECIFIED)
1241 status_format = STATUS_FORMAT_PORCELAIN;
1242 else if (status_format == STATUS_FORMAT_LONG)
1243 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1246 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1247 status_format = status_deferred_config.status_format;
1248 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1249 status_format = STATUS_FORMAT_NONE;
1251 if (use_deferred_config && s->show_branch < 0)
1252 s->show_branch = status_deferred_config.show_branch;
1253 if (s->show_branch < 0)
1254 s->show_branch = 0;
1257 * If the user did not give a "--[no]-ahead-behind" command
1258 * line argument *AND* we will print in a human-readable format
1259 * (short, long etc.) then we inherit from the status.aheadbehind
1260 * config setting. In all other cases (and porcelain V[12] formats
1261 * in particular), we inherit _FULL for backwards compatibility.
1263 if (use_deferred_config &&
1264 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1265 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1267 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1268 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1271 static void check_fixup_reword_options(int argc, const char *argv[]) {
1272 if (whence != FROM_COMMIT) {
1273 if (whence == FROM_MERGE)
1274 die(_("You are in the middle of a merge -- cannot reword."));
1275 else if (is_from_cherry_pick(whence))
1276 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1278 if (argc)
1279 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1280 if (patch_interactive || interactive || all || also || only)
1281 die(_("reword option of '%s' and '%s' cannot be used together"),
1282 "--fixup", "--patch/--interactive/--all/--include/--only");
1285 static int parse_and_validate_options(int argc, const char *argv[],
1286 const struct option *options,
1287 const char * const usage[],
1288 const char *prefix,
1289 struct commit *current_head,
1290 struct wt_status *s)
1292 argc = parse_options(argc, argv, prefix, options, usage, 0);
1293 finalize_deferred_config(s);
1295 if (force_author && !strchr(force_author, '>'))
1296 force_author = find_author_by_nickname(force_author);
1298 if (force_author && renew_authorship)
1299 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1301 if (logfile || have_option_m || use_message)
1302 use_editor = 0;
1304 /* Sanity check options */
1305 if (amend && !current_head)
1306 die(_("You have nothing to amend."));
1307 if (amend && whence != FROM_COMMIT) {
1308 if (whence == FROM_MERGE)
1309 die(_("You are in the middle of a merge -- cannot amend."));
1310 else if (is_from_cherry_pick(whence))
1311 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1312 else if (whence == FROM_REBASE_PICK)
1313 die(_("You are in the middle of a rebase -- cannot amend."));
1315 if (fixup_message && squash_message)
1316 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1317 die_for_incompatible_opt4(!!use_message, "-C",
1318 !!edit_message, "-c",
1319 !!logfile, "-F",
1320 !!fixup_message, "--fixup");
1321 die_for_incompatible_opt4(have_option_m, "-m",
1322 !!edit_message, "-c",
1323 !!use_message, "-C",
1324 !!logfile, "-F");
1325 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1326 template_file = NULL;
1327 if (edit_message)
1328 use_message = edit_message;
1329 if (amend && !use_message && !fixup_message)
1330 use_message = "HEAD";
1331 if (!use_message && !is_from_cherry_pick(whence) &&
1332 !is_from_rebase(whence) && renew_authorship)
1333 die(_("--reset-author can be used only with -C, -c or --amend."));
1334 if (use_message) {
1335 use_message_buffer = read_commit_message(use_message);
1336 if (!renew_authorship) {
1337 author_message = use_message;
1338 author_message_buffer = use_message_buffer;
1341 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1342 !renew_authorship) {
1343 author_message = "CHERRY_PICK_HEAD";
1344 author_message_buffer = read_commit_message(author_message);
1347 if (patch_interactive)
1348 interactive = 1;
1350 die_for_incompatible_opt4(also, "-i/--include",
1351 only, "-o/--only",
1352 all, "-a/--all",
1353 interactive, "--interactive/-p/--patch");
1354 if (fixup_message) {
1356 * We limit --fixup's suboptions to only alpha characters.
1357 * If the first character after a run of alpha is colon,
1358 * then the part before the colon may be a known suboption
1359 * name like `amend` or `reword`, or a misspelt suboption
1360 * name. In either case, we treat it as
1361 * --fixup=<suboption>:<arg>.
1363 * Otherwise, we are dealing with --fixup=<commit>.
1365 char *p = fixup_message;
1366 while (isalpha(*p))
1367 p++;
1368 if (p > fixup_message && *p == ':') {
1369 *p = '\0';
1370 fixup_commit = p + 1;
1371 if (!strcmp("amend", fixup_message) ||
1372 !strcmp("reword", fixup_message)) {
1373 fixup_prefix = "amend";
1374 allow_empty = 1;
1375 if (*fixup_message == 'r') {
1376 check_fixup_reword_options(argc, argv);
1377 only = 1;
1379 } else {
1380 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1382 } else {
1383 fixup_commit = fixup_message;
1384 fixup_prefix = "fixup";
1385 use_editor = 0;
1389 if (0 <= edit_flag)
1390 use_editor = edit_flag;
1392 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1394 handle_untracked_files_arg(s);
1396 if (all && argc > 0)
1397 die(_("paths '%s ...' with -a does not make sense"),
1398 argv[0]);
1400 if (status_format != STATUS_FORMAT_NONE)
1401 dry_run = 1;
1403 return argc;
1406 static int dry_run_commit(const char **argv, const char *prefix,
1407 const struct commit *current_head, struct wt_status *s)
1409 int committable;
1410 const char *index_file;
1412 index_file = prepare_index(argv, prefix, current_head, 1);
1413 committable = run_status(stdout, index_file, prefix, 0, s);
1414 rollback_index_files();
1416 return committable ? 0 : 1;
1419 define_list_config_array_extra(color_status_slots, {"added"});
1421 static int parse_status_slot(const char *slot)
1423 if (!strcasecmp(slot, "added"))
1424 return WT_STATUS_UPDATED;
1426 return LOOKUP_CONFIG(color_status_slots, slot);
1429 static int git_status_config(const char *k, const char *v,
1430 const struct config_context *ctx, void *cb)
1432 struct wt_status *s = cb;
1433 const char *slot_name;
1435 if (starts_with(k, "column."))
1436 return git_column_config(k, v, "status", &s->colopts);
1437 if (!strcmp(k, "status.submodulesummary")) {
1438 int is_bool;
1439 s->submodule_summary = git_config_bool_or_int(k, v, ctx->kvi,
1440 &is_bool);
1441 if (is_bool && s->submodule_summary)
1442 s->submodule_summary = -1;
1443 return 0;
1445 if (!strcmp(k, "status.short")) {
1446 if (git_config_bool(k, v))
1447 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1448 else
1449 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1450 return 0;
1452 if (!strcmp(k, "status.branch")) {
1453 status_deferred_config.show_branch = git_config_bool(k, v);
1454 return 0;
1456 if (!strcmp(k, "status.aheadbehind")) {
1457 status_deferred_config.ahead_behind = git_config_bool(k, v);
1458 return 0;
1460 if (!strcmp(k, "status.showstash")) {
1461 s->show_stash = git_config_bool(k, v);
1462 return 0;
1464 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1465 s->use_color = git_config_colorbool(k, v);
1466 return 0;
1468 if (!strcmp(k, "status.displaycommentprefix")) {
1469 s->display_comment_prefix = git_config_bool(k, v);
1470 return 0;
1472 if (skip_prefix(k, "status.color.", &slot_name) ||
1473 skip_prefix(k, "color.status.", &slot_name)) {
1474 int slot = parse_status_slot(slot_name);
1475 if (slot < 0)
1476 return 0;
1477 if (!v)
1478 return config_error_nonbool(k);
1479 return color_parse(v, s->color_palette[slot]);
1481 if (!strcmp(k, "status.relativepaths")) {
1482 s->relative_paths = git_config_bool(k, v);
1483 return 0;
1485 if (!strcmp(k, "status.showuntrackedfiles")) {
1486 enum untracked_status_type u;
1488 u = parse_untracked_setting_name(v);
1489 if (u == SHOW_UNTRACKED_FILES_ERROR)
1490 return error(_("Invalid untracked files mode '%s'"), v);
1491 s->show_untracked_files = u;
1492 return 0;
1494 if (!strcmp(k, "diff.renamelimit")) {
1495 if (s->rename_limit == -1)
1496 s->rename_limit = git_config_int(k, v, ctx->kvi);
1497 return 0;
1499 if (!strcmp(k, "status.renamelimit")) {
1500 s->rename_limit = git_config_int(k, v, ctx->kvi);
1501 return 0;
1503 if (!strcmp(k, "diff.renames")) {
1504 if (s->detect_rename == -1)
1505 s->detect_rename = git_config_rename(k, v);
1506 return 0;
1508 if (!strcmp(k, "status.renames")) {
1509 s->detect_rename = git_config_rename(k, v);
1510 return 0;
1512 return git_diff_ui_config(k, v, ctx, NULL);
1515 int cmd_status(int argc, const char **argv, const char *prefix)
1517 static int no_renames = -1;
1518 static const char *rename_score_arg = (const char *)-1;
1519 static struct wt_status s;
1520 unsigned int progress_flag = 0;
1521 int fd;
1522 struct object_id oid;
1523 static struct option builtin_status_options[] = {
1524 OPT__VERBOSE(&verbose, N_("be verbose")),
1525 OPT_SET_INT('s', "short", &status_format,
1526 N_("show status concisely"), STATUS_FORMAT_SHORT),
1527 OPT_BOOL('b', "branch", &s.show_branch,
1528 N_("show branch information")),
1529 OPT_BOOL(0, "show-stash", &s.show_stash,
1530 N_("show stash information")),
1531 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1532 N_("compute full ahead/behind values")),
1533 OPT_CALLBACK_F(0, "porcelain", &status_format,
1534 N_("version"), N_("machine-readable output"),
1535 PARSE_OPT_OPTARG, opt_parse_porcelain),
1536 OPT_SET_INT(0, "long", &status_format,
1537 N_("show status in long format (default)"),
1538 STATUS_FORMAT_LONG),
1539 OPT_BOOL('z', "null", &s.null_termination,
1540 N_("terminate entries with NUL")),
1541 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1542 N_("mode"),
1543 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1544 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1545 { OPTION_STRING, 0, "ignored", &ignored_arg,
1546 N_("mode"),
1547 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1548 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1549 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1550 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1551 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1552 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1553 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1554 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1555 N_("n"), N_("detect renames, optionally set similarity index"),
1556 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1557 OPT_END(),
1560 if (argc == 2 && !strcmp(argv[1], "-h"))
1561 usage_with_options(builtin_status_usage, builtin_status_options);
1563 prepare_repo_settings(the_repository);
1564 the_repository->settings.command_requires_full_index = 0;
1566 status_init_config(&s, git_status_config);
1567 argc = parse_options(argc, argv, prefix,
1568 builtin_status_options,
1569 builtin_status_usage, 0);
1570 finalize_colopts(&s.colopts, -1);
1571 finalize_deferred_config(&s);
1573 handle_untracked_files_arg(&s);
1574 handle_ignored_arg(&s);
1576 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1577 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1578 die(_("Unsupported combination of ignored and untracked-files arguments"));
1580 parse_pathspec(&s.pathspec, 0,
1581 PATHSPEC_PREFER_FULL,
1582 prefix, argv);
1584 if (status_format != STATUS_FORMAT_PORCELAIN &&
1585 status_format != STATUS_FORMAT_PORCELAIN_V2)
1586 progress_flag = REFRESH_PROGRESS;
1587 repo_read_index(the_repository);
1588 refresh_index(the_repository->index,
1589 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1590 &s.pathspec, NULL, NULL);
1592 if (use_optional_locks())
1593 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1594 else
1595 fd = -1;
1597 s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1598 if (!s.is_initial)
1599 oidcpy(&s.oid_commit, &oid);
1601 s.ignore_submodule_arg = ignore_submodule_arg;
1602 s.status_format = status_format;
1603 s.verbose = verbose;
1604 if (no_renames != -1)
1605 s.detect_rename = !no_renames;
1606 if ((intptr_t)rename_score_arg != -1) {
1607 if (s.detect_rename < DIFF_DETECT_RENAME)
1608 s.detect_rename = DIFF_DETECT_RENAME;
1609 if (rename_score_arg)
1610 s.rename_score = parse_rename_score(&rename_score_arg);
1613 wt_status_collect(&s);
1615 if (0 <= fd)
1616 repo_update_index_if_able(the_repository, &index_lock);
1618 if (s.relative_paths)
1619 s.prefix = prefix;
1621 wt_status_print(&s);
1622 wt_status_collect_free_buffers(&s);
1624 return 0;
1627 static int git_commit_config(const char *k, const char *v,
1628 const struct config_context *ctx, void *cb)
1630 struct wt_status *s = cb;
1632 if (!strcmp(k, "commit.template"))
1633 return git_config_pathname(&template_file, k, v);
1634 if (!strcmp(k, "commit.status")) {
1635 include_status = git_config_bool(k, v);
1636 return 0;
1638 if (!strcmp(k, "commit.cleanup"))
1639 return git_config_string(&cleanup_arg, k, v);
1640 if (!strcmp(k, "commit.gpgsign")) {
1641 sign_commit = git_config_bool(k, v) ? "" : NULL;
1642 return 0;
1644 if (!strcmp(k, "commit.verbose")) {
1645 int is_bool;
1646 config_commit_verbose = git_config_bool_or_int(k, v, ctx->kvi,
1647 &is_bool);
1648 return 0;
1651 return git_status_config(k, v, ctx, s);
1654 int cmd_commit(int argc, const char **argv, const char *prefix)
1656 static struct wt_status s;
1657 static struct option builtin_commit_options[] = {
1658 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1659 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1661 OPT_GROUP(N_("Commit message options")),
1662 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1663 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1664 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1665 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1666 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1667 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1669 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1670 * and only translate <commit>.
1672 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1673 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1674 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1675 OPT_CALLBACK_F(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG, opt_pass_trailer),
1676 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1677 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1678 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1679 OPT_CLEANUP(&cleanup_arg),
1680 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1681 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1682 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1683 /* end commit message options */
1685 OPT_GROUP(N_("Commit contents options")),
1686 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1687 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1688 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1689 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1690 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1691 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1692 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1693 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1694 STATUS_FORMAT_SHORT),
1695 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1696 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1697 N_("compute full ahead/behind values")),
1698 OPT_SET_INT(0, "porcelain", &status_format,
1699 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1700 OPT_SET_INT(0, "long", &status_format,
1701 N_("show status in long format (default)"),
1702 STATUS_FORMAT_LONG),
1703 OPT_BOOL('z', "null", &s.null_termination,
1704 N_("terminate entries with NUL")),
1705 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1706 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1707 { 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" },
1708 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1709 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1710 /* end commit contents options */
1712 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1713 N_("ok to record an empty change")),
1714 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1715 N_("ok to record a change with an empty message")),
1717 OPT_END()
1720 struct strbuf sb = STRBUF_INIT;
1721 struct strbuf author_ident = STRBUF_INIT;
1722 const char *index_file, *reflog_msg;
1723 struct object_id oid;
1724 struct commit_list *parents = NULL;
1725 struct stat statbuf;
1726 struct commit *current_head = NULL;
1727 struct commit_extra_header *extra = NULL;
1728 struct strbuf err = STRBUF_INIT;
1729 int ret = 0;
1731 if (argc == 2 && !strcmp(argv[1], "-h"))
1732 usage_with_options(builtin_commit_usage, builtin_commit_options);
1734 prepare_repo_settings(the_repository);
1735 the_repository->settings.command_requires_full_index = 0;
1737 status_init_config(&s, git_commit_config);
1738 s.commit_template = 1;
1739 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1740 s.colopts = 0;
1742 if (repo_get_oid(the_repository, "HEAD", &oid))
1743 current_head = NULL;
1744 else {
1745 current_head = lookup_commit_or_die(&oid, "HEAD");
1746 if (repo_parse_commit(the_repository, current_head))
1747 die(_("could not parse HEAD commit"));
1749 verbose = -1; /* unspecified */
1750 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1751 builtin_commit_usage,
1752 prefix, current_head, &s);
1753 if (verbose == -1)
1754 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1756 if (dry_run)
1757 return dry_run_commit(argv, prefix, current_head, &s);
1758 index_file = prepare_index(argv, prefix, current_head, 0);
1760 /* Set up everything for writing the commit object. This includes
1761 running hooks, writing the trees, and interacting with the user. */
1762 if (!prepare_to_commit(index_file, prefix,
1763 current_head, &s, &author_ident)) {
1764 ret = 1;
1765 rollback_index_files();
1766 goto cleanup;
1769 /* Determine parents */
1770 reflog_msg = getenv("GIT_REFLOG_ACTION");
1771 if (!current_head) {
1772 if (!reflog_msg)
1773 reflog_msg = "commit (initial)";
1774 } else if (amend) {
1775 if (!reflog_msg)
1776 reflog_msg = "commit (amend)";
1777 parents = copy_commit_list(current_head->parents);
1778 } else if (whence == FROM_MERGE) {
1779 struct strbuf m = STRBUF_INIT;
1780 FILE *fp;
1781 int allow_fast_forward = 1;
1782 struct commit_list **pptr = &parents;
1784 if (!reflog_msg)
1785 reflog_msg = "commit (merge)";
1786 pptr = commit_list_append(current_head, pptr);
1787 fp = xfopen(git_path_merge_head(the_repository), "r");
1788 while (strbuf_getline_lf(&m, fp) != EOF) {
1789 struct commit *parent;
1791 parent = get_merge_parent(m.buf);
1792 if (!parent)
1793 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1794 pptr = commit_list_append(parent, pptr);
1796 fclose(fp);
1797 strbuf_release(&m);
1798 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1799 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1800 die_errno(_("could not read MERGE_MODE"));
1801 if (!strcmp(sb.buf, "no-ff"))
1802 allow_fast_forward = 0;
1804 if (allow_fast_forward)
1805 reduce_heads_replace(&parents);
1806 } else {
1807 if (!reflog_msg)
1808 reflog_msg = is_from_cherry_pick(whence)
1809 ? "commit (cherry-pick)"
1810 : is_from_rebase(whence)
1811 ? "commit (rebase)"
1812 : "commit";
1813 commit_list_insert(current_head, &parents);
1816 /* Finally, get the commit message */
1817 strbuf_reset(&sb);
1818 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1819 int saved_errno = errno;
1820 rollback_index_files();
1821 die(_("could not read commit message: %s"), strerror(saved_errno));
1824 cleanup_message(&sb, cleanup_mode, verbose);
1826 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1827 rollback_index_files();
1828 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1829 exit(1);
1831 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1832 rollback_index_files();
1833 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1834 exit(1);
1837 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1838 !allow_empty_message) {
1839 struct strbuf body = STRBUF_INIT;
1840 size_t len = commit_subject_length(sb.buf);
1841 strbuf_addstr(&body, sb.buf + len);
1842 if (message_is_empty(&body, cleanup_mode)) {
1843 rollback_index_files();
1844 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1845 exit(1);
1847 strbuf_release(&body);
1850 if (amend) {
1851 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1852 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1853 } else {
1854 struct commit_extra_header **tail = &extra;
1855 append_merge_tag_headers(parents, &tail);
1858 if (commit_tree_extended(sb.buf, sb.len, &the_repository->index->cache_tree->oid,
1859 parents, &oid, author_ident.buf, NULL,
1860 sign_commit, extra)) {
1861 rollback_index_files();
1862 die(_("failed to write commit object"));
1864 free_commit_extra_headers(extra);
1866 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1867 &err)) {
1868 rollback_index_files();
1869 die("%s", err.buf);
1872 sequencer_post_commit_cleanup(the_repository, 0);
1873 unlink(git_path_merge_head(the_repository));
1874 unlink(git_path_merge_msg(the_repository));
1875 unlink(git_path_merge_mode(the_repository));
1876 unlink(git_path_squash_msg(the_repository));
1878 if (commit_index_files())
1879 die(_("repository has been updated, but unable to write\n"
1880 "new index file. Check that disk is not full and quota is\n"
1881 "not exceeded, and then \"git restore --staged :/\" to recover."));
1883 git_test_write_commit_graph_or_die();
1885 repo_rerere(the_repository, 0);
1886 run_auto_maintenance(quiet);
1887 run_commit_hook(use_editor, get_index_file(), NULL, "post-commit",
1888 NULL);
1889 if (amend && !no_post_rewrite) {
1890 commit_post_rewrite(the_repository, current_head, &oid);
1892 if (!quiet) {
1893 unsigned int flags = 0;
1895 if (!current_head)
1896 flags |= SUMMARY_INITIAL_COMMIT;
1897 if (author_date_is_interesting())
1898 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1899 print_commit_summary(the_repository, prefix,
1900 &oid, flags);
1903 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1905 cleanup:
1906 strbuf_release(&author_ident);
1907 strbuf_release(&err);
1908 strbuf_release(&sb);
1909 return ret;