builtin/show: do not prune by pathspec
[git/mjg.git] / builtin / commit.c
blobdec78dfb86fdc492f2576576a5e0a417b82bf74a
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"
40 #include "trailer.h"
42 static const char * const builtin_commit_usage[] = {
43 N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]\n"
44 " [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>)]\n"
45 " [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
46 " [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
47 " [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
48 " [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
49 " [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
50 " [--] [<pathspec>...]"),
51 NULL
54 static const char * const builtin_status_usage[] = {
55 N_("git status [<options>] [--] [<pathspec>...]"),
56 NULL
59 static const char empty_amend_advice[] =
60 N_("You asked to amend the most recent commit, but doing so would make\n"
61 "it empty. You can repeat your command with --allow-empty, or you can\n"
62 "remove the commit entirely with \"git reset HEAD^\".\n");
64 static const char empty_cherry_pick_advice[] =
65 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
66 "If you wish to commit it anyway, use:\n"
67 "\n"
68 " git commit --allow-empty\n"
69 "\n");
71 static const char empty_rebase_pick_advice[] =
72 N_("Otherwise, please use 'git rebase --skip'\n");
74 static const char empty_cherry_pick_advice_single[] =
75 N_("Otherwise, please use 'git cherry-pick --skip'\n");
77 static const char empty_cherry_pick_advice_multi[] =
78 N_("and then use:\n"
79 "\n"
80 " git cherry-pick --continue\n"
81 "\n"
82 "to resume cherry-picking the remaining commits.\n"
83 "If you wish to skip this commit, use:\n"
84 "\n"
85 " git cherry-pick --skip\n"
86 "\n");
88 static const char *color_status_slots[] = {
89 [WT_STATUS_HEADER] = "header",
90 [WT_STATUS_UPDATED] = "updated",
91 [WT_STATUS_CHANGED] = "changed",
92 [WT_STATUS_UNTRACKED] = "untracked",
93 [WT_STATUS_NOBRANCH] = "noBranch",
94 [WT_STATUS_UNMERGED] = "unmerged",
95 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
96 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
97 [WT_STATUS_ONBRANCH] = "branch",
100 static const char *use_message_buffer;
101 static struct lock_file index_lock; /* real index */
102 static struct lock_file false_lock; /* used only for partial commits */
103 static enum {
104 COMMIT_AS_IS = 1,
105 COMMIT_NORMAL,
106 COMMIT_PARTIAL
107 } commit_style;
109 static const char *force_author;
110 static char *logfile;
111 static char *template_file;
113 * The _message variables are commit names from which to take
114 * the commit message and/or authorship.
116 static const char *author_message, *author_message_buffer;
117 static const char *edit_message, *use_message;
118 static char *fixup_message, *fixup_commit, *squash_message;
119 static const char *fixup_prefix;
120 static int all, also, interactive, patch_interactive, only, amend, signoff;
121 static int edit_flag = -1; /* unspecified */
122 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
123 static int config_commit_verbose = -1; /* unspecified */
124 static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
125 static const char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
126 static const char *sign_commit, *pathspec_from_file;
127 static struct strvec trailer_args = STRVEC_INIT;
130 * The default commit message cleanup mode will remove the lines
131 * beginning with # (shell comments) and leading and trailing
132 * whitespaces (empty lines or containing only whitespaces)
133 * if editor is used, and only the whitespaces if the message
134 * is specified explicitly.
136 static enum commit_msg_cleanup_mode cleanup_mode;
137 static char *cleanup_arg;
139 static enum commit_whence whence;
140 static int use_editor = 1, include_status = 1;
141 static int have_option_m;
142 static struct strbuf message = STRBUF_INIT;
144 static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
146 static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
148 enum wt_status_format *value = (enum wt_status_format *)opt->value;
149 if (unset)
150 *value = STATUS_FORMAT_NONE;
151 else if (!arg)
152 *value = STATUS_FORMAT_PORCELAIN;
153 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
154 *value = STATUS_FORMAT_PORCELAIN;
155 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
156 *value = STATUS_FORMAT_PORCELAIN_V2;
157 else
158 die("unsupported porcelain version '%s'", arg);
160 return 0;
163 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
165 struct strbuf *buf = opt->value;
166 if (unset) {
167 have_option_m = 0;
168 strbuf_setlen(buf, 0);
169 } else {
170 have_option_m = 1;
171 if (buf->len)
172 strbuf_addch(buf, '\n');
173 strbuf_addstr(buf, arg);
174 strbuf_complete_line(buf);
176 return 0;
179 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
181 const char **value = opt->value;
183 BUG_ON_OPT_NEG(unset);
185 if (arg != NULL && *arg == '=')
186 arg = arg + 1;
188 *value = arg;
189 return 0;
192 static void determine_whence(struct wt_status *s)
194 if (file_exists(git_path_merge_head(the_repository)))
195 whence = FROM_MERGE;
196 else if (!sequencer_determine_whence(the_repository, &whence))
197 whence = FROM_COMMIT;
198 if (s)
199 s->whence = whence;
202 static void status_init_config(struct wt_status *s, config_fn_t fn)
204 wt_status_prepare(the_repository, s);
205 init_diff_ui_defaults();
206 git_config(fn, s);
207 determine_whence(s);
208 s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after git_config() */
211 static void rollback_index_files(void)
213 switch (commit_style) {
214 case COMMIT_AS_IS:
215 break; /* nothing to do */
216 case COMMIT_NORMAL:
217 rollback_lock_file(&index_lock);
218 break;
219 case COMMIT_PARTIAL:
220 rollback_lock_file(&index_lock);
221 rollback_lock_file(&false_lock);
222 break;
226 static int commit_index_files(void)
228 int err = 0;
230 switch (commit_style) {
231 case COMMIT_AS_IS:
232 break; /* nothing to do */
233 case COMMIT_NORMAL:
234 err = commit_lock_file(&index_lock);
235 break;
236 case COMMIT_PARTIAL:
237 err = commit_lock_file(&index_lock);
238 rollback_lock_file(&false_lock);
239 break;
242 return err;
246 * Take a union of paths in the index and the named tree (typically, "HEAD"),
247 * and return the paths that match the given pattern in list.
249 static int list_paths(struct string_list *list, const char *with_tree,
250 const struct pathspec *pattern)
252 int i, ret;
253 char *m;
255 if (!pattern->nr)
256 return 0;
258 m = xcalloc(1, pattern->nr);
260 if (with_tree) {
261 char *max_prefix = common_prefix(pattern);
262 overlay_tree_on_index(the_repository->index, with_tree, max_prefix);
263 free(max_prefix);
266 /* TODO: audit for interaction with sparse-index. */
267 ensure_full_index(the_repository->index);
268 for (i = 0; i < the_repository->index->cache_nr; i++) {
269 const struct cache_entry *ce = the_repository->index->cache[i];
270 struct string_list_item *item;
272 if (ce->ce_flags & CE_UPDATE)
273 continue;
274 if (!ce_path_match(the_repository->index, ce, pattern, m))
275 continue;
276 item = string_list_insert(list, ce->name);
277 if (ce_skip_worktree(ce))
278 item->util = item; /* better a valid pointer than a fake one */
281 ret = report_path_error(m, pattern);
282 free(m);
283 return ret;
286 static void add_remove_files(struct string_list *list)
288 int i;
289 for (i = 0; i < list->nr; i++) {
290 struct stat st;
291 struct string_list_item *p = &(list->items[i]);
293 /* p->util is skip-worktree */
294 if (p->util)
295 continue;
297 if (!lstat(p->string, &st)) {
298 if (add_to_index(the_repository->index, p->string, &st, 0))
299 die(_("updating files failed"));
300 } else
301 remove_file_from_index(the_repository->index, p->string);
305 static void create_base_index(const struct commit *current_head)
307 struct tree *tree;
308 struct unpack_trees_options opts;
309 struct tree_desc t;
311 if (!current_head) {
312 discard_index(the_repository->index);
313 return;
316 memset(&opts, 0, sizeof(opts));
317 opts.head_idx = 1;
318 opts.index_only = 1;
319 opts.merge = 1;
320 opts.src_index = the_repository->index;
321 opts.dst_index = the_repository->index;
323 opts.fn = oneway_merge;
324 tree = parse_tree_indirect(&current_head->object.oid);
325 if (!tree)
326 die(_("failed to unpack HEAD tree object"));
327 if (parse_tree(tree) < 0)
328 exit(128);
329 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
330 if (unpack_trees(1, &t, &opts))
331 exit(128); /* We've already reported the error, finish dying */
334 static void refresh_cache_or_die(int refresh_flags)
337 * refresh_flags contains REFRESH_QUIET, so the only errors
338 * are for unmerged entries.
340 if (refresh_index(the_repository->index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
341 die_resolve_conflict("commit");
344 static const char *prepare_index(const char **argv, const char *prefix,
345 const struct commit *current_head, int is_status)
347 struct string_list partial = STRING_LIST_INIT_DUP;
348 struct pathspec pathspec;
349 int refresh_flags = REFRESH_QUIET;
350 const char *ret;
352 if (is_status)
353 refresh_flags |= REFRESH_UNMERGED;
354 parse_pathspec(&pathspec, 0,
355 PATHSPEC_PREFER_FULL,
356 prefix, argv);
358 if (pathspec_from_file) {
359 if (interactive)
360 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
362 if (all)
363 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
365 if (pathspec.nr)
366 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
368 parse_pathspec_file(&pathspec, 0,
369 PATHSPEC_PREFER_FULL,
370 prefix, pathspec_from_file, pathspec_file_nul);
371 } else if (pathspec_file_nul) {
372 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
375 if (!pathspec.nr && (also || (only && !allow_empty &&
376 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
377 die(_("No paths with --include/--only does not make sense."));
379 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
380 die(_("index file corrupt"));
382 if (interactive) {
383 char *old_index_env = NULL, *old_repo_index_file;
384 repo_hold_locked_index(the_repository, &index_lock,
385 LOCK_DIE_ON_ERROR);
387 refresh_cache_or_die(refresh_flags);
389 if (write_locked_index(the_repository->index, &index_lock, 0))
390 die(_("unable to create temporary index"));
392 old_repo_index_file = the_repository->index_file;
393 the_repository->index_file =
394 (char *)get_lock_file_path(&index_lock);
395 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
396 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
398 if (interactive_add(argv, prefix, patch_interactive) != 0)
399 die(_("interactive add failed"));
401 the_repository->index_file = old_repo_index_file;
402 if (old_index_env && *old_index_env)
403 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
404 else
405 unsetenv(INDEX_ENVIRONMENT);
406 FREE_AND_NULL(old_index_env);
408 discard_index(the_repository->index);
409 read_index_from(the_repository->index, get_lock_file_path(&index_lock),
410 get_git_dir());
411 if (cache_tree_update(the_repository->index, WRITE_TREE_SILENT) == 0) {
412 if (reopen_lock_file(&index_lock) < 0)
413 die(_("unable to write index file"));
414 if (write_locked_index(the_repository->index, &index_lock, 0))
415 die(_("unable to update temporary index"));
416 } else
417 warning(_("Failed to update main cache tree"));
419 commit_style = COMMIT_NORMAL;
420 ret = get_lock_file_path(&index_lock);
421 goto out;
425 * Non partial, non as-is commit.
427 * (1) get the real index;
428 * (2) update the_index as necessary;
429 * (3) write the_index out to the real index (still locked);
430 * (4) return the name of the locked index file.
432 * The caller should run hooks on the locked real index, and
433 * (A) if all goes well, commit the real index;
434 * (B) on failure, rollback the real index.
436 if (all || (also && pathspec.nr)) {
437 char *ps_matched = xcalloc(pathspec.nr, 1);
438 repo_hold_locked_index(the_repository, &index_lock,
439 LOCK_DIE_ON_ERROR);
440 add_files_to_cache(the_repository, also ? prefix : NULL,
441 &pathspec, ps_matched, 0, 0);
442 if (!all && report_path_error(ps_matched, &pathspec))
443 exit(128);
445 refresh_cache_or_die(refresh_flags);
446 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
447 if (write_locked_index(the_repository->index, &index_lock, 0))
448 die(_("unable to write new index file"));
449 commit_style = COMMIT_NORMAL;
450 ret = get_lock_file_path(&index_lock);
451 free(ps_matched);
452 goto out;
456 * As-is commit.
458 * (1) return the name of the real index file.
460 * The caller should run hooks on the real index,
461 * and create commit from the_index.
462 * We still need to refresh the index here.
464 if (!only && !pathspec.nr) {
465 repo_hold_locked_index(the_repository, &index_lock,
466 LOCK_DIE_ON_ERROR);
467 refresh_cache_or_die(refresh_flags);
468 if (the_repository->index->cache_changed
469 || !cache_tree_fully_valid(the_repository->index->cache_tree))
470 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
471 if (write_locked_index(the_repository->index, &index_lock,
472 COMMIT_LOCK | SKIP_IF_UNCHANGED))
473 die(_("unable to write new index file"));
474 commit_style = COMMIT_AS_IS;
475 ret = get_index_file();
476 goto out;
480 * A partial commit.
482 * (0) find the set of affected paths;
483 * (1) get lock on the real index file;
484 * (2) update the_index with the given paths;
485 * (3) write the_index out to the real index (still locked);
486 * (4) get lock on the false index file;
487 * (5) reset the_index from HEAD;
488 * (6) update the_index the same way as (2);
489 * (7) write the_index out to the false index file;
490 * (8) return the name of the false index file (still locked);
492 * The caller should run hooks on the locked false index, and
493 * create commit from it. Then
494 * (A) if all goes well, commit the real index;
495 * (B) on failure, rollback the real index;
496 * In either case, rollback the false index.
498 commit_style = COMMIT_PARTIAL;
500 if (whence != FROM_COMMIT) {
501 if (whence == FROM_MERGE)
502 die(_("cannot do a partial commit during a merge."));
503 else if (is_from_cherry_pick(whence))
504 die(_("cannot do a partial commit during a cherry-pick."));
505 else if (is_from_rebase(whence))
506 die(_("cannot do a partial commit during a rebase."));
509 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
510 exit(1);
512 discard_index(the_repository->index);
513 if (repo_read_index(the_repository) < 0)
514 die(_("cannot read the index"));
516 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
517 add_remove_files(&partial);
518 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
519 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
520 if (write_locked_index(the_repository->index, &index_lock, 0))
521 die(_("unable to write new index file"));
523 hold_lock_file_for_update(&false_lock,
524 git_path("next-index-%"PRIuMAX,
525 (uintmax_t) getpid()),
526 LOCK_DIE_ON_ERROR);
528 create_base_index(current_head);
529 add_remove_files(&partial);
530 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
532 if (write_locked_index(the_repository->index, &false_lock, 0))
533 die(_("unable to write temporary index file"));
535 discard_index(the_repository->index);
536 ret = get_lock_file_path(&false_lock);
537 read_index_from(the_repository->index, ret, get_git_dir());
538 out:
539 string_list_clear(&partial, 0);
540 clear_pathspec(&pathspec);
541 return ret;
544 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
545 struct wt_status *s)
547 struct object_id oid;
549 if (s->relative_paths)
550 s->prefix = prefix;
552 if (amend) {
553 s->amend = 1;
554 s->reference = "HEAD^1";
556 s->verbose = verbose;
557 s->index_file = index_file;
558 s->fp = fp;
559 s->nowarn = nowarn;
560 s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
561 if (!s->is_initial)
562 oidcpy(&s->oid_commit, &oid);
563 s->status_format = status_format;
564 s->ignore_submodule_arg = ignore_submodule_arg;
566 wt_status_collect(s);
567 wt_status_print(s);
568 wt_status_collect_free_buffers(s);
570 return s->committable;
573 static int is_a_merge(const struct commit *current_head)
575 return !!(current_head->parents && current_head->parents->next);
578 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
580 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
581 BUG("unable to parse our own ident: %s", buf->buf);
584 static void export_one(const char *var, const char *s, const char *e, int hack)
586 struct strbuf buf = STRBUF_INIT;
587 if (hack)
588 strbuf_addch(&buf, hack);
589 strbuf_add(&buf, s, e - s);
590 setenv(var, buf.buf, 1);
591 strbuf_release(&buf);
594 static int parse_force_date(const char *in, struct strbuf *out)
596 strbuf_addch(out, '@');
598 if (parse_date(in, out) < 0) {
599 int errors = 0;
600 unsigned long t = approxidate_careful(in, &errors);
601 if (errors)
602 return -1;
603 strbuf_addf(out, "%lu", t);
606 return 0;
609 static void set_ident_var(char **buf, char *val)
611 free(*buf);
612 *buf = val;
615 static void determine_author_info(struct strbuf *author_ident)
617 char *name, *email, *date;
618 struct ident_split author;
620 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
621 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
622 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
624 if (author_message) {
625 struct ident_split ident;
626 size_t len;
627 const char *a;
629 a = find_commit_header(author_message_buffer, "author", &len);
630 if (!a)
631 die(_("commit '%s' lacks author header"), author_message);
632 if (split_ident_line(&ident, a, len) < 0)
633 die(_("commit '%s' has malformed author line"), author_message);
635 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
636 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
638 if (ident.date_begin) {
639 struct strbuf date_buf = STRBUF_INIT;
640 strbuf_addch(&date_buf, '@');
641 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
642 strbuf_addch(&date_buf, ' ');
643 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
644 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
648 if (force_author) {
649 struct ident_split ident;
651 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
652 die(_("malformed --author parameter"));
653 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
654 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
657 if (force_date) {
658 struct strbuf date_buf = STRBUF_INIT;
659 if (parse_force_date(force_date, &date_buf))
660 die(_("invalid date format: %s"), force_date);
661 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
664 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
665 IDENT_STRICT));
666 assert_split_ident(&author, author_ident);
667 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
668 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
669 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
670 free(name);
671 free(email);
672 free(date);
675 static int author_date_is_interesting(void)
677 return author_message || force_date;
680 static void adjust_comment_line_char(const struct strbuf *sb)
682 char candidates[] = "#;@!$%^&|:";
683 char *candidate;
684 const char *p;
686 if (!memchr(sb->buf, candidates[0], sb->len)) {
687 comment_line_str = xstrfmt("%c", candidates[0]);
688 return;
691 p = sb->buf;
692 candidate = strchr(candidates, *p);
693 if (candidate)
694 *candidate = ' ';
695 for (p = sb->buf; *p; p++) {
696 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
697 candidate = strchr(candidates, p[1]);
698 if (candidate)
699 *candidate = ' ';
703 for (p = candidates; *p == ' '; p++)
705 if (!*p)
706 die(_("unable to select a comment character that is not used\n"
707 "in the current commit message"));
708 comment_line_str = xstrfmt("%c", *p);
711 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
712 struct pretty_print_context *ctx)
714 const char *buffer, *subject, *fmt;
716 buffer = repo_get_commit_buffer(the_repository, commit, NULL);
717 find_commit_subject(buffer, &subject);
719 * If we amend the 'amend!' commit then we don't want to
720 * duplicate the subject line.
722 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
723 repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
724 repo_unuse_commit_buffer(the_repository, commit, buffer);
727 static int prepare_to_commit(const char *index_file, const char *prefix,
728 struct commit *current_head,
729 struct wt_status *s,
730 struct strbuf *author_ident)
732 struct stat statbuf;
733 struct strbuf committer_ident = STRBUF_INIT;
734 int committable;
735 struct strbuf sb = STRBUF_INIT;
736 const char *hook_arg1 = NULL;
737 const char *hook_arg2 = NULL;
738 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
739 int old_display_comment_prefix;
740 int invoked_hook;
742 /* This checks and barfs if author is badly specified */
743 determine_author_info(author_ident);
745 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
746 "pre-commit", NULL))
747 return 0;
749 if (squash_message) {
751 * Insert the proper subject line before other commit
752 * message options add their content.
754 if (use_message && !strcmp(use_message, squash_message))
755 strbuf_addstr(&sb, "squash! ");
756 else {
757 struct pretty_print_context ctx = {0};
758 struct commit *c;
759 c = lookup_commit_reference_by_name(squash_message);
760 if (!c)
761 die(_("could not lookup commit '%s'"), squash_message);
762 ctx.output_encoding = get_commit_output_encoding();
763 repo_format_commit_message(the_repository, c,
764 "squash! %s\n\n", &sb,
765 &ctx);
769 if (have_option_m && !fixup_message) {
770 strbuf_addbuf(&sb, &message);
771 hook_arg1 = "message";
772 } else if (logfile && !strcmp(logfile, "-")) {
773 if (isatty(0))
774 fprintf(stderr, _("(reading log message from standard input)\n"));
775 if (strbuf_read(&sb, 0, 0) < 0)
776 die_errno(_("could not read log from standard input"));
777 hook_arg1 = "message";
778 } else if (logfile) {
779 if (strbuf_read_file(&sb, logfile, 0) < 0)
780 die_errno(_("could not read log file '%s'"),
781 logfile);
782 hook_arg1 = "message";
783 } else if (use_message) {
784 char *buffer;
785 buffer = strstr(use_message_buffer, "\n\n");
786 if (buffer)
787 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
788 hook_arg1 = "commit";
789 hook_arg2 = use_message;
790 } else if (fixup_message) {
791 struct pretty_print_context ctx = {0};
792 struct commit *commit;
793 char *fmt;
794 commit = lookup_commit_reference_by_name(fixup_commit);
795 if (!commit)
796 die(_("could not lookup commit '%s'"), fixup_commit);
797 ctx.output_encoding = get_commit_output_encoding();
798 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
799 repo_format_commit_message(the_repository, commit, fmt, &sb,
800 &ctx);
801 free(fmt);
802 hook_arg1 = "message";
805 * Only `-m` commit message option is checked here, as
806 * it supports `--fixup` to append the commit message.
808 * The other commit message options `-c`/`-C`/`-F` are
809 * incompatible with all the forms of `--fixup` and
810 * have already errored out while parsing the `git commit`
811 * options.
813 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
814 strbuf_addbuf(&sb, &message);
816 if (!strcmp(fixup_prefix, "amend")) {
817 if (have_option_m)
818 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
819 prepare_amend_commit(commit, &sb, &ctx);
821 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
822 size_t merge_msg_start;
825 * prepend SQUASH_MSG here if it exists and a
826 * "merge --squash" was originally performed
828 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
829 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
830 die_errno(_("could not read SQUASH_MSG"));
831 hook_arg1 = "squash";
832 } else
833 hook_arg1 = "merge";
835 merge_msg_start = sb.len;
836 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
837 die_errno(_("could not read MERGE_MSG"));
839 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
840 wt_status_locate_end(sb.buf + merge_msg_start,
841 sb.len - merge_msg_start) <
842 sb.len - merge_msg_start)
843 s->added_cut_line = 1;
844 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
845 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
846 die_errno(_("could not read SQUASH_MSG"));
847 hook_arg1 = "squash";
848 } else if (template_file) {
849 if (strbuf_read_file(&sb, template_file, 0) < 0)
850 die_errno(_("could not read '%s'"), template_file);
851 hook_arg1 = "template";
852 clean_message_contents = 0;
856 * The remaining cases don't modify the template message, but
857 * just set the argument(s) to the prepare-commit-msg hook.
859 else if (whence == FROM_MERGE)
860 hook_arg1 = "merge";
861 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
862 hook_arg1 = "commit";
863 hook_arg2 = "CHERRY_PICK_HEAD";
866 if (squash_message) {
868 * If squash_commit was used for the commit subject,
869 * then we're possibly hijacking other commit log options.
870 * Reset the hook args to tell the real story.
872 hook_arg1 = "message";
873 hook_arg2 = "";
876 s->fp = fopen_for_writing(git_path_commit_editmsg());
877 if (!s->fp)
878 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
880 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
881 old_display_comment_prefix = s->display_comment_prefix;
882 s->display_comment_prefix = 1;
885 * Most hints are counter-productive when the commit has
886 * already started.
888 s->hints = 0;
890 if (clean_message_contents)
891 strbuf_stripspace(&sb, NULL);
893 if (signoff)
894 append_signoff(&sb, ignored_log_message_bytes(sb.buf, sb.len), 0);
896 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
897 die_errno(_("could not write commit template"));
899 if (auto_comment_line_char)
900 adjust_comment_line_char(&sb);
901 strbuf_release(&sb);
903 /* This checks if committer ident is explicitly given */
904 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
905 if (use_editor && include_status) {
906 int ident_shown = 0;
907 int saved_color_setting;
908 struct ident_split ci, ai;
909 const char *hint_cleanup_all = allow_empty_message ?
910 _("Please enter the commit message for your changes."
911 " Lines starting\nwith '%s' will be ignored.\n") :
912 _("Please enter the commit message for your changes."
913 " Lines starting\nwith '%s' will be ignored, and an empty"
914 " message aborts the commit.\n");
915 const char *hint_cleanup_space = allow_empty_message ?
916 _("Please enter the commit message for your changes."
917 " Lines starting\n"
918 "with '%s' will be kept; you may remove them"
919 " yourself if you want to.\n") :
920 _("Please enter the commit message for your changes."
921 " Lines starting\n"
922 "with '%s' will be kept; you may remove them"
923 " yourself if you want to.\n"
924 "An empty message aborts the commit.\n");
925 if (whence != FROM_COMMIT) {
926 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
927 wt_status_add_cut_line(s);
928 status_printf_ln(
929 s, GIT_COLOR_NORMAL,
930 whence == FROM_MERGE ?
931 _("\n"
932 "It looks like you may be committing a merge.\n"
933 "If this is not correct, please run\n"
934 " git update-ref -d MERGE_HEAD\n"
935 "and try again.\n") :
936 _("\n"
937 "It looks like you may be committing a cherry-pick.\n"
938 "If this is not correct, please run\n"
939 " git update-ref -d CHERRY_PICK_HEAD\n"
940 "and try again.\n"));
943 fprintf(s->fp, "\n");
944 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
945 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_str);
946 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
947 if (whence == FROM_COMMIT)
948 wt_status_add_cut_line(s);
949 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
950 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_str);
953 * These should never fail because they come from our own
954 * fmt_ident. They may fail the sane_ident test, but we know
955 * that the name and mail pointers will at least be valid,
956 * which is enough for our tests and printing here.
958 assert_split_ident(&ai, author_ident);
959 assert_split_ident(&ci, &committer_ident);
961 if (ident_cmp(&ai, &ci))
962 status_printf_ln(s, GIT_COLOR_NORMAL,
963 _("%s"
964 "Author: %.*s <%.*s>"),
965 ident_shown++ ? "" : "\n",
966 (int)(ai.name_end - ai.name_begin), ai.name_begin,
967 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
969 if (author_date_is_interesting())
970 status_printf_ln(s, GIT_COLOR_NORMAL,
971 _("%s"
972 "Date: %s"),
973 ident_shown++ ? "" : "\n",
974 show_ident_date(&ai, DATE_MODE(NORMAL)));
976 if (!committer_ident_sufficiently_given())
977 status_printf_ln(s, GIT_COLOR_NORMAL,
978 _("%s"
979 "Committer: %.*s <%.*s>"),
980 ident_shown++ ? "" : "\n",
981 (int)(ci.name_end - ci.name_begin), ci.name_begin,
982 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
984 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
986 saved_color_setting = s->use_color;
987 s->use_color = 0;
988 committable = run_status(s->fp, index_file, prefix, 1, s);
989 s->use_color = saved_color_setting;
990 string_list_clear(&s->change, 1);
991 } else {
992 struct object_id oid;
993 const char *parent = "HEAD";
995 if (!the_repository->index->initialized && repo_read_index(the_repository) < 0)
996 die(_("Cannot read index"));
998 if (amend)
999 parent = "HEAD^1";
1001 if (repo_get_oid(the_repository, parent, &oid)) {
1002 int i, ita_nr = 0;
1004 /* TODO: audit for interaction with sparse-index. */
1005 ensure_full_index(the_repository->index);
1006 for (i = 0; i < the_repository->index->cache_nr; i++)
1007 if (ce_intent_to_add(the_repository->index->cache[i]))
1008 ita_nr++;
1009 committable = the_repository->index->cache_nr - ita_nr > 0;
1010 } else {
1012 * Unless the user did explicitly request a submodule
1013 * ignore mode by passing a command line option we do
1014 * not ignore any changed submodule SHA-1s when
1015 * comparing index and parent, no matter what is
1016 * configured. Otherwise we won't commit any
1017 * submodules which were manually staged, which would
1018 * be really confusing.
1020 struct diff_flags flags = DIFF_FLAGS_INIT;
1021 flags.override_submodule_config = 1;
1022 if (ignore_submodule_arg &&
1023 !strcmp(ignore_submodule_arg, "all"))
1024 flags.ignore_submodules = 1;
1025 committable = index_differs_from(the_repository,
1026 parent, &flags, 1);
1029 strbuf_release(&committer_ident);
1031 fclose(s->fp);
1033 if (trailer_args.nr) {
1034 if (amend_file_with_trailers(git_path_commit_editmsg(), &trailer_args))
1035 die(_("unable to pass trailers to --trailers"));
1036 strvec_clear(&trailer_args);
1040 * Reject an attempt to record a non-merge empty commit without
1041 * explicit --allow-empty. In the cherry-pick case, it may be
1042 * empty due to conflict resolution, which the user should okay.
1044 if (!committable && whence != FROM_MERGE && !allow_empty &&
1045 !(amend && is_a_merge(current_head))) {
1046 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1047 s->display_comment_prefix = old_display_comment_prefix;
1048 run_status(stdout, index_file, prefix, 0, s);
1049 if (amend)
1050 fputs(_(empty_amend_advice), stderr);
1051 else if (is_from_cherry_pick(whence) ||
1052 whence == FROM_REBASE_PICK) {
1053 fputs(_(empty_cherry_pick_advice), stderr);
1054 if (whence == FROM_CHERRY_PICK_SINGLE)
1055 fputs(_(empty_cherry_pick_advice_single), stderr);
1056 else if (whence == FROM_CHERRY_PICK_MULTI)
1057 fputs(_(empty_cherry_pick_advice_multi), stderr);
1058 else
1059 fputs(_(empty_rebase_pick_advice), stderr);
1061 return 0;
1064 if (!no_verify && invoked_hook) {
1066 * Re-read the index as the pre-commit-commit hook was invoked
1067 * and could have updated it. We must do this before we invoke
1068 * the editor and after we invoke run_status above.
1070 discard_index(the_repository->index);
1072 read_index_from(the_repository->index, index_file, get_git_dir());
1074 if (cache_tree_update(the_repository->index, 0)) {
1075 error(_("Error building trees"));
1076 return 0;
1079 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1080 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1081 return 0;
1083 if (use_editor) {
1084 struct strvec env = STRVEC_INIT;
1086 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1087 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1088 fprintf(stderr,
1089 _("Please supply the message using either -m or -F option.\n"));
1090 exit(1);
1092 strvec_clear(&env);
1095 if (!no_verify &&
1096 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1097 git_path_commit_editmsg(), NULL)) {
1098 return 0;
1101 return 1;
1104 static const char *find_author_by_nickname(const char *name)
1106 struct rev_info revs;
1107 struct commit *commit;
1108 struct strbuf buf = STRBUF_INIT;
1109 const char *av[20];
1110 int ac = 0;
1112 repo_init_revisions(the_repository, &revs, NULL);
1113 strbuf_addf(&buf, "--author=%s", name);
1114 av[++ac] = "--all";
1115 av[++ac] = "-i";
1116 av[++ac] = buf.buf;
1117 av[++ac] = NULL;
1118 setup_revisions(ac, av, &revs, NULL);
1119 revs.mailmap = xmalloc(sizeof(struct string_list));
1120 string_list_init_nodup(revs.mailmap);
1121 read_mailmap(revs.mailmap);
1123 if (prepare_revision_walk(&revs))
1124 die(_("revision walk setup failed"));
1125 commit = get_revision(&revs);
1126 if (commit) {
1127 struct pretty_print_context ctx = {0};
1128 ctx.date_mode.type = DATE_NORMAL;
1129 strbuf_release(&buf);
1130 repo_format_commit_message(the_repository, commit,
1131 "%aN <%aE>", &buf, &ctx);
1132 release_revisions(&revs);
1133 return strbuf_detach(&buf, NULL);
1135 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1138 static void handle_ignored_arg(struct wt_status *s)
1140 if (!ignored_arg)
1141 ; /* default already initialized */
1142 else if (!strcmp(ignored_arg, "traditional"))
1143 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1144 else if (!strcmp(ignored_arg, "no"))
1145 s->show_ignored_mode = SHOW_NO_IGNORED;
1146 else if (!strcmp(ignored_arg, "matching"))
1147 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1148 else
1149 die(_("Invalid ignored mode '%s'"), ignored_arg);
1152 static enum untracked_status_type parse_untracked_setting_name(const char *u)
1155 * Please update $__git_untracked_file_modes in
1156 * git-completion.bash when you add new options
1158 switch (git_parse_maybe_bool(u)) {
1159 case 0:
1160 u = "no";
1161 break;
1162 case 1:
1163 u = "normal";
1164 break;
1165 default:
1166 break;
1169 if (!strcmp(u, "no"))
1170 return SHOW_NO_UNTRACKED_FILES;
1171 else if (!strcmp(u, "normal"))
1172 return SHOW_NORMAL_UNTRACKED_FILES;
1173 else if (!strcmp(u, "all"))
1174 return SHOW_ALL_UNTRACKED_FILES;
1175 else
1176 return SHOW_UNTRACKED_FILES_ERROR;
1179 static void handle_untracked_files_arg(struct wt_status *s)
1181 enum untracked_status_type u;
1183 if (!untracked_files_arg)
1184 return; /* default already initialized */
1186 u = parse_untracked_setting_name(untracked_files_arg);
1187 if (u == SHOW_UNTRACKED_FILES_ERROR)
1188 die(_("Invalid untracked files mode '%s'"),
1189 untracked_files_arg);
1190 s->show_untracked_files = u;
1193 static const char *read_commit_message(const char *name)
1195 const char *out_enc;
1196 struct commit *commit;
1198 commit = lookup_commit_reference_by_name(name);
1199 if (!commit)
1200 die(_("could not lookup commit '%s'"), name);
1201 out_enc = get_commit_output_encoding();
1202 return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1206 * Enumerate what needs to be propagated when --porcelain
1207 * is not in effect here.
1209 static struct status_deferred_config {
1210 enum wt_status_format status_format;
1211 int show_branch;
1212 enum ahead_behind_flags ahead_behind;
1213 } status_deferred_config = {
1214 STATUS_FORMAT_UNSPECIFIED,
1215 -1, /* unspecified */
1216 AHEAD_BEHIND_UNSPECIFIED,
1219 static void finalize_deferred_config(struct wt_status *s)
1221 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1222 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1223 !s->null_termination);
1225 if (s->null_termination) {
1226 if (status_format == STATUS_FORMAT_NONE ||
1227 status_format == STATUS_FORMAT_UNSPECIFIED)
1228 status_format = STATUS_FORMAT_PORCELAIN;
1229 else if (status_format == STATUS_FORMAT_LONG)
1230 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1233 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1234 status_format = status_deferred_config.status_format;
1235 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1236 status_format = STATUS_FORMAT_NONE;
1238 if (use_deferred_config && s->show_branch < 0)
1239 s->show_branch = status_deferred_config.show_branch;
1240 if (s->show_branch < 0)
1241 s->show_branch = 0;
1244 * If the user did not give a "--[no]-ahead-behind" command
1245 * line argument *AND* we will print in a human-readable format
1246 * (short, long etc.) then we inherit from the status.aheadbehind
1247 * config setting. In all other cases (and porcelain V[12] formats
1248 * in particular), we inherit _FULL for backwards compatibility.
1250 if (use_deferred_config &&
1251 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1252 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1254 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1255 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1258 static void check_fixup_reword_options(int argc, const char *argv[]) {
1259 if (whence != FROM_COMMIT) {
1260 if (whence == FROM_MERGE)
1261 die(_("You are in the middle of a merge -- cannot reword."));
1262 else if (is_from_cherry_pick(whence))
1263 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1265 if (argc)
1266 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1267 if (patch_interactive || interactive || all || also || only)
1268 die(_("reword option of '%s' and '%s' cannot be used together"),
1269 "--fixup", "--patch/--interactive/--all/--include/--only");
1272 static int parse_and_validate_options(int argc, const char *argv[],
1273 const struct option *options,
1274 const char * const usage[],
1275 const char *prefix,
1276 struct commit *current_head,
1277 struct wt_status *s)
1279 argc = parse_options(argc, argv, prefix, options, usage, 0);
1280 finalize_deferred_config(s);
1282 if (force_author && !strchr(force_author, '>'))
1283 force_author = find_author_by_nickname(force_author);
1285 if (force_author && renew_authorship)
1286 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1288 if (logfile || have_option_m || use_message)
1289 use_editor = 0;
1291 /* Sanity check options */
1292 if (amend && !current_head)
1293 die(_("You have nothing to amend."));
1294 if (amend && whence != FROM_COMMIT) {
1295 if (whence == FROM_MERGE)
1296 die(_("You are in the middle of a merge -- cannot amend."));
1297 else if (is_from_cherry_pick(whence))
1298 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1299 else if (whence == FROM_REBASE_PICK)
1300 die(_("You are in the middle of a rebase -- cannot amend."));
1302 if (fixup_message && squash_message)
1303 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1304 die_for_incompatible_opt4(!!use_message, "-C",
1305 !!edit_message, "-c",
1306 !!logfile, "-F",
1307 !!fixup_message, "--fixup");
1308 die_for_incompatible_opt4(have_option_m, "-m",
1309 !!edit_message, "-c",
1310 !!use_message, "-C",
1311 !!logfile, "-F");
1312 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1313 FREE_AND_NULL(template_file);
1314 if (edit_message)
1315 use_message = edit_message;
1316 if (amend && !use_message && !fixup_message)
1317 use_message = "HEAD";
1318 if (!use_message && !is_from_cherry_pick(whence) &&
1319 !is_from_rebase(whence) && renew_authorship)
1320 die(_("--reset-author can be used only with -C, -c or --amend."));
1321 if (use_message) {
1322 use_message_buffer = read_commit_message(use_message);
1323 if (!renew_authorship) {
1324 author_message = use_message;
1325 author_message_buffer = use_message_buffer;
1328 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1329 !renew_authorship) {
1330 author_message = "CHERRY_PICK_HEAD";
1331 author_message_buffer = read_commit_message(author_message);
1334 if (patch_interactive)
1335 interactive = 1;
1337 die_for_incompatible_opt4(also, "-i/--include",
1338 only, "-o/--only",
1339 all, "-a/--all",
1340 interactive, "--interactive/-p/--patch");
1341 if (fixup_message) {
1343 * We limit --fixup's suboptions to only alpha characters.
1344 * If the first character after a run of alpha is colon,
1345 * then the part before the colon may be a known suboption
1346 * name like `amend` or `reword`, or a misspelt suboption
1347 * name. In either case, we treat it as
1348 * --fixup=<suboption>:<arg>.
1350 * Otherwise, we are dealing with --fixup=<commit>.
1352 char *p = fixup_message;
1353 while (isalpha(*p))
1354 p++;
1355 if (p > fixup_message && *p == ':') {
1356 *p = '\0';
1357 fixup_commit = p + 1;
1358 if (!strcmp("amend", fixup_message) ||
1359 !strcmp("reword", fixup_message)) {
1360 fixup_prefix = "amend";
1361 allow_empty = 1;
1362 if (*fixup_message == 'r') {
1363 check_fixup_reword_options(argc, argv);
1364 only = 1;
1366 } else {
1367 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1369 } else {
1370 fixup_commit = fixup_message;
1371 fixup_prefix = "fixup";
1372 use_editor = 0;
1376 if (0 <= edit_flag)
1377 use_editor = edit_flag;
1379 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1381 handle_untracked_files_arg(s);
1383 if (all && argc > 0)
1384 die(_("paths '%s ...' with -a does not make sense"),
1385 argv[0]);
1387 if (status_format != STATUS_FORMAT_NONE)
1388 dry_run = 1;
1390 return argc;
1393 static int dry_run_commit(const char **argv, const char *prefix,
1394 const struct commit *current_head, struct wt_status *s)
1396 int committable;
1397 const char *index_file;
1399 index_file = prepare_index(argv, prefix, current_head, 1);
1400 committable = run_status(stdout, index_file, prefix, 0, s);
1401 rollback_index_files();
1403 return committable ? 0 : 1;
1406 define_list_config_array_extra(color_status_slots, {"added"});
1408 static int parse_status_slot(const char *slot)
1410 if (!strcasecmp(slot, "added"))
1411 return WT_STATUS_UPDATED;
1413 return LOOKUP_CONFIG(color_status_slots, slot);
1416 static int git_status_config(const char *k, const char *v,
1417 const struct config_context *ctx, void *cb)
1419 struct wt_status *s = cb;
1420 const char *slot_name;
1422 if (starts_with(k, "column."))
1423 return git_column_config(k, v, "status", &s->colopts);
1424 if (!strcmp(k, "status.submodulesummary")) {
1425 int is_bool;
1426 s->submodule_summary = git_config_bool_or_int(k, v, ctx->kvi,
1427 &is_bool);
1428 if (is_bool && s->submodule_summary)
1429 s->submodule_summary = -1;
1430 return 0;
1432 if (!strcmp(k, "status.short")) {
1433 if (git_config_bool(k, v))
1434 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1435 else
1436 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1437 return 0;
1439 if (!strcmp(k, "status.branch")) {
1440 status_deferred_config.show_branch = git_config_bool(k, v);
1441 return 0;
1443 if (!strcmp(k, "status.aheadbehind")) {
1444 status_deferred_config.ahead_behind = git_config_bool(k, v);
1445 return 0;
1447 if (!strcmp(k, "status.showstash")) {
1448 s->show_stash = git_config_bool(k, v);
1449 return 0;
1451 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1452 s->use_color = git_config_colorbool(k, v);
1453 return 0;
1455 if (!strcmp(k, "status.displaycommentprefix")) {
1456 s->display_comment_prefix = git_config_bool(k, v);
1457 return 0;
1459 if (skip_prefix(k, "status.color.", &slot_name) ||
1460 skip_prefix(k, "color.status.", &slot_name)) {
1461 int slot = parse_status_slot(slot_name);
1462 if (slot < 0)
1463 return 0;
1464 if (!v)
1465 return config_error_nonbool(k);
1466 return color_parse(v, s->color_palette[slot]);
1468 if (!strcmp(k, "status.relativepaths")) {
1469 s->relative_paths = git_config_bool(k, v);
1470 return 0;
1472 if (!strcmp(k, "status.showuntrackedfiles")) {
1473 enum untracked_status_type u;
1475 u = parse_untracked_setting_name(v);
1476 if (u == SHOW_UNTRACKED_FILES_ERROR)
1477 return error(_("Invalid untracked files mode '%s'"), v);
1478 s->show_untracked_files = u;
1479 return 0;
1481 if (!strcmp(k, "diff.renamelimit")) {
1482 if (s->rename_limit == -1)
1483 s->rename_limit = git_config_int(k, v, ctx->kvi);
1484 return 0;
1486 if (!strcmp(k, "status.renamelimit")) {
1487 s->rename_limit = git_config_int(k, v, ctx->kvi);
1488 return 0;
1490 if (!strcmp(k, "diff.renames")) {
1491 if (s->detect_rename == -1)
1492 s->detect_rename = git_config_rename(k, v);
1493 return 0;
1495 if (!strcmp(k, "status.renames")) {
1496 s->detect_rename = git_config_rename(k, v);
1497 return 0;
1499 return git_diff_ui_config(k, v, ctx, NULL);
1502 int cmd_status(int argc, const char **argv, const char *prefix)
1504 static int no_renames = -1;
1505 static const char *rename_score_arg = (const char *)-1;
1506 static struct wt_status s;
1507 unsigned int progress_flag = 0;
1508 int fd;
1509 struct object_id oid;
1510 static struct option builtin_status_options[] = {
1511 OPT__VERBOSE(&verbose, N_("be verbose")),
1512 OPT_SET_INT('s', "short", &status_format,
1513 N_("show status concisely"), STATUS_FORMAT_SHORT),
1514 OPT_BOOL('b', "branch", &s.show_branch,
1515 N_("show branch information")),
1516 OPT_BOOL(0, "show-stash", &s.show_stash,
1517 N_("show stash information")),
1518 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1519 N_("compute full ahead/behind values")),
1520 OPT_CALLBACK_F(0, "porcelain", &status_format,
1521 N_("version"), N_("machine-readable output"),
1522 PARSE_OPT_OPTARG, opt_parse_porcelain),
1523 OPT_SET_INT(0, "long", &status_format,
1524 N_("show status in long format (default)"),
1525 STATUS_FORMAT_LONG),
1526 OPT_BOOL('z', "null", &s.null_termination,
1527 N_("terminate entries with NUL")),
1528 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1529 N_("mode"),
1530 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1531 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1532 { OPTION_STRING, 0, "ignored", &ignored_arg,
1533 N_("mode"),
1534 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1535 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1536 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1537 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1538 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1539 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1540 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1541 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1542 N_("n"), N_("detect renames, optionally set similarity index"),
1543 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1544 OPT_END(),
1547 if (argc == 2 && !strcmp(argv[1], "-h"))
1548 usage_with_options(builtin_status_usage, builtin_status_options);
1550 prepare_repo_settings(the_repository);
1551 the_repository->settings.command_requires_full_index = 0;
1553 status_init_config(&s, git_status_config);
1554 argc = parse_options(argc, argv, prefix,
1555 builtin_status_options,
1556 builtin_status_usage, 0);
1557 finalize_colopts(&s.colopts, -1);
1558 finalize_deferred_config(&s);
1560 handle_untracked_files_arg(&s);
1561 handle_ignored_arg(&s);
1563 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1564 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1565 die(_("Unsupported combination of ignored and untracked-files arguments"));
1567 parse_pathspec(&s.pathspec, 0,
1568 PATHSPEC_PREFER_FULL,
1569 prefix, argv);
1571 if (status_format != STATUS_FORMAT_PORCELAIN &&
1572 status_format != STATUS_FORMAT_PORCELAIN_V2)
1573 progress_flag = REFRESH_PROGRESS;
1574 repo_read_index(the_repository);
1575 refresh_index(the_repository->index,
1576 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1577 &s.pathspec, NULL, NULL);
1579 if (use_optional_locks())
1580 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1581 else
1582 fd = -1;
1584 s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1585 if (!s.is_initial)
1586 oidcpy(&s.oid_commit, &oid);
1588 s.ignore_submodule_arg = ignore_submodule_arg;
1589 s.status_format = status_format;
1590 s.verbose = verbose;
1591 if (no_renames != -1)
1592 s.detect_rename = !no_renames;
1593 if ((intptr_t)rename_score_arg != -1) {
1594 if (s.detect_rename < DIFF_DETECT_RENAME)
1595 s.detect_rename = DIFF_DETECT_RENAME;
1596 if (rename_score_arg)
1597 s.rename_score = parse_rename_score(&rename_score_arg);
1600 wt_status_collect(&s);
1602 if (0 <= fd)
1603 repo_update_index_if_able(the_repository, &index_lock);
1605 if (s.relative_paths)
1606 s.prefix = prefix;
1608 wt_status_print(&s);
1609 wt_status_collect_free_buffers(&s);
1611 return 0;
1614 static int git_commit_config(const char *k, const char *v,
1615 const struct config_context *ctx, void *cb)
1617 struct wt_status *s = cb;
1619 if (!strcmp(k, "commit.template"))
1620 return git_config_pathname(&template_file, k, v);
1621 if (!strcmp(k, "commit.status")) {
1622 include_status = git_config_bool(k, v);
1623 return 0;
1625 if (!strcmp(k, "commit.cleanup"))
1626 return git_config_string(&cleanup_arg, k, v);
1627 if (!strcmp(k, "commit.gpgsign")) {
1628 sign_commit = git_config_bool(k, v) ? "" : NULL;
1629 return 0;
1631 if (!strcmp(k, "commit.verbose")) {
1632 int is_bool;
1633 config_commit_verbose = git_config_bool_or_int(k, v, ctx->kvi,
1634 &is_bool);
1635 return 0;
1638 return git_status_config(k, v, ctx, s);
1641 int cmd_commit(int argc, const char **argv, const char *prefix)
1643 static struct wt_status s;
1644 static struct option builtin_commit_options[] = {
1645 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1646 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1648 OPT_GROUP(N_("Commit message options")),
1649 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1650 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1651 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1652 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1653 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1654 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1656 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1657 * and only translate <commit>.
1659 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1660 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1661 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1662 OPT_PASSTHRU_ARGV(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG),
1663 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1664 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1665 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1666 OPT_CLEANUP(&cleanup_arg),
1667 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1668 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1669 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1670 /* end commit message options */
1672 OPT_GROUP(N_("Commit contents options")),
1673 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1674 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1675 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1676 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1677 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1678 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1679 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1680 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1681 STATUS_FORMAT_SHORT),
1682 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1683 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1684 N_("compute full ahead/behind values")),
1685 OPT_SET_INT(0, "porcelain", &status_format,
1686 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1687 OPT_SET_INT(0, "long", &status_format,
1688 N_("show status in long format (default)"),
1689 STATUS_FORMAT_LONG),
1690 OPT_BOOL('z', "null", &s.null_termination,
1691 N_("terminate entries with NUL")),
1692 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1693 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1694 { 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" },
1695 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1696 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1697 /* end commit contents options */
1699 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1700 N_("ok to record an empty change")),
1701 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1702 N_("ok to record a change with an empty message")),
1704 OPT_END()
1707 struct strbuf sb = STRBUF_INIT;
1708 struct strbuf author_ident = STRBUF_INIT;
1709 const char *index_file, *reflog_msg;
1710 struct object_id oid;
1711 struct commit_list *parents = NULL;
1712 struct stat statbuf;
1713 struct commit *current_head = NULL;
1714 struct commit_extra_header *extra = NULL;
1715 struct strbuf err = STRBUF_INIT;
1716 int ret = 0;
1718 if (argc == 2 && !strcmp(argv[1], "-h"))
1719 usage_with_options(builtin_commit_usage, builtin_commit_options);
1721 prepare_repo_settings(the_repository);
1722 the_repository->settings.command_requires_full_index = 0;
1724 status_init_config(&s, git_commit_config);
1725 s.commit_template = 1;
1726 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1727 s.colopts = 0;
1729 if (repo_get_oid(the_repository, "HEAD", &oid))
1730 current_head = NULL;
1731 else {
1732 current_head = lookup_commit_or_die(&oid, "HEAD");
1733 if (repo_parse_commit(the_repository, current_head))
1734 die(_("could not parse HEAD commit"));
1736 verbose = -1; /* unspecified */
1737 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1738 builtin_commit_usage,
1739 prefix, current_head, &s);
1740 if (verbose == -1)
1741 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1743 if (dry_run)
1744 return dry_run_commit(argv, prefix, current_head, &s);
1745 index_file = prepare_index(argv, prefix, current_head, 0);
1747 /* Set up everything for writing the commit object. This includes
1748 running hooks, writing the trees, and interacting with the user. */
1749 if (!prepare_to_commit(index_file, prefix,
1750 current_head, &s, &author_ident)) {
1751 ret = 1;
1752 rollback_index_files();
1753 goto cleanup;
1756 /* Determine parents */
1757 reflog_msg = getenv("GIT_REFLOG_ACTION");
1758 if (!current_head) {
1759 if (!reflog_msg)
1760 reflog_msg = "commit (initial)";
1761 } else if (amend) {
1762 if (!reflog_msg)
1763 reflog_msg = "commit (amend)";
1764 parents = copy_commit_list(current_head->parents);
1765 } else if (whence == FROM_MERGE) {
1766 struct strbuf m = STRBUF_INIT;
1767 FILE *fp;
1768 int allow_fast_forward = 1;
1769 struct commit_list **pptr = &parents;
1771 if (!reflog_msg)
1772 reflog_msg = "commit (merge)";
1773 pptr = commit_list_append(current_head, pptr);
1774 fp = xfopen(git_path_merge_head(the_repository), "r");
1775 while (strbuf_getline_lf(&m, fp) != EOF) {
1776 struct commit *parent;
1778 parent = get_merge_parent(m.buf);
1779 if (!parent)
1780 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1781 pptr = commit_list_append(parent, pptr);
1783 fclose(fp);
1784 strbuf_release(&m);
1785 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1786 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1787 die_errno(_("could not read MERGE_MODE"));
1788 if (!strcmp(sb.buf, "no-ff"))
1789 allow_fast_forward = 0;
1791 if (allow_fast_forward)
1792 reduce_heads_replace(&parents);
1793 } else {
1794 if (!reflog_msg)
1795 reflog_msg = is_from_cherry_pick(whence)
1796 ? "commit (cherry-pick)"
1797 : is_from_rebase(whence)
1798 ? "commit (rebase)"
1799 : "commit";
1800 commit_list_insert(current_head, &parents);
1803 /* Finally, get the commit message */
1804 strbuf_reset(&sb);
1805 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1806 int saved_errno = errno;
1807 rollback_index_files();
1808 die(_("could not read commit message: %s"), strerror(saved_errno));
1811 cleanup_message(&sb, cleanup_mode, verbose);
1813 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1814 rollback_index_files();
1815 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1816 exit(1);
1818 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1819 rollback_index_files();
1820 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1821 exit(1);
1824 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1825 !allow_empty_message) {
1826 struct strbuf body = STRBUF_INIT;
1827 size_t len = commit_subject_length(sb.buf);
1828 strbuf_addstr(&body, sb.buf + len);
1829 if (message_is_empty(&body, cleanup_mode)) {
1830 rollback_index_files();
1831 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1832 exit(1);
1834 strbuf_release(&body);
1837 if (amend) {
1838 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1839 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1840 } else {
1841 struct commit_extra_header **tail = &extra;
1842 append_merge_tag_headers(parents, &tail);
1845 if (commit_tree_extended(sb.buf, sb.len, &the_repository->index->cache_tree->oid,
1846 parents, &oid, author_ident.buf, NULL,
1847 sign_commit, extra)) {
1848 rollback_index_files();
1849 die(_("failed to write commit object"));
1852 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1853 &err)) {
1854 rollback_index_files();
1855 die("%s", err.buf);
1858 sequencer_post_commit_cleanup(the_repository, 0);
1859 unlink(git_path_merge_head(the_repository));
1860 unlink(git_path_merge_msg(the_repository));
1861 unlink(git_path_merge_mode(the_repository));
1862 unlink(git_path_squash_msg(the_repository));
1864 if (commit_index_files())
1865 die(_("repository has been updated, but unable to write\n"
1866 "new index file. Check that disk is not full and quota is\n"
1867 "not exceeded, and then \"git restore --staged :/\" to recover."));
1869 git_test_write_commit_graph_or_die();
1871 repo_rerere(the_repository, 0);
1872 run_auto_maintenance(quiet);
1873 run_commit_hook(use_editor, get_index_file(), NULL, "post-commit",
1874 NULL);
1875 if (amend && !no_post_rewrite) {
1876 commit_post_rewrite(the_repository, current_head, &oid);
1878 if (!quiet) {
1879 unsigned int flags = 0;
1881 if (!current_head)
1882 flags |= SUMMARY_INITIAL_COMMIT;
1883 if (author_date_is_interesting())
1884 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1885 print_commit_summary(the_repository, prefix,
1886 &oid, flags);
1889 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1891 cleanup:
1892 free_commit_extra_headers(extra);
1893 free_commit_list(parents);
1894 strbuf_release(&author_ident);
1895 strbuf_release(&err);
1896 strbuf_release(&sb);
1897 free(logfile);
1898 free(template_file);
1899 return ret;