t1502, docs: disallow --no-help
[git/debian.git] / builtin / commit.c
blob7da5f924484d586c765796f8e411a042f2a3817a
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 "diffcore.h"
20 #include "commit.h"
21 #include "gettext.h"
22 #include "revision.h"
23 #include "wt-status.h"
24 #include "run-command.h"
25 #include "hook.h"
26 #include "refs.h"
27 #include "log-tree.h"
28 #include "strbuf.h"
29 #include "utf8.h"
30 #include "object-name.h"
31 #include "parse-options.h"
32 #include "path.h"
33 #include "preload-index.h"
34 #include "read-cache.h"
35 #include "string-list.h"
36 #include "rerere.h"
37 #include "unpack-trees.h"
38 #include "quote.h"
39 #include "submodule.h"
40 #include "gpg-interface.h"
41 #include "column.h"
42 #include "sequencer.h"
43 #include "sparse-index.h"
44 #include "mailmap.h"
45 #include "help.h"
46 #include "commit-reach.h"
47 #include "commit-graph.h"
48 #include "pretty.h"
50 static const char * const builtin_commit_usage[] = {
51 N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]\n"
52 " [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>)]\n"
53 " [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
54 " [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
55 " [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
56 " [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
57 " [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
58 " [--] [<pathspec>...]"),
59 NULL
62 static const char * const builtin_status_usage[] = {
63 N_("git status [<options>] [--] [<pathspec>...]"),
64 NULL
67 static const char empty_amend_advice[] =
68 N_("You asked to amend the most recent commit, but doing so would make\n"
69 "it empty. You can repeat your command with --allow-empty, or you can\n"
70 "remove the commit entirely with \"git reset HEAD^\".\n");
72 static const char empty_cherry_pick_advice[] =
73 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
74 "If you wish to commit it anyway, use:\n"
75 "\n"
76 " git commit --allow-empty\n"
77 "\n");
79 static const char empty_rebase_pick_advice[] =
80 N_("Otherwise, please use 'git rebase --skip'\n");
82 static const char empty_cherry_pick_advice_single[] =
83 N_("Otherwise, please use 'git cherry-pick --skip'\n");
85 static const char empty_cherry_pick_advice_multi[] =
86 N_("and then use:\n"
87 "\n"
88 " git cherry-pick --continue\n"
89 "\n"
90 "to resume cherry-picking the remaining commits.\n"
91 "If you wish to skip this commit, use:\n"
92 "\n"
93 " git cherry-pick --skip\n"
94 "\n");
96 static const char *color_status_slots[] = {
97 [WT_STATUS_HEADER] = "header",
98 [WT_STATUS_UPDATED] = "updated",
99 [WT_STATUS_CHANGED] = "changed",
100 [WT_STATUS_UNTRACKED] = "untracked",
101 [WT_STATUS_NOBRANCH] = "noBranch",
102 [WT_STATUS_UNMERGED] = "unmerged",
103 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
104 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
105 [WT_STATUS_ONBRANCH] = "branch",
108 static const char *use_message_buffer;
109 static struct lock_file index_lock; /* real index */
110 static struct lock_file false_lock; /* used only for partial commits */
111 static enum {
112 COMMIT_AS_IS = 1,
113 COMMIT_NORMAL,
114 COMMIT_PARTIAL
115 } commit_style;
117 static const char *logfile, *force_author;
118 static const char *template_file;
120 * The _message variables are commit names from which to take
121 * the commit message and/or authorship.
123 static const char *author_message, *author_message_buffer;
124 static char *edit_message, *use_message;
125 static char *fixup_message, *fixup_commit, *squash_message;
126 static const char *fixup_prefix;
127 static int all, also, interactive, patch_interactive, only, amend, signoff;
128 static int edit_flag = -1; /* unspecified */
129 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
130 static int config_commit_verbose = -1; /* unspecified */
131 static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
132 static char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
133 static char *sign_commit, *pathspec_from_file;
134 static struct strvec trailer_args = STRVEC_INIT;
137 * The default commit message cleanup mode will remove the lines
138 * beginning with # (shell comments) and leading and trailing
139 * whitespaces (empty lines or containing only whitespaces)
140 * if editor is used, and only the whitespaces if the message
141 * is specified explicitly.
143 static enum commit_msg_cleanup_mode cleanup_mode;
144 static const char *cleanup_arg;
146 static enum commit_whence whence;
147 static int use_editor = 1, include_status = 1;
148 static int have_option_m;
149 static struct strbuf message = STRBUF_INIT;
151 static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
153 static int opt_pass_trailer(const struct option *opt, const char *arg, int unset)
155 BUG_ON_OPT_NEG(unset);
157 strvec_pushl(opt->value, "--trailer", arg, NULL);
158 return 0;
161 static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
163 enum wt_status_format *value = (enum wt_status_format *)opt->value;
164 if (unset)
165 *value = STATUS_FORMAT_NONE;
166 else if (!arg)
167 *value = STATUS_FORMAT_PORCELAIN;
168 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
169 *value = STATUS_FORMAT_PORCELAIN;
170 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
171 *value = STATUS_FORMAT_PORCELAIN_V2;
172 else
173 die("unsupported porcelain version '%s'", arg);
175 return 0;
178 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
180 struct strbuf *buf = opt->value;
181 if (unset) {
182 have_option_m = 0;
183 strbuf_setlen(buf, 0);
184 } else {
185 have_option_m = 1;
186 if (buf->len)
187 strbuf_addch(buf, '\n');
188 strbuf_addstr(buf, arg);
189 strbuf_complete_line(buf);
191 return 0;
194 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
196 const char **value = opt->value;
198 BUG_ON_OPT_NEG(unset);
200 if (arg != NULL && *arg == '=')
201 arg = arg + 1;
203 *value = arg;
204 return 0;
207 static void determine_whence(struct wt_status *s)
209 if (file_exists(git_path_merge_head(the_repository)))
210 whence = FROM_MERGE;
211 else if (!sequencer_determine_whence(the_repository, &whence))
212 whence = FROM_COMMIT;
213 if (s)
214 s->whence = whence;
217 static void status_init_config(struct wt_status *s, config_fn_t fn)
219 wt_status_prepare(the_repository, s);
220 init_diff_ui_defaults();
221 git_config(fn, s);
222 determine_whence(s);
223 s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after git_config() */
226 static void rollback_index_files(void)
228 switch (commit_style) {
229 case COMMIT_AS_IS:
230 break; /* nothing to do */
231 case COMMIT_NORMAL:
232 rollback_lock_file(&index_lock);
233 break;
234 case COMMIT_PARTIAL:
235 rollback_lock_file(&index_lock);
236 rollback_lock_file(&false_lock);
237 break;
241 static int commit_index_files(void)
243 int err = 0;
245 switch (commit_style) {
246 case COMMIT_AS_IS:
247 break; /* nothing to do */
248 case COMMIT_NORMAL:
249 err = commit_lock_file(&index_lock);
250 break;
251 case COMMIT_PARTIAL:
252 err = commit_lock_file(&index_lock);
253 rollback_lock_file(&false_lock);
254 break;
257 return err;
261 * Take a union of paths in the index and the named tree (typically, "HEAD"),
262 * and return the paths that match the given pattern in list.
264 static int list_paths(struct string_list *list, const char *with_tree,
265 const struct pathspec *pattern)
267 int i, ret;
268 char *m;
270 if (!pattern->nr)
271 return 0;
273 m = xcalloc(1, pattern->nr);
275 if (with_tree) {
276 char *max_prefix = common_prefix(pattern);
277 overlay_tree_on_index(&the_index, with_tree, max_prefix);
278 free(max_prefix);
281 /* TODO: audit for interaction with sparse-index. */
282 ensure_full_index(&the_index);
283 for (i = 0; i < the_index.cache_nr; i++) {
284 const struct cache_entry *ce = the_index.cache[i];
285 struct string_list_item *item;
287 if (ce->ce_flags & CE_UPDATE)
288 continue;
289 if (!ce_path_match(&the_index, ce, pattern, m))
290 continue;
291 item = string_list_insert(list, ce->name);
292 if (ce_skip_worktree(ce))
293 item->util = item; /* better a valid pointer than a fake one */
296 ret = report_path_error(m, pattern);
297 free(m);
298 return ret;
301 static void add_remove_files(struct string_list *list)
303 int i;
304 for (i = 0; i < list->nr; i++) {
305 struct stat st;
306 struct string_list_item *p = &(list->items[i]);
308 /* p->util is skip-worktree */
309 if (p->util)
310 continue;
312 if (!lstat(p->string, &st)) {
313 if (add_to_index(&the_index, p->string, &st, 0))
314 die(_("updating files failed"));
315 } else
316 remove_file_from_index(&the_index, p->string);
320 static void create_base_index(const struct commit *current_head)
322 struct tree *tree;
323 struct unpack_trees_options opts;
324 struct tree_desc t;
326 if (!current_head) {
327 discard_index(&the_index);
328 return;
331 memset(&opts, 0, sizeof(opts));
332 opts.head_idx = 1;
333 opts.index_only = 1;
334 opts.merge = 1;
335 opts.src_index = &the_index;
336 opts.dst_index = &the_index;
338 opts.fn = oneway_merge;
339 tree = parse_tree_indirect(&current_head->object.oid);
340 if (!tree)
341 die(_("failed to unpack HEAD tree object"));
342 parse_tree(tree);
343 init_tree_desc(&t, tree->buffer, tree->size);
344 if (unpack_trees(1, &t, &opts))
345 exit(128); /* We've already reported the error, finish dying */
348 static void refresh_cache_or_die(int refresh_flags)
351 * refresh_flags contains REFRESH_QUIET, so the only errors
352 * are for unmerged entries.
354 if (refresh_index(&the_index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
355 die_resolve_conflict("commit");
358 static const char *prepare_index(const char **argv, const char *prefix,
359 const struct commit *current_head, int is_status)
361 struct string_list partial = STRING_LIST_INIT_DUP;
362 struct pathspec pathspec;
363 int refresh_flags = REFRESH_QUIET;
364 const char *ret;
366 if (is_status)
367 refresh_flags |= REFRESH_UNMERGED;
368 parse_pathspec(&pathspec, 0,
369 PATHSPEC_PREFER_FULL,
370 prefix, argv);
372 if (pathspec_from_file) {
373 if (interactive)
374 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
376 if (all)
377 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
379 if (pathspec.nr)
380 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
382 parse_pathspec_file(&pathspec, 0,
383 PATHSPEC_PREFER_FULL,
384 prefix, pathspec_from_file, pathspec_file_nul);
385 } else if (pathspec_file_nul) {
386 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
389 if (!pathspec.nr && (also || (only && !allow_empty &&
390 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
391 die(_("No paths with --include/--only does not make sense."));
393 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
394 die(_("index file corrupt"));
396 if (interactive) {
397 char *old_index_env = NULL, *old_repo_index_file;
398 repo_hold_locked_index(the_repository, &index_lock,
399 LOCK_DIE_ON_ERROR);
401 refresh_cache_or_die(refresh_flags);
403 if (write_locked_index(&the_index, &index_lock, 0))
404 die(_("unable to create temporary index"));
406 old_repo_index_file = the_repository->index_file;
407 the_repository->index_file =
408 (char *)get_lock_file_path(&index_lock);
409 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
410 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
412 if (interactive_add(argv, prefix, patch_interactive) != 0)
413 die(_("interactive add failed"));
415 the_repository->index_file = old_repo_index_file;
416 if (old_index_env && *old_index_env)
417 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
418 else
419 unsetenv(INDEX_ENVIRONMENT);
420 FREE_AND_NULL(old_index_env);
422 discard_index(&the_index);
423 read_index_from(&the_index, get_lock_file_path(&index_lock),
424 get_git_dir());
425 if (cache_tree_update(&the_index, WRITE_TREE_SILENT) == 0) {
426 if (reopen_lock_file(&index_lock) < 0)
427 die(_("unable to write index file"));
428 if (write_locked_index(&the_index, &index_lock, 0))
429 die(_("unable to update temporary index"));
430 } else
431 warning(_("Failed to update main cache tree"));
433 commit_style = COMMIT_NORMAL;
434 ret = get_lock_file_path(&index_lock);
435 goto out;
439 * Non partial, non as-is commit.
441 * (1) get the real index;
442 * (2) update the_index as necessary;
443 * (3) write the_index out to the real index (still locked);
444 * (4) return the name of the locked index file.
446 * The caller should run hooks on the locked real index, and
447 * (A) if all goes well, commit the real index;
448 * (B) on failure, rollback the real index.
450 if (all || (also && pathspec.nr)) {
451 repo_hold_locked_index(the_repository, &index_lock,
452 LOCK_DIE_ON_ERROR);
453 add_files_to_cache(the_repository, also ? prefix : NULL,
454 &pathspec, 0, 0);
455 refresh_cache_or_die(refresh_flags);
456 cache_tree_update(&the_index, WRITE_TREE_SILENT);
457 if (write_locked_index(&the_index, &index_lock, 0))
458 die(_("unable to write new_index file"));
459 commit_style = COMMIT_NORMAL;
460 ret = get_lock_file_path(&index_lock);
461 goto out;
465 * As-is commit.
467 * (1) return the name of the real index file.
469 * The caller should run hooks on the real index,
470 * and create commit from the_index.
471 * We still need to refresh the index here.
473 if (!only && !pathspec.nr) {
474 repo_hold_locked_index(the_repository, &index_lock,
475 LOCK_DIE_ON_ERROR);
476 refresh_cache_or_die(refresh_flags);
477 if (the_index.cache_changed
478 || !cache_tree_fully_valid(the_index.cache_tree))
479 cache_tree_update(&the_index, WRITE_TREE_SILENT);
480 if (write_locked_index(&the_index, &index_lock,
481 COMMIT_LOCK | SKIP_IF_UNCHANGED))
482 die(_("unable to write new_index file"));
483 commit_style = COMMIT_AS_IS;
484 ret = get_index_file();
485 goto out;
489 * A partial commit.
491 * (0) find the set of affected paths;
492 * (1) get lock on the real index file;
493 * (2) update the_index with the given paths;
494 * (3) write the_index out to the real index (still locked);
495 * (4) get lock on the false index file;
496 * (5) reset the_index from HEAD;
497 * (6) update the_index the same way as (2);
498 * (7) write the_index out to the false index file;
499 * (8) return the name of the false index file (still locked);
501 * The caller should run hooks on the locked false index, and
502 * create commit from it. Then
503 * (A) if all goes well, commit the real index;
504 * (B) on failure, rollback the real index;
505 * In either case, rollback the false index.
507 commit_style = COMMIT_PARTIAL;
509 if (whence != FROM_COMMIT) {
510 if (whence == FROM_MERGE)
511 die(_("cannot do a partial commit during a merge."));
512 else if (is_from_cherry_pick(whence))
513 die(_("cannot do a partial commit during a cherry-pick."));
514 else if (is_from_rebase(whence))
515 die(_("cannot do a partial commit during a rebase."));
518 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
519 exit(1);
521 discard_index(&the_index);
522 if (repo_read_index(the_repository) < 0)
523 die(_("cannot read the index"));
525 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
526 add_remove_files(&partial);
527 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
528 cache_tree_update(&the_index, WRITE_TREE_SILENT);
529 if (write_locked_index(&the_index, &index_lock, 0))
530 die(_("unable to write new_index file"));
532 hold_lock_file_for_update(&false_lock,
533 git_path("next-index-%"PRIuMAX,
534 (uintmax_t) getpid()),
535 LOCK_DIE_ON_ERROR);
537 create_base_index(current_head);
538 add_remove_files(&partial);
539 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
541 if (write_locked_index(&the_index, &false_lock, 0))
542 die(_("unable to write temporary index file"));
544 discard_index(&the_index);
545 ret = get_lock_file_path(&false_lock);
546 read_index_from(&the_index, ret, get_git_dir());
547 out:
548 string_list_clear(&partial, 0);
549 clear_pathspec(&pathspec);
550 return ret;
553 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
554 struct wt_status *s)
556 struct object_id oid;
558 if (s->relative_paths)
559 s->prefix = prefix;
561 if (amend) {
562 s->amend = 1;
563 s->reference = "HEAD^1";
565 s->verbose = verbose;
566 s->index_file = index_file;
567 s->fp = fp;
568 s->nowarn = nowarn;
569 s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
570 if (!s->is_initial)
571 oidcpy(&s->oid_commit, &oid);
572 s->status_format = status_format;
573 s->ignore_submodule_arg = ignore_submodule_arg;
575 wt_status_collect(s);
576 wt_status_print(s);
577 wt_status_collect_free_buffers(s);
579 return s->committable;
582 static int is_a_merge(const struct commit *current_head)
584 return !!(current_head->parents && current_head->parents->next);
587 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
589 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
590 BUG("unable to parse our own ident: %s", buf->buf);
593 static void export_one(const char *var, const char *s, const char *e, int hack)
595 struct strbuf buf = STRBUF_INIT;
596 if (hack)
597 strbuf_addch(&buf, hack);
598 strbuf_add(&buf, s, e - s);
599 setenv(var, buf.buf, 1);
600 strbuf_release(&buf);
603 static int parse_force_date(const char *in, struct strbuf *out)
605 strbuf_addch(out, '@');
607 if (parse_date(in, out) < 0) {
608 int errors = 0;
609 unsigned long t = approxidate_careful(in, &errors);
610 if (errors)
611 return -1;
612 strbuf_addf(out, "%lu", t);
615 return 0;
618 static void set_ident_var(char **buf, char *val)
620 free(*buf);
621 *buf = val;
624 static void determine_author_info(struct strbuf *author_ident)
626 char *name, *email, *date;
627 struct ident_split author;
629 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
630 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
631 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
633 if (author_message) {
634 struct ident_split ident;
635 size_t len;
636 const char *a;
638 a = find_commit_header(author_message_buffer, "author", &len);
639 if (!a)
640 die(_("commit '%s' lacks author header"), author_message);
641 if (split_ident_line(&ident, a, len) < 0)
642 die(_("commit '%s' has malformed author line"), author_message);
644 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
645 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
647 if (ident.date_begin) {
648 struct strbuf date_buf = STRBUF_INIT;
649 strbuf_addch(&date_buf, '@');
650 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
651 strbuf_addch(&date_buf, ' ');
652 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
653 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
657 if (force_author) {
658 struct ident_split ident;
660 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
661 die(_("malformed --author parameter"));
662 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
663 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
666 if (force_date) {
667 struct strbuf date_buf = STRBUF_INIT;
668 if (parse_force_date(force_date, &date_buf))
669 die(_("invalid date format: %s"), force_date);
670 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
673 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
674 IDENT_STRICT));
675 assert_split_ident(&author, author_ident);
676 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
677 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
678 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
679 free(name);
680 free(email);
681 free(date);
684 static int author_date_is_interesting(void)
686 return author_message || force_date;
689 static void adjust_comment_line_char(const struct strbuf *sb)
691 char candidates[] = "#;@!$%^&|:";
692 char *candidate;
693 const char *p;
695 comment_line_char = candidates[0];
696 if (!memchr(sb->buf, comment_line_char, sb->len))
697 return;
699 p = sb->buf;
700 candidate = strchr(candidates, *p);
701 if (candidate)
702 *candidate = ' ';
703 for (p = sb->buf; *p; p++) {
704 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
705 candidate = strchr(candidates, p[1]);
706 if (candidate)
707 *candidate = ' ';
711 for (p = candidates; *p == ' '; p++)
713 if (!*p)
714 die(_("unable to select a comment character that is not used\n"
715 "in the current commit message"));
716 comment_line_char = *p;
719 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
720 struct pretty_print_context *ctx)
722 const char *buffer, *subject, *fmt;
724 buffer = repo_get_commit_buffer(the_repository, commit, NULL);
725 find_commit_subject(buffer, &subject);
727 * If we amend the 'amend!' commit then we don't want to
728 * duplicate the subject line.
730 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
731 repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
732 repo_unuse_commit_buffer(the_repository, commit, buffer);
735 static int prepare_to_commit(const char *index_file, const char *prefix,
736 struct commit *current_head,
737 struct wt_status *s,
738 struct strbuf *author_ident)
740 struct stat statbuf;
741 struct strbuf committer_ident = STRBUF_INIT;
742 int committable;
743 struct strbuf sb = STRBUF_INIT;
744 const char *hook_arg1 = NULL;
745 const char *hook_arg2 = NULL;
746 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
747 int old_display_comment_prefix;
748 int merge_contains_scissors = 0;
749 int invoked_hook;
751 /* This checks and barfs if author is badly specified */
752 determine_author_info(author_ident);
754 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
755 "pre-commit", NULL))
756 return 0;
758 if (squash_message) {
760 * Insert the proper subject line before other commit
761 * message options add their content.
763 if (use_message && !strcmp(use_message, squash_message))
764 strbuf_addstr(&sb, "squash! ");
765 else {
766 struct pretty_print_context ctx = {0};
767 struct commit *c;
768 c = lookup_commit_reference_by_name(squash_message);
769 if (!c)
770 die(_("could not lookup commit '%s'"), squash_message);
771 ctx.output_encoding = get_commit_output_encoding();
772 repo_format_commit_message(the_repository, c,
773 "squash! %s\n\n", &sb,
774 &ctx);
778 if (have_option_m && !fixup_message) {
779 strbuf_addbuf(&sb, &message);
780 hook_arg1 = "message";
781 } else if (logfile && !strcmp(logfile, "-")) {
782 if (isatty(0))
783 fprintf(stderr, _("(reading log message from standard input)\n"));
784 if (strbuf_read(&sb, 0, 0) < 0)
785 die_errno(_("could not read log from standard input"));
786 hook_arg1 = "message";
787 } else if (logfile) {
788 if (strbuf_read_file(&sb, logfile, 0) < 0)
789 die_errno(_("could not read log file '%s'"),
790 logfile);
791 hook_arg1 = "message";
792 } else if (use_message) {
793 char *buffer;
794 buffer = strstr(use_message_buffer, "\n\n");
795 if (buffer)
796 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
797 hook_arg1 = "commit";
798 hook_arg2 = use_message;
799 } else if (fixup_message) {
800 struct pretty_print_context ctx = {0};
801 struct commit *commit;
802 char *fmt;
803 commit = lookup_commit_reference_by_name(fixup_commit);
804 if (!commit)
805 die(_("could not lookup commit '%s'"), fixup_commit);
806 ctx.output_encoding = get_commit_output_encoding();
807 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
808 repo_format_commit_message(the_repository, commit, fmt, &sb,
809 &ctx);
810 free(fmt);
811 hook_arg1 = "message";
814 * Only `-m` commit message option is checked here, as
815 * it supports `--fixup` to append the commit message.
817 * The other commit message options `-c`/`-C`/`-F` are
818 * incompatible with all the forms of `--fixup` and
819 * have already errored out while parsing the `git commit`
820 * options.
822 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
823 strbuf_addbuf(&sb, &message);
825 if (!strcmp(fixup_prefix, "amend")) {
826 if (have_option_m)
827 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
828 prepare_amend_commit(commit, &sb, &ctx);
830 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
831 size_t merge_msg_start;
834 * prepend SQUASH_MSG here if it exists and a
835 * "merge --squash" was originally performed
837 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
838 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
839 die_errno(_("could not read SQUASH_MSG"));
840 hook_arg1 = "squash";
841 } else
842 hook_arg1 = "merge";
844 merge_msg_start = sb.len;
845 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
846 die_errno(_("could not read MERGE_MSG"));
848 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
849 wt_status_locate_end(sb.buf + merge_msg_start,
850 sb.len - merge_msg_start) <
851 sb.len - merge_msg_start)
852 merge_contains_scissors = 1;
853 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
854 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
855 die_errno(_("could not read SQUASH_MSG"));
856 hook_arg1 = "squash";
857 } else if (template_file) {
858 if (strbuf_read_file(&sb, template_file, 0) < 0)
859 die_errno(_("could not read '%s'"), template_file);
860 hook_arg1 = "template";
861 clean_message_contents = 0;
865 * The remaining cases don't modify the template message, but
866 * just set the argument(s) to the prepare-commit-msg hook.
868 else if (whence == FROM_MERGE)
869 hook_arg1 = "merge";
870 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
871 hook_arg1 = "commit";
872 hook_arg2 = "CHERRY_PICK_HEAD";
875 if (squash_message) {
877 * If squash_commit was used for the commit subject,
878 * then we're possibly hijacking other commit log options.
879 * Reset the hook args to tell the real story.
881 hook_arg1 = "message";
882 hook_arg2 = "";
885 s->fp = fopen_for_writing(git_path_commit_editmsg());
886 if (!s->fp)
887 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
889 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
890 old_display_comment_prefix = s->display_comment_prefix;
891 s->display_comment_prefix = 1;
894 * Most hints are counter-productive when the commit has
895 * already started.
897 s->hints = 0;
899 if (clean_message_contents)
900 strbuf_stripspace(&sb, '\0');
902 if (signoff)
903 append_signoff(&sb, ignore_non_trailer(sb.buf, sb.len), 0);
905 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
906 die_errno(_("could not write commit template"));
908 if (auto_comment_line_char)
909 adjust_comment_line_char(&sb);
910 strbuf_release(&sb);
912 /* This checks if committer ident is explicitly given */
913 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
914 if (use_editor && include_status) {
915 int ident_shown = 0;
916 int saved_color_setting;
917 struct ident_split ci, ai;
918 const char *hint_cleanup_all = allow_empty_message ?
919 _("Please enter the commit message for your changes."
920 " Lines starting\nwith '%c' will be ignored.\n") :
921 _("Please enter the commit message for your changes."
922 " Lines starting\nwith '%c' will be ignored, and an empty"
923 " message aborts the commit.\n");
924 const char *hint_cleanup_space = allow_empty_message ?
925 _("Please enter the commit message for your changes."
926 " Lines starting\n"
927 "with '%c' will be kept; you may remove them"
928 " yourself if you want to.\n") :
929 _("Please enter the commit message for your changes."
930 " Lines starting\n"
931 "with '%c' will be kept; you may remove them"
932 " yourself if you want to.\n"
933 "An empty message aborts the commit.\n");
934 if (whence != FROM_COMMIT) {
935 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
936 !merge_contains_scissors)
937 wt_status_add_cut_line(s->fp);
938 status_printf_ln(
939 s, GIT_COLOR_NORMAL,
940 whence == FROM_MERGE ?
941 _("\n"
942 "It looks like you may be committing a merge.\n"
943 "If this is not correct, please run\n"
944 " git update-ref -d MERGE_HEAD\n"
945 "and try again.\n") :
946 _("\n"
947 "It looks like you may be committing a cherry-pick.\n"
948 "If this is not correct, please run\n"
949 " git update-ref -d CHERRY_PICK_HEAD\n"
950 "and try again.\n"));
953 fprintf(s->fp, "\n");
954 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
955 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_char);
956 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
957 if (whence == FROM_COMMIT && !merge_contains_scissors)
958 wt_status_add_cut_line(s->fp);
959 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
960 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_char);
963 * These should never fail because they come from our own
964 * fmt_ident. They may fail the sane_ident test, but we know
965 * that the name and mail pointers will at least be valid,
966 * which is enough for our tests and printing here.
968 assert_split_ident(&ai, author_ident);
969 assert_split_ident(&ci, &committer_ident);
971 if (ident_cmp(&ai, &ci))
972 status_printf_ln(s, GIT_COLOR_NORMAL,
973 _("%s"
974 "Author: %.*s <%.*s>"),
975 ident_shown++ ? "" : "\n",
976 (int)(ai.name_end - ai.name_begin), ai.name_begin,
977 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
979 if (author_date_is_interesting())
980 status_printf_ln(s, GIT_COLOR_NORMAL,
981 _("%s"
982 "Date: %s"),
983 ident_shown++ ? "" : "\n",
984 show_ident_date(&ai, DATE_MODE(NORMAL)));
986 if (!committer_ident_sufficiently_given())
987 status_printf_ln(s, GIT_COLOR_NORMAL,
988 _("%s"
989 "Committer: %.*s <%.*s>"),
990 ident_shown++ ? "" : "\n",
991 (int)(ci.name_end - ci.name_begin), ci.name_begin,
992 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
994 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
996 saved_color_setting = s->use_color;
997 s->use_color = 0;
998 committable = run_status(s->fp, index_file, prefix, 1, s);
999 s->use_color = saved_color_setting;
1000 string_list_clear(&s->change, 1);
1001 } else {
1002 struct object_id oid;
1003 const char *parent = "HEAD";
1005 if (!the_index.initialized && repo_read_index(the_repository) < 0)
1006 die(_("Cannot read index"));
1008 if (amend)
1009 parent = "HEAD^1";
1011 if (repo_get_oid(the_repository, parent, &oid)) {
1012 int i, ita_nr = 0;
1014 /* TODO: audit for interaction with sparse-index. */
1015 ensure_full_index(&the_index);
1016 for (i = 0; i < the_index.cache_nr; i++)
1017 if (ce_intent_to_add(the_index.cache[i]))
1018 ita_nr++;
1019 committable = the_index.cache_nr - ita_nr > 0;
1020 } else {
1022 * Unless the user did explicitly request a submodule
1023 * ignore mode by passing a command line option we do
1024 * not ignore any changed submodule SHA-1s when
1025 * comparing index and parent, no matter what is
1026 * configured. Otherwise we won't commit any
1027 * submodules which were manually staged, which would
1028 * be really confusing.
1030 struct diff_flags flags = DIFF_FLAGS_INIT;
1031 flags.override_submodule_config = 1;
1032 if (ignore_submodule_arg &&
1033 !strcmp(ignore_submodule_arg, "all"))
1034 flags.ignore_submodules = 1;
1035 committable = index_differs_from(the_repository,
1036 parent, &flags, 1);
1039 strbuf_release(&committer_ident);
1041 fclose(s->fp);
1043 if (trailer_args.nr) {
1044 struct child_process run_trailer = CHILD_PROCESS_INIT;
1046 strvec_pushl(&run_trailer.args, "interpret-trailers",
1047 "--in-place", "--no-divider",
1048 git_path_commit_editmsg(), NULL);
1049 strvec_pushv(&run_trailer.args, trailer_args.v);
1050 run_trailer.git_cmd = 1;
1051 if (run_command(&run_trailer))
1052 die(_("unable to pass trailers to --trailers"));
1053 strvec_clear(&trailer_args);
1057 * Reject an attempt to record a non-merge empty commit without
1058 * explicit --allow-empty. In the cherry-pick case, it may be
1059 * empty due to conflict resolution, which the user should okay.
1061 if (!committable && whence != FROM_MERGE && !allow_empty &&
1062 !(amend && is_a_merge(current_head))) {
1063 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1064 s->display_comment_prefix = old_display_comment_prefix;
1065 run_status(stdout, index_file, prefix, 0, s);
1066 if (amend)
1067 fputs(_(empty_amend_advice), stderr);
1068 else if (is_from_cherry_pick(whence) ||
1069 whence == FROM_REBASE_PICK) {
1070 fputs(_(empty_cherry_pick_advice), stderr);
1071 if (whence == FROM_CHERRY_PICK_SINGLE)
1072 fputs(_(empty_cherry_pick_advice_single), stderr);
1073 else if (whence == FROM_CHERRY_PICK_MULTI)
1074 fputs(_(empty_cherry_pick_advice_multi), stderr);
1075 else
1076 fputs(_(empty_rebase_pick_advice), stderr);
1078 return 0;
1081 if (!no_verify && invoked_hook) {
1083 * Re-read the index as the pre-commit-commit hook was invoked
1084 * and could have updated it. We must do this before we invoke
1085 * the editor and after we invoke run_status above.
1087 discard_index(&the_index);
1089 read_index_from(&the_index, index_file, get_git_dir());
1091 if (cache_tree_update(&the_index, 0)) {
1092 error(_("Error building trees"));
1093 return 0;
1096 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1097 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1098 return 0;
1100 if (use_editor) {
1101 struct strvec env = STRVEC_INIT;
1103 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1104 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1105 fprintf(stderr,
1106 _("Please supply the message using either -m or -F option.\n"));
1107 exit(1);
1109 strvec_clear(&env);
1112 if (!no_verify &&
1113 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1114 git_path_commit_editmsg(), NULL)) {
1115 return 0;
1118 return 1;
1121 static const char *find_author_by_nickname(const char *name)
1123 struct rev_info revs;
1124 struct commit *commit;
1125 struct strbuf buf = STRBUF_INIT;
1126 const char *av[20];
1127 int ac = 0;
1129 repo_init_revisions(the_repository, &revs, NULL);
1130 strbuf_addf(&buf, "--author=%s", name);
1131 av[++ac] = "--all";
1132 av[++ac] = "-i";
1133 av[++ac] = buf.buf;
1134 av[++ac] = NULL;
1135 setup_revisions(ac, av, &revs, NULL);
1136 revs.mailmap = xmalloc(sizeof(struct string_list));
1137 string_list_init_nodup(revs.mailmap);
1138 read_mailmap(revs.mailmap);
1140 if (prepare_revision_walk(&revs))
1141 die(_("revision walk setup failed"));
1142 commit = get_revision(&revs);
1143 if (commit) {
1144 struct pretty_print_context ctx = {0};
1145 ctx.date_mode.type = DATE_NORMAL;
1146 strbuf_release(&buf);
1147 repo_format_commit_message(the_repository, commit,
1148 "%aN <%aE>", &buf, &ctx);
1149 release_revisions(&revs);
1150 return strbuf_detach(&buf, NULL);
1152 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1155 static void handle_ignored_arg(struct wt_status *s)
1157 if (!ignored_arg)
1158 ; /* default already initialized */
1159 else if (!strcmp(ignored_arg, "traditional"))
1160 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1161 else if (!strcmp(ignored_arg, "no"))
1162 s->show_ignored_mode = SHOW_NO_IGNORED;
1163 else if (!strcmp(ignored_arg, "matching"))
1164 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1165 else
1166 die(_("Invalid ignored mode '%s'"), ignored_arg);
1169 static void handle_untracked_files_arg(struct wt_status *s)
1171 if (!untracked_files_arg)
1172 ; /* default already initialized */
1173 else if (!strcmp(untracked_files_arg, "no"))
1174 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1175 else if (!strcmp(untracked_files_arg, "normal"))
1176 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1177 else if (!strcmp(untracked_files_arg, "all"))
1178 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1180 * Please update $__git_untracked_file_modes in
1181 * git-completion.bash when you add new options
1183 else
1184 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1187 static const char *read_commit_message(const char *name)
1189 const char *out_enc;
1190 struct commit *commit;
1192 commit = lookup_commit_reference_by_name(name);
1193 if (!commit)
1194 die(_("could not lookup commit '%s'"), name);
1195 out_enc = get_commit_output_encoding();
1196 return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1200 * Enumerate what needs to be propagated when --porcelain
1201 * is not in effect here.
1203 static struct status_deferred_config {
1204 enum wt_status_format status_format;
1205 int show_branch;
1206 enum ahead_behind_flags ahead_behind;
1207 } status_deferred_config = {
1208 STATUS_FORMAT_UNSPECIFIED,
1209 -1, /* unspecified */
1210 AHEAD_BEHIND_UNSPECIFIED,
1213 static void finalize_deferred_config(struct wt_status *s)
1215 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1216 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1217 !s->null_termination);
1219 if (s->null_termination) {
1220 if (status_format == STATUS_FORMAT_NONE ||
1221 status_format == STATUS_FORMAT_UNSPECIFIED)
1222 status_format = STATUS_FORMAT_PORCELAIN;
1223 else if (status_format == STATUS_FORMAT_LONG)
1224 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1227 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1228 status_format = status_deferred_config.status_format;
1229 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1230 status_format = STATUS_FORMAT_NONE;
1232 if (use_deferred_config && s->show_branch < 0)
1233 s->show_branch = status_deferred_config.show_branch;
1234 if (s->show_branch < 0)
1235 s->show_branch = 0;
1238 * If the user did not give a "--[no]-ahead-behind" command
1239 * line argument *AND* we will print in a human-readable format
1240 * (short, long etc.) then we inherit from the status.aheadbehind
1241 * config setting. In all other cases (and porcelain V[12] formats
1242 * in particular), we inherit _FULL for backwards compatibility.
1244 if (use_deferred_config &&
1245 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1246 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1248 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1249 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1252 static void check_fixup_reword_options(int argc, const char *argv[]) {
1253 if (whence != FROM_COMMIT) {
1254 if (whence == FROM_MERGE)
1255 die(_("You are in the middle of a merge -- cannot reword."));
1256 else if (is_from_cherry_pick(whence))
1257 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1259 if (argc)
1260 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1261 if (patch_interactive || interactive || all || also || only)
1262 die(_("reword option of '%s' and '%s' cannot be used together"),
1263 "--fixup", "--patch/--interactive/--all/--include/--only");
1266 static int parse_and_validate_options(int argc, const char *argv[],
1267 const struct option *options,
1268 const char * const usage[],
1269 const char *prefix,
1270 struct commit *current_head,
1271 struct wt_status *s)
1273 argc = parse_options(argc, argv, prefix, options, usage, 0);
1274 finalize_deferred_config(s);
1276 if (force_author && !strchr(force_author, '>'))
1277 force_author = find_author_by_nickname(force_author);
1279 if (force_author && renew_authorship)
1280 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1282 if (logfile || have_option_m || use_message)
1283 use_editor = 0;
1285 /* Sanity check options */
1286 if (amend && !current_head)
1287 die(_("You have nothing to amend."));
1288 if (amend && whence != FROM_COMMIT) {
1289 if (whence == FROM_MERGE)
1290 die(_("You are in the middle of a merge -- cannot amend."));
1291 else if (is_from_cherry_pick(whence))
1292 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1293 else if (whence == FROM_REBASE_PICK)
1294 die(_("You are in the middle of a rebase -- cannot amend."));
1296 if (fixup_message && squash_message)
1297 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1298 die_for_incompatible_opt4(!!use_message, "-C",
1299 !!edit_message, "-c",
1300 !!logfile, "-F",
1301 !!fixup_message, "--fixup");
1302 die_for_incompatible_opt4(have_option_m, "-m",
1303 !!edit_message, "-c",
1304 !!use_message, "-C",
1305 !!logfile, "-F");
1306 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1307 template_file = NULL;
1308 if (edit_message)
1309 use_message = edit_message;
1310 if (amend && !use_message && !fixup_message)
1311 use_message = "HEAD";
1312 if (!use_message && !is_from_cherry_pick(whence) &&
1313 !is_from_rebase(whence) && renew_authorship)
1314 die(_("--reset-author can be used only with -C, -c or --amend."));
1315 if (use_message) {
1316 use_message_buffer = read_commit_message(use_message);
1317 if (!renew_authorship) {
1318 author_message = use_message;
1319 author_message_buffer = use_message_buffer;
1322 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1323 !renew_authorship) {
1324 author_message = "CHERRY_PICK_HEAD";
1325 author_message_buffer = read_commit_message(author_message);
1328 if (patch_interactive)
1329 interactive = 1;
1331 die_for_incompatible_opt4(also, "-i/--include",
1332 only, "-o/--only",
1333 all, "-a/--all",
1334 interactive, "--interactive/-p/--patch");
1335 if (fixup_message) {
1337 * We limit --fixup's suboptions to only alpha characters.
1338 * If the first character after a run of alpha is colon,
1339 * then the part before the colon may be a known suboption
1340 * name like `amend` or `reword`, or a misspelt suboption
1341 * name. In either case, we treat it as
1342 * --fixup=<suboption>:<arg>.
1344 * Otherwise, we are dealing with --fixup=<commit>.
1346 char *p = fixup_message;
1347 while (isalpha(*p))
1348 p++;
1349 if (p > fixup_message && *p == ':') {
1350 *p = '\0';
1351 fixup_commit = p + 1;
1352 if (!strcmp("amend", fixup_message) ||
1353 !strcmp("reword", fixup_message)) {
1354 fixup_prefix = "amend";
1355 allow_empty = 1;
1356 if (*fixup_message == 'r') {
1357 check_fixup_reword_options(argc, argv);
1358 only = 1;
1360 } else {
1361 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1363 } else {
1364 fixup_commit = fixup_message;
1365 fixup_prefix = "fixup";
1366 use_editor = 0;
1370 if (0 <= edit_flag)
1371 use_editor = edit_flag;
1373 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1375 handle_untracked_files_arg(s);
1377 if (all && argc > 0)
1378 die(_("paths '%s ...' with -a does not make sense"),
1379 argv[0]);
1381 if (status_format != STATUS_FORMAT_NONE)
1382 dry_run = 1;
1384 return argc;
1387 static int dry_run_commit(const char **argv, const char *prefix,
1388 const struct commit *current_head, struct wt_status *s)
1390 int committable;
1391 const char *index_file;
1393 index_file = prepare_index(argv, prefix, current_head, 1);
1394 committable = run_status(stdout, index_file, prefix, 0, s);
1395 rollback_index_files();
1397 return committable ? 0 : 1;
1400 define_list_config_array_extra(color_status_slots, {"added"});
1402 static int parse_status_slot(const char *slot)
1404 if (!strcasecmp(slot, "added"))
1405 return WT_STATUS_UPDATED;
1407 return LOOKUP_CONFIG(color_status_slots, slot);
1410 static int git_status_config(const char *k, const char *v,
1411 const struct config_context *ctx, void *cb)
1413 struct wt_status *s = cb;
1414 const char *slot_name;
1416 if (starts_with(k, "column."))
1417 return git_column_config(k, v, "status", &s->colopts);
1418 if (!strcmp(k, "status.submodulesummary")) {
1419 int is_bool;
1420 s->submodule_summary = git_config_bool_or_int(k, v, ctx->kvi,
1421 &is_bool);
1422 if (is_bool && s->submodule_summary)
1423 s->submodule_summary = -1;
1424 return 0;
1426 if (!strcmp(k, "status.short")) {
1427 if (git_config_bool(k, v))
1428 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1429 else
1430 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1431 return 0;
1433 if (!strcmp(k, "status.branch")) {
1434 status_deferred_config.show_branch = git_config_bool(k, v);
1435 return 0;
1437 if (!strcmp(k, "status.aheadbehind")) {
1438 status_deferred_config.ahead_behind = git_config_bool(k, v);
1439 return 0;
1441 if (!strcmp(k, "status.showstash")) {
1442 s->show_stash = git_config_bool(k, v);
1443 return 0;
1445 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1446 s->use_color = git_config_colorbool(k, v);
1447 return 0;
1449 if (!strcmp(k, "status.displaycommentprefix")) {
1450 s->display_comment_prefix = git_config_bool(k, v);
1451 return 0;
1453 if (skip_prefix(k, "status.color.", &slot_name) ||
1454 skip_prefix(k, "color.status.", &slot_name)) {
1455 int slot = parse_status_slot(slot_name);
1456 if (slot < 0)
1457 return 0;
1458 if (!v)
1459 return config_error_nonbool(k);
1460 return color_parse(v, s->color_palette[slot]);
1462 if (!strcmp(k, "status.relativepaths")) {
1463 s->relative_paths = git_config_bool(k, v);
1464 return 0;
1466 if (!strcmp(k, "status.showuntrackedfiles")) {
1467 if (!v)
1468 return config_error_nonbool(k);
1469 else if (!strcmp(v, "no"))
1470 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1471 else if (!strcmp(v, "normal"))
1472 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1473 else if (!strcmp(v, "all"))
1474 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1475 else
1476 return error(_("Invalid untracked files mode '%s'"), v);
1477 return 0;
1479 if (!strcmp(k, "diff.renamelimit")) {
1480 if (s->rename_limit == -1)
1481 s->rename_limit = git_config_int(k, v, ctx->kvi);
1482 return 0;
1484 if (!strcmp(k, "status.renamelimit")) {
1485 s->rename_limit = git_config_int(k, v, ctx->kvi);
1486 return 0;
1488 if (!strcmp(k, "diff.renames")) {
1489 if (s->detect_rename == -1)
1490 s->detect_rename = git_config_rename(k, v);
1491 return 0;
1493 if (!strcmp(k, "status.renames")) {
1494 s->detect_rename = git_config_rename(k, v);
1495 return 0;
1497 return git_diff_ui_config(k, v, ctx, NULL);
1500 int cmd_status(int argc, const char **argv, const char *prefix)
1502 static int no_renames = -1;
1503 static const char *rename_score_arg = (const char *)-1;
1504 static struct wt_status s;
1505 unsigned int progress_flag = 0;
1506 int fd;
1507 struct object_id oid;
1508 static struct option builtin_status_options[] = {
1509 OPT__VERBOSE(&verbose, N_("be verbose")),
1510 OPT_SET_INT('s', "short", &status_format,
1511 N_("show status concisely"), STATUS_FORMAT_SHORT),
1512 OPT_BOOL('b', "branch", &s.show_branch,
1513 N_("show branch information")),
1514 OPT_BOOL(0, "show-stash", &s.show_stash,
1515 N_("show stash information")),
1516 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1517 N_("compute full ahead/behind values")),
1518 OPT_CALLBACK_F(0, "porcelain", &status_format,
1519 N_("version"), N_("machine-readable output"),
1520 PARSE_OPT_OPTARG, opt_parse_porcelain),
1521 OPT_SET_INT(0, "long", &status_format,
1522 N_("show status in long format (default)"),
1523 STATUS_FORMAT_LONG),
1524 OPT_BOOL('z', "null", &s.null_termination,
1525 N_("terminate entries with NUL")),
1526 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1527 N_("mode"),
1528 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1529 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1530 { OPTION_STRING, 0, "ignored", &ignored_arg,
1531 N_("mode"),
1532 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1533 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1534 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1535 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1536 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1537 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1538 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1539 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1540 N_("n"), N_("detect renames, optionally set similarity index"),
1541 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1542 OPT_END(),
1545 if (argc == 2 && !strcmp(argv[1], "-h"))
1546 usage_with_options(builtin_status_usage, builtin_status_options);
1548 prepare_repo_settings(the_repository);
1549 the_repository->settings.command_requires_full_index = 0;
1551 status_init_config(&s, git_status_config);
1552 argc = parse_options(argc, argv, prefix,
1553 builtin_status_options,
1554 builtin_status_usage, 0);
1555 finalize_colopts(&s.colopts, -1);
1556 finalize_deferred_config(&s);
1558 handle_untracked_files_arg(&s);
1559 handle_ignored_arg(&s);
1561 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1562 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1563 die(_("Unsupported combination of ignored and untracked-files arguments"));
1565 parse_pathspec(&s.pathspec, 0,
1566 PATHSPEC_PREFER_FULL,
1567 prefix, argv);
1569 if (status_format != STATUS_FORMAT_PORCELAIN &&
1570 status_format != STATUS_FORMAT_PORCELAIN_V2)
1571 progress_flag = REFRESH_PROGRESS;
1572 repo_read_index(the_repository);
1573 refresh_index(&the_index,
1574 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1575 &s.pathspec, NULL, NULL);
1577 if (use_optional_locks())
1578 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1579 else
1580 fd = -1;
1582 s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1583 if (!s.is_initial)
1584 oidcpy(&s.oid_commit, &oid);
1586 s.ignore_submodule_arg = ignore_submodule_arg;
1587 s.status_format = status_format;
1588 s.verbose = verbose;
1589 if (no_renames != -1)
1590 s.detect_rename = !no_renames;
1591 if ((intptr_t)rename_score_arg != -1) {
1592 if (s.detect_rename < DIFF_DETECT_RENAME)
1593 s.detect_rename = DIFF_DETECT_RENAME;
1594 if (rename_score_arg)
1595 s.rename_score = parse_rename_score(&rename_score_arg);
1598 wt_status_collect(&s);
1600 if (0 <= fd)
1601 repo_update_index_if_able(the_repository, &index_lock);
1603 if (s.relative_paths)
1604 s.prefix = prefix;
1606 wt_status_print(&s);
1607 wt_status_collect_free_buffers(&s);
1609 return 0;
1612 static int git_commit_config(const char *k, const char *v,
1613 const struct config_context *ctx, void *cb)
1615 struct wt_status *s = cb;
1617 if (!strcmp(k, "commit.template"))
1618 return git_config_pathname(&template_file, k, v);
1619 if (!strcmp(k, "commit.status")) {
1620 include_status = git_config_bool(k, v);
1621 return 0;
1623 if (!strcmp(k, "commit.cleanup"))
1624 return git_config_string(&cleanup_arg, k, v);
1625 if (!strcmp(k, "commit.gpgsign")) {
1626 sign_commit = git_config_bool(k, v) ? "" : NULL;
1627 return 0;
1629 if (!strcmp(k, "commit.verbose")) {
1630 int is_bool;
1631 config_commit_verbose = git_config_bool_or_int(k, v, ctx->kvi,
1632 &is_bool);
1633 return 0;
1636 return git_status_config(k, v, ctx, s);
1639 int cmd_commit(int argc, const char **argv, const char *prefix)
1641 static struct wt_status s;
1642 static struct option builtin_commit_options[] = {
1643 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1644 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1646 OPT_GROUP(N_("Commit message options")),
1647 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1648 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1649 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1650 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1651 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1652 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1654 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1655 * and only translate <commit>.
1657 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1658 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1659 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1660 OPT_CALLBACK_F(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG, opt_pass_trailer),
1661 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1662 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1663 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1664 OPT_CLEANUP(&cleanup_arg),
1665 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1666 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1667 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1668 /* end commit message options */
1670 OPT_GROUP(N_("Commit contents options")),
1671 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1672 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1673 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1674 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1675 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1676 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1677 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1678 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1679 STATUS_FORMAT_SHORT),
1680 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1681 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1682 N_("compute full ahead/behind values")),
1683 OPT_SET_INT(0, "porcelain", &status_format,
1684 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1685 OPT_SET_INT(0, "long", &status_format,
1686 N_("show status in long format (default)"),
1687 STATUS_FORMAT_LONG),
1688 OPT_BOOL('z', "null", &s.null_termination,
1689 N_("terminate entries with NUL")),
1690 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1691 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1692 { 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" },
1693 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1694 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1695 /* end commit contents options */
1697 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1698 N_("ok to record an empty change")),
1699 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1700 N_("ok to record a change with an empty message")),
1702 OPT_END()
1705 struct strbuf sb = STRBUF_INIT;
1706 struct strbuf author_ident = STRBUF_INIT;
1707 const char *index_file, *reflog_msg;
1708 struct object_id oid;
1709 struct commit_list *parents = NULL;
1710 struct stat statbuf;
1711 struct commit *current_head = NULL;
1712 struct commit_extra_header *extra = NULL;
1713 struct strbuf err = STRBUF_INIT;
1714 int ret = 0;
1716 if (argc == 2 && !strcmp(argv[1], "-h"))
1717 usage_with_options(builtin_commit_usage, builtin_commit_options);
1719 prepare_repo_settings(the_repository);
1720 the_repository->settings.command_requires_full_index = 0;
1722 status_init_config(&s, git_commit_config);
1723 s.commit_template = 1;
1724 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1725 s.colopts = 0;
1727 if (repo_get_oid(the_repository, "HEAD", &oid))
1728 current_head = NULL;
1729 else {
1730 current_head = lookup_commit_or_die(&oid, "HEAD");
1731 if (repo_parse_commit(the_repository, current_head))
1732 die(_("could not parse HEAD commit"));
1734 verbose = -1; /* unspecified */
1735 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1736 builtin_commit_usage,
1737 prefix, current_head, &s);
1738 if (verbose == -1)
1739 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1741 if (dry_run)
1742 return dry_run_commit(argv, prefix, current_head, &s);
1743 index_file = prepare_index(argv, prefix, current_head, 0);
1745 /* Set up everything for writing the commit object. This includes
1746 running hooks, writing the trees, and interacting with the user. */
1747 if (!prepare_to_commit(index_file, prefix,
1748 current_head, &s, &author_ident)) {
1749 ret = 1;
1750 rollback_index_files();
1751 goto cleanup;
1754 /* Determine parents */
1755 reflog_msg = getenv("GIT_REFLOG_ACTION");
1756 if (!current_head) {
1757 if (!reflog_msg)
1758 reflog_msg = "commit (initial)";
1759 } else if (amend) {
1760 if (!reflog_msg)
1761 reflog_msg = "commit (amend)";
1762 parents = copy_commit_list(current_head->parents);
1763 } else if (whence == FROM_MERGE) {
1764 struct strbuf m = STRBUF_INIT;
1765 FILE *fp;
1766 int allow_fast_forward = 1;
1767 struct commit_list **pptr = &parents;
1769 if (!reflog_msg)
1770 reflog_msg = "commit (merge)";
1771 pptr = commit_list_append(current_head, pptr);
1772 fp = xfopen(git_path_merge_head(the_repository), "r");
1773 while (strbuf_getline_lf(&m, fp) != EOF) {
1774 struct commit *parent;
1776 parent = get_merge_parent(m.buf);
1777 if (!parent)
1778 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1779 pptr = commit_list_append(parent, pptr);
1781 fclose(fp);
1782 strbuf_release(&m);
1783 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1784 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1785 die_errno(_("could not read MERGE_MODE"));
1786 if (!strcmp(sb.buf, "no-ff"))
1787 allow_fast_forward = 0;
1789 if (allow_fast_forward)
1790 reduce_heads_replace(&parents);
1791 } else {
1792 if (!reflog_msg)
1793 reflog_msg = is_from_cherry_pick(whence)
1794 ? "commit (cherry-pick)"
1795 : is_from_rebase(whence)
1796 ? "commit (rebase)"
1797 : "commit";
1798 commit_list_insert(current_head, &parents);
1801 /* Finally, get the commit message */
1802 strbuf_reset(&sb);
1803 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1804 int saved_errno = errno;
1805 rollback_index_files();
1806 die(_("could not read commit message: %s"), strerror(saved_errno));
1809 cleanup_message(&sb, cleanup_mode, verbose);
1811 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1812 rollback_index_files();
1813 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1814 exit(1);
1816 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1817 rollback_index_files();
1818 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1819 exit(1);
1822 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1823 !allow_empty_message) {
1824 struct strbuf body = STRBUF_INIT;
1825 size_t len = commit_subject_length(sb.buf);
1826 strbuf_addstr(&body, sb.buf + len);
1827 if (message_is_empty(&body, cleanup_mode)) {
1828 rollback_index_files();
1829 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1830 exit(1);
1832 strbuf_release(&body);
1835 if (amend) {
1836 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1837 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1838 } else {
1839 struct commit_extra_header **tail = &extra;
1840 append_merge_tag_headers(parents, &tail);
1843 if (commit_tree_extended(sb.buf, sb.len, &the_index.cache_tree->oid,
1844 parents, &oid, author_ident.buf, NULL,
1845 sign_commit, extra)) {
1846 rollback_index_files();
1847 die(_("failed to write commit object"));
1849 free_commit_extra_headers(extra);
1851 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1852 &err)) {
1853 rollback_index_files();
1854 die("%s", err.buf);
1857 sequencer_post_commit_cleanup(the_repository, 0);
1858 unlink(git_path_merge_head(the_repository));
1859 unlink(git_path_merge_msg(the_repository));
1860 unlink(git_path_merge_mode(the_repository));
1861 unlink(git_path_squash_msg(the_repository));
1863 if (commit_index_files())
1864 die(_("repository has been updated, but unable to write\n"
1865 "new_index file. Check that disk is not full and quota is\n"
1866 "not exceeded, and then \"git restore --staged :/\" to recover."));
1868 git_test_write_commit_graph_or_die();
1870 repo_rerere(the_repository, 0);
1871 run_auto_maintenance(quiet);
1872 run_commit_hook(use_editor, get_index_file(), NULL, "post-commit",
1873 NULL);
1874 if (amend && !no_post_rewrite) {
1875 commit_post_rewrite(the_repository, current_head, &oid);
1877 if (!quiet) {
1878 unsigned int flags = 0;
1880 if (!current_head)
1881 flags |= SUMMARY_INITIAL_COMMIT;
1882 if (author_date_is_interesting())
1883 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1884 print_commit_summary(the_repository, prefix,
1885 &oid, flags);
1888 apply_autostash(git_path_merge_autostash(the_repository));
1890 cleanup:
1891 strbuf_release(&author_ident);
1892 strbuf_release(&err);
1893 strbuf_release(&sb);
1894 return ret;