Be more user-friendly when refusing to do something because of conflict.
[git.git] / builtin-commit.c
blobc58712c5393245c62edc082a168c690bd7ecb466
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 "cache.h"
9 #include "cache-tree.h"
10 #include "color.h"
11 #include "dir.h"
12 #include "builtin.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "commit.h"
16 #include "revision.h"
17 #include "wt-status.h"
18 #include "run-command.h"
19 #include "refs.h"
20 #include "log-tree.h"
21 #include "strbuf.h"
22 #include "utf8.h"
23 #include "parse-options.h"
24 #include "string-list.h"
25 #include "rerere.h"
26 #include "unpack-trees.h"
28 static const char * const builtin_commit_usage[] = {
29 "git commit [options] [--] <filepattern>...",
30 NULL
33 static const char * const builtin_status_usage[] = {
34 "git status [options] [--] <filepattern>...",
35 NULL
38 static unsigned char head_sha1[20], merge_head_sha1[20];
39 static char *use_message_buffer;
40 static const char commit_editmsg[] = "COMMIT_EDITMSG";
41 static struct lock_file index_lock; /* real index */
42 static struct lock_file false_lock; /* used only for partial commits */
43 static enum {
44 COMMIT_AS_IS = 1,
45 COMMIT_NORMAL,
46 COMMIT_PARTIAL,
47 } commit_style;
49 static const char *logfile, *force_author;
50 static const char *template_file;
51 static char *edit_message, *use_message;
52 static char *author_name, *author_email, *author_date;
53 static int all, edit_flag, also, interactive, only, amend, signoff;
54 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
55 static char *untracked_files_arg;
57 * The default commit message cleanup mode will remove the lines
58 * beginning with # (shell comments) and leading and trailing
59 * whitespaces (empty lines or containing only whitespaces)
60 * if editor is used, and only the whitespaces if the message
61 * is specified explicitly.
63 static enum {
64 CLEANUP_SPACE,
65 CLEANUP_NONE,
66 CLEANUP_ALL,
67 } cleanup_mode;
68 static char *cleanup_arg;
70 static int use_editor = 1, initial_commit, in_merge;
71 static const char *only_include_assumed;
72 static struct strbuf message;
74 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
76 struct strbuf *buf = opt->value;
77 if (unset)
78 strbuf_setlen(buf, 0);
79 else {
80 strbuf_addstr(buf, arg);
81 strbuf_addstr(buf, "\n\n");
83 return 0;
86 static struct option builtin_commit_options[] = {
87 OPT__QUIET(&quiet),
88 OPT__VERBOSE(&verbose),
89 OPT_GROUP("Commit message options"),
91 OPT_FILENAME('F', "file", &logfile, "read log from file"),
92 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
93 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
94 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
95 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
96 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
97 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
98 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
99 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
101 OPT_GROUP("Commit contents options"),
102 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
103 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
104 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
105 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
106 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
107 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
108 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
109 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, "mode", "show untracked files, optional modes: all, normal, no. (Default: all)", PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
110 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
111 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
113 OPT_END()
116 static void rollback_index_files(void)
118 switch (commit_style) {
119 case COMMIT_AS_IS:
120 break; /* nothing to do */
121 case COMMIT_NORMAL:
122 rollback_lock_file(&index_lock);
123 break;
124 case COMMIT_PARTIAL:
125 rollback_lock_file(&index_lock);
126 rollback_lock_file(&false_lock);
127 break;
131 static int commit_index_files(void)
133 int err = 0;
135 switch (commit_style) {
136 case COMMIT_AS_IS:
137 break; /* nothing to do */
138 case COMMIT_NORMAL:
139 err = commit_lock_file(&index_lock);
140 break;
141 case COMMIT_PARTIAL:
142 err = commit_lock_file(&index_lock);
143 rollback_lock_file(&false_lock);
144 break;
147 return err;
151 * Take a union of paths in the index and the named tree (typically, "HEAD"),
152 * and return the paths that match the given pattern in list.
154 static int list_paths(struct string_list *list, const char *with_tree,
155 const char *prefix, const char **pattern)
157 int i;
158 char *m;
160 for (i = 0; pattern[i]; i++)
162 m = xcalloc(1, i);
164 if (with_tree)
165 overlay_tree_on_cache(with_tree, prefix);
167 for (i = 0; i < active_nr; i++) {
168 struct cache_entry *ce = active_cache[i];
169 if (ce->ce_flags & CE_UPDATE)
170 continue;
171 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
172 continue;
173 string_list_insert(ce->name, list);
176 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
179 static void add_remove_files(struct string_list *list)
181 int i;
182 for (i = 0; i < list->nr; i++) {
183 struct stat st;
184 struct string_list_item *p = &(list->items[i]);
186 if (!lstat(p->string, &st)) {
187 if (add_to_cache(p->string, &st, 0))
188 die("updating files failed");
189 } else
190 remove_file_from_cache(p->string);
194 static void create_base_index(void)
196 struct tree *tree;
197 struct unpack_trees_options opts;
198 struct tree_desc t;
200 if (initial_commit) {
201 discard_cache();
202 return;
205 memset(&opts, 0, sizeof(opts));
206 opts.head_idx = 1;
207 opts.index_only = 1;
208 opts.merge = 1;
209 opts.src_index = &the_index;
210 opts.dst_index = &the_index;
212 opts.fn = oneway_merge;
213 tree = parse_tree_indirect(head_sha1);
214 if (!tree)
215 die("failed to unpack HEAD tree object");
216 parse_tree(tree);
217 init_tree_desc(&t, tree->buffer, tree->size);
218 if (unpack_trees(1, &t, &opts))
219 exit(128); /* We've already reported the error, finish dying */
222 static void refresh_cache_or_die(int refresh_flags)
225 * refresh_flags contains REFRESH_QUIET, so the only errors
226 * are for unmerged entries.
228 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
229 die_resolve_conflict("commit");
232 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
234 int fd;
235 struct string_list partial;
236 const char **pathspec = NULL;
237 int refresh_flags = REFRESH_QUIET;
239 if (is_status)
240 refresh_flags |= REFRESH_UNMERGED;
241 if (interactive) {
242 if (interactive_add(argc, argv, prefix) != 0)
243 die("interactive add failed");
244 if (read_cache_preload(NULL) < 0)
245 die("index file corrupt");
246 commit_style = COMMIT_AS_IS;
247 return get_index_file();
250 if (*argv)
251 pathspec = get_pathspec(prefix, argv);
253 if (read_cache_preload(pathspec) < 0)
254 die("index file corrupt");
257 * Non partial, non as-is commit.
259 * (1) get the real index;
260 * (2) update the_index as necessary;
261 * (3) write the_index out to the real index (still locked);
262 * (4) return the name of the locked index file.
264 * The caller should run hooks on the locked real index, and
265 * (A) if all goes well, commit the real index;
266 * (B) on failure, rollback the real index.
268 if (all || (also && pathspec && *pathspec)) {
269 int fd = hold_locked_index(&index_lock, 1);
270 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
271 refresh_cache_or_die(refresh_flags);
272 if (write_cache(fd, active_cache, active_nr) ||
273 close_lock_file(&index_lock))
274 die("unable to write new_index file");
275 commit_style = COMMIT_NORMAL;
276 return index_lock.filename;
280 * As-is commit.
282 * (1) return the name of the real index file.
284 * The caller should run hooks on the real index, and run
285 * hooks on the real index, and create commit from the_index.
286 * We still need to refresh the index here.
288 if (!pathspec || !*pathspec) {
289 fd = hold_locked_index(&index_lock, 1);
290 refresh_cache_or_die(refresh_flags);
291 if (write_cache(fd, active_cache, active_nr) ||
292 commit_locked_index(&index_lock))
293 die("unable to write new_index file");
294 commit_style = COMMIT_AS_IS;
295 return get_index_file();
299 * A partial commit.
301 * (0) find the set of affected paths;
302 * (1) get lock on the real index file;
303 * (2) update the_index with the given paths;
304 * (3) write the_index out to the real index (still locked);
305 * (4) get lock on the false index file;
306 * (5) reset the_index from HEAD;
307 * (6) update the_index the same way as (2);
308 * (7) write the_index out to the false index file;
309 * (8) return the name of the false index file (still locked);
311 * The caller should run hooks on the locked false index, and
312 * create commit from it. Then
313 * (A) if all goes well, commit the real index;
314 * (B) on failure, rollback the real index;
315 * In either case, rollback the false index.
317 commit_style = COMMIT_PARTIAL;
319 if (file_exists(git_path("MERGE_HEAD")))
320 die("cannot do a partial commit during a merge.");
322 memset(&partial, 0, sizeof(partial));
323 partial.strdup_strings = 1;
324 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
325 exit(1);
327 discard_cache();
328 if (read_cache() < 0)
329 die("cannot read the index");
331 fd = hold_locked_index(&index_lock, 1);
332 add_remove_files(&partial);
333 refresh_cache(REFRESH_QUIET);
334 if (write_cache(fd, active_cache, active_nr) ||
335 close_lock_file(&index_lock))
336 die("unable to write new_index file");
338 fd = hold_lock_file_for_update(&false_lock,
339 git_path("next-index-%"PRIuMAX,
340 (uintmax_t) getpid()),
341 LOCK_DIE_ON_ERROR);
343 create_base_index();
344 add_remove_files(&partial);
345 refresh_cache(REFRESH_QUIET);
347 if (write_cache(fd, active_cache, active_nr) ||
348 close_lock_file(&false_lock))
349 die("unable to write temporary index file");
351 discard_cache();
352 read_cache_from(false_lock.filename);
354 return false_lock.filename;
357 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
358 struct wt_status *s)
360 if (s->relative_paths)
361 s->prefix = prefix;
363 if (amend) {
364 s->amend = 1;
365 s->reference = "HEAD^1";
367 s->verbose = verbose;
368 s->index_file = index_file;
369 s->fp = fp;
370 s->nowarn = nowarn;
372 wt_status_print(s);
374 return s->commitable;
377 static int is_a_merge(const unsigned char *sha1)
379 struct commit *commit = lookup_commit(sha1);
380 if (!commit || parse_commit(commit))
381 die("could not parse HEAD commit");
382 return !!(commit->parents && commit->parents->next);
385 static const char sign_off_header[] = "Signed-off-by: ";
387 static void determine_author_info(void)
389 char *name, *email, *date;
391 name = getenv("GIT_AUTHOR_NAME");
392 email = getenv("GIT_AUTHOR_EMAIL");
393 date = getenv("GIT_AUTHOR_DATE");
395 if (use_message && !renew_authorship) {
396 const char *a, *lb, *rb, *eol;
398 a = strstr(use_message_buffer, "\nauthor ");
399 if (!a)
400 die("invalid commit: %s", use_message);
402 lb = strstr(a + 8, " <");
403 rb = strstr(a + 8, "> ");
404 eol = strchr(a + 8, '\n');
405 if (!lb || !rb || !eol)
406 die("invalid commit: %s", use_message);
408 name = xstrndup(a + 8, lb - (a + 8));
409 email = xstrndup(lb + 2, rb - (lb + 2));
410 date = xstrndup(rb + 2, eol - (rb + 2));
413 if (force_author) {
414 const char *lb = strstr(force_author, " <");
415 const char *rb = strchr(force_author, '>');
417 if (!lb || !rb)
418 die("malformed --author parameter");
419 name = xstrndup(force_author, lb - force_author);
420 email = xstrndup(lb + 2, rb - (lb + 2));
423 author_name = name;
424 author_email = email;
425 author_date = date;
428 static int ends_rfc2822_footer(struct strbuf *sb)
430 int ch;
431 int hit = 0;
432 int i, j, k;
433 int len = sb->len;
434 int first = 1;
435 const char *buf = sb->buf;
437 for (i = len - 1; i > 0; i--) {
438 if (hit && buf[i] == '\n')
439 break;
440 hit = (buf[i] == '\n');
443 while (i < len - 1 && buf[i] == '\n')
444 i++;
446 for (; i < len; i = k) {
447 for (k = i; k < len && buf[k] != '\n'; k++)
448 ; /* do nothing */
449 k++;
451 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
452 continue;
454 first = 0;
456 for (j = 0; i + j < len; j++) {
457 ch = buf[i + j];
458 if (ch == ':')
459 break;
460 if (isalnum(ch) ||
461 (ch == '-'))
462 continue;
463 return 0;
466 return 1;
469 static int prepare_to_commit(const char *index_file, const char *prefix,
470 struct wt_status *s)
472 struct stat statbuf;
473 int commitable, saved_color_setting;
474 struct strbuf sb = STRBUF_INIT;
475 char *buffer;
476 FILE *fp;
477 const char *hook_arg1 = NULL;
478 const char *hook_arg2 = NULL;
479 int ident_shown = 0;
481 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
482 return 0;
484 if (message.len) {
485 strbuf_addbuf(&sb, &message);
486 hook_arg1 = "message";
487 } else if (logfile && !strcmp(logfile, "-")) {
488 if (isatty(0))
489 fprintf(stderr, "(reading log message from standard input)\n");
490 if (strbuf_read(&sb, 0, 0) < 0)
491 die_errno("could not read log from standard input");
492 hook_arg1 = "message";
493 } else if (logfile) {
494 if (strbuf_read_file(&sb, logfile, 0) < 0)
495 die_errno("could not read log file '%s'",
496 logfile);
497 hook_arg1 = "message";
498 } else if (use_message) {
499 buffer = strstr(use_message_buffer, "\n\n");
500 if (!buffer || buffer[2] == '\0')
501 die("commit has empty message");
502 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
503 hook_arg1 = "commit";
504 hook_arg2 = use_message;
505 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
506 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
507 die_errno("could not read MERGE_MSG");
508 hook_arg1 = "merge";
509 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
510 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
511 die_errno("could not read SQUASH_MSG");
512 hook_arg1 = "squash";
513 } else if (template_file && !stat(template_file, &statbuf)) {
514 if (strbuf_read_file(&sb, template_file, 0) < 0)
515 die_errno("could not read '%s'", template_file);
516 hook_arg1 = "template";
520 * This final case does not modify the template message,
521 * it just sets the argument to the prepare-commit-msg hook.
523 else if (in_merge)
524 hook_arg1 = "merge";
526 fp = fopen(git_path(commit_editmsg), "w");
527 if (fp == NULL)
528 die_errno("could not open '%s'", git_path(commit_editmsg));
530 if (cleanup_mode != CLEANUP_NONE)
531 stripspace(&sb, 0);
533 if (signoff) {
534 struct strbuf sob = STRBUF_INIT;
535 int i;
537 strbuf_addstr(&sob, sign_off_header);
538 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
539 getenv("GIT_COMMITTER_EMAIL")));
540 strbuf_addch(&sob, '\n');
541 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
542 ; /* do nothing */
543 if (prefixcmp(sb.buf + i, sob.buf)) {
544 if (!i || !ends_rfc2822_footer(&sb))
545 strbuf_addch(&sb, '\n');
546 strbuf_addbuf(&sb, &sob);
548 strbuf_release(&sob);
551 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
552 die_errno("could not write commit template");
554 strbuf_release(&sb);
556 determine_author_info();
558 /* This checks if committer ident is explicitly given */
559 git_committer_info(0);
560 if (use_editor) {
561 char *author_ident;
562 const char *committer_ident;
564 if (in_merge)
565 fprintf(fp,
566 "#\n"
567 "# It looks like you may be committing a MERGE.\n"
568 "# If this is not correct, please remove the file\n"
569 "# %s\n"
570 "# and try again.\n"
571 "#\n",
572 git_path("MERGE_HEAD"));
574 fprintf(fp,
575 "\n"
576 "# Please enter the commit message for your changes.");
577 if (cleanup_mode == CLEANUP_ALL)
578 fprintf(fp,
579 " Lines starting\n"
580 "# with '#' will be ignored, and an empty"
581 " message aborts the commit.\n");
582 else /* CLEANUP_SPACE, that is. */
583 fprintf(fp,
584 " Lines starting\n"
585 "# with '#' will be kept; you may remove them"
586 " yourself if you want to.\n"
587 "# An empty message aborts the commit.\n");
588 if (only_include_assumed)
589 fprintf(fp, "# %s\n", only_include_assumed);
591 author_ident = xstrdup(fmt_name(author_name, author_email));
592 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
593 getenv("GIT_COMMITTER_EMAIL"));
594 if (strcmp(author_ident, committer_ident))
595 fprintf(fp,
596 "%s"
597 "# Author: %s\n",
598 ident_shown++ ? "" : "#\n",
599 author_ident);
600 free(author_ident);
602 if (!user_ident_explicitly_given)
603 fprintf(fp,
604 "%s"
605 "# Committer: %s\n",
606 ident_shown++ ? "" : "#\n",
607 committer_ident);
609 if (ident_shown)
610 fprintf(fp, "#\n");
612 saved_color_setting = s->use_color;
613 s->use_color = 0;
614 commitable = run_status(fp, index_file, prefix, 1, s);
615 s->use_color = saved_color_setting;
616 } else {
617 unsigned char sha1[20];
618 const char *parent = "HEAD";
620 if (!active_nr && read_cache() < 0)
621 die("Cannot read index");
623 if (amend)
624 parent = "HEAD^1";
626 if (get_sha1(parent, sha1))
627 commitable = !!active_nr;
628 else
629 commitable = index_differs_from(parent, 0);
632 fclose(fp);
634 if (!commitable && !in_merge && !allow_empty &&
635 !(amend && is_a_merge(head_sha1))) {
636 run_status(stdout, index_file, prefix, 0, s);
637 return 0;
641 * Re-read the index as pre-commit hook could have updated it,
642 * and write it out as a tree. We must do this before we invoke
643 * the editor and after we invoke run_status above.
645 discard_cache();
646 read_cache_from(index_file);
647 if (!active_cache_tree)
648 active_cache_tree = cache_tree();
649 if (cache_tree_update(active_cache_tree,
650 active_cache, active_nr, 0, 0) < 0) {
651 error("Error building trees");
652 return 0;
655 if (run_hook(index_file, "prepare-commit-msg",
656 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
657 return 0;
659 if (use_editor) {
660 char index[PATH_MAX];
661 const char *env[2] = { index, NULL };
662 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
663 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
664 fprintf(stderr,
665 "Please supply the message using either -m or -F option.\n");
666 exit(1);
670 if (!no_verify &&
671 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
672 return 0;
675 return 1;
679 * Find out if the message in the strbuf contains only whitespace and
680 * Signed-off-by lines.
682 static int message_is_empty(struct strbuf *sb)
684 struct strbuf tmpl = STRBUF_INIT;
685 const char *nl;
686 int eol, i, start = 0;
688 if (cleanup_mode == CLEANUP_NONE && sb->len)
689 return 0;
691 /* See if the template is just a prefix of the message. */
692 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
693 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
694 if (start + tmpl.len <= sb->len &&
695 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
696 start += tmpl.len;
698 strbuf_release(&tmpl);
700 /* Check if the rest is just whitespace and Signed-of-by's. */
701 for (i = start; i < sb->len; i++) {
702 nl = memchr(sb->buf + i, '\n', sb->len - i);
703 if (nl)
704 eol = nl - sb->buf;
705 else
706 eol = sb->len;
708 if (strlen(sign_off_header) <= eol - i &&
709 !prefixcmp(sb->buf + i, sign_off_header)) {
710 i = eol;
711 continue;
713 while (i < eol)
714 if (!isspace(sb->buf[i++]))
715 return 0;
718 return 1;
721 static const char *find_author_by_nickname(const char *name)
723 struct rev_info revs;
724 struct commit *commit;
725 struct strbuf buf = STRBUF_INIT;
726 const char *av[20];
727 int ac = 0;
729 init_revisions(&revs, NULL);
730 strbuf_addf(&buf, "--author=%s", name);
731 av[++ac] = "--all";
732 av[++ac] = "-i";
733 av[++ac] = buf.buf;
734 av[++ac] = NULL;
735 setup_revisions(ac, av, &revs, NULL);
736 prepare_revision_walk(&revs);
737 commit = get_revision(&revs);
738 if (commit) {
739 struct pretty_print_context ctx = {0};
740 ctx.date_mode = DATE_NORMAL;
741 strbuf_release(&buf);
742 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
743 return strbuf_detach(&buf, NULL);
745 die("No existing author found with '%s'", name);
748 static int parse_and_validate_options(int argc, const char *argv[],
749 const char * const usage[],
750 const char *prefix,
751 struct wt_status *s)
753 int f = 0;
755 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
758 if (force_author && !strchr(force_author, '>'))
759 force_author = find_author_by_nickname(force_author);
761 if (force_author && renew_authorship)
762 die("Using both --reset-author and --author does not make sense");
764 if (logfile || message.len || use_message)
765 use_editor = 0;
766 if (edit_flag)
767 use_editor = 1;
768 if (!use_editor)
769 setenv("GIT_EDITOR", ":", 1);
771 if (get_sha1("HEAD", head_sha1))
772 initial_commit = 1;
774 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
775 in_merge = 1;
777 /* Sanity check options */
778 if (amend && initial_commit)
779 die("You have nothing to amend.");
780 if (amend && in_merge)
781 die("You are in the middle of a merge -- cannot amend.");
783 if (use_message)
784 f++;
785 if (edit_message)
786 f++;
787 if (logfile)
788 f++;
789 if (f > 1)
790 die("Only one of -c/-C/-F can be used.");
791 if (message.len && f > 0)
792 die("Option -m cannot be combined with -c/-C/-F.");
793 if (edit_message)
794 use_message = edit_message;
795 if (amend && !use_message)
796 use_message = "HEAD";
797 if (!use_message && renew_authorship)
798 die("--reset-author can be used only with -C, -c or --amend.");
799 if (use_message) {
800 unsigned char sha1[20];
801 static char utf8[] = "UTF-8";
802 const char *out_enc;
803 char *enc, *end;
804 struct commit *commit;
806 if (get_sha1(use_message, sha1))
807 die("could not lookup commit %s", use_message);
808 commit = lookup_commit_reference(sha1);
809 if (!commit || parse_commit(commit))
810 die("could not parse commit %s", use_message);
812 enc = strstr(commit->buffer, "\nencoding");
813 if (enc) {
814 end = strchr(enc + 10, '\n');
815 enc = xstrndup(enc + 10, end - (enc + 10));
816 } else {
817 enc = utf8;
819 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
821 if (strcmp(out_enc, enc))
822 use_message_buffer =
823 reencode_string(commit->buffer, out_enc, enc);
826 * If we failed to reencode the buffer, just copy it
827 * byte for byte so the user can try to fix it up.
828 * This also handles the case where input and output
829 * encodings are identical.
831 if (use_message_buffer == NULL)
832 use_message_buffer = xstrdup(commit->buffer);
833 if (enc != utf8)
834 free(enc);
837 if (!!also + !!only + !!all + !!interactive > 1)
838 die("Only one of --include/--only/--all/--interactive can be used.");
839 if (argc == 0 && (also || (only && !amend)))
840 die("No paths with --include/--only does not make sense.");
841 if (argc == 0 && only && amend)
842 only_include_assumed = "Clever... amending the last one with dirty index.";
843 if (argc > 0 && !also && !only)
844 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
845 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
846 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
847 else if (!strcmp(cleanup_arg, "verbatim"))
848 cleanup_mode = CLEANUP_NONE;
849 else if (!strcmp(cleanup_arg, "whitespace"))
850 cleanup_mode = CLEANUP_SPACE;
851 else if (!strcmp(cleanup_arg, "strip"))
852 cleanup_mode = CLEANUP_ALL;
853 else
854 die("Invalid cleanup mode %s", cleanup_arg);
856 if (!untracked_files_arg)
857 ; /* default already initialized */
858 else if (!strcmp(untracked_files_arg, "no"))
859 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
860 else if (!strcmp(untracked_files_arg, "normal"))
861 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
862 else if (!strcmp(untracked_files_arg, "all"))
863 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
864 else
865 die("Invalid untracked files mode '%s'", untracked_files_arg);
867 if (all && argc > 0)
868 die("Paths with -a does not make sense.");
869 else if (interactive && argc > 0)
870 die("Paths with --interactive does not make sense.");
872 return argc;
875 static int dry_run_commit(int argc, const char **argv, const char *prefix,
876 struct wt_status *s)
878 int commitable;
879 const char *index_file;
881 index_file = prepare_index(argc, argv, prefix, 1);
882 commitable = run_status(stdout, index_file, prefix, 0, s);
883 rollback_index_files();
885 return commitable ? 0 : 1;
888 static int parse_status_slot(const char *var, int offset)
890 if (!strcasecmp(var+offset, "header"))
891 return WT_STATUS_HEADER;
892 if (!strcasecmp(var+offset, "updated")
893 || !strcasecmp(var+offset, "added"))
894 return WT_STATUS_UPDATED;
895 if (!strcasecmp(var+offset, "changed"))
896 return WT_STATUS_CHANGED;
897 if (!strcasecmp(var+offset, "untracked"))
898 return WT_STATUS_UNTRACKED;
899 if (!strcasecmp(var+offset, "nobranch"))
900 return WT_STATUS_NOBRANCH;
901 if (!strcasecmp(var+offset, "unmerged"))
902 return WT_STATUS_UNMERGED;
903 return -1;
906 static int git_status_config(const char *k, const char *v, void *cb)
908 struct wt_status *s = cb;
910 if (!strcmp(k, "status.submodulesummary")) {
911 int is_bool;
912 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
913 if (is_bool && s->submodule_summary)
914 s->submodule_summary = -1;
915 return 0;
917 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
918 s->use_color = git_config_colorbool(k, v, -1);
919 return 0;
921 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
922 int slot = parse_status_slot(k, 13);
923 if (slot < 0)
924 return 0;
925 if (!v)
926 return config_error_nonbool(k);
927 color_parse(v, k, s->color_palette[slot]);
928 return 0;
930 if (!strcmp(k, "status.relativepaths")) {
931 s->relative_paths = git_config_bool(k, v);
932 return 0;
934 if (!strcmp(k, "status.showuntrackedfiles")) {
935 if (!v)
936 return config_error_nonbool(k);
937 else if (!strcmp(v, "no"))
938 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
939 else if (!strcmp(v, "normal"))
940 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
941 else if (!strcmp(v, "all"))
942 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
943 else
944 return error("Invalid untracked files mode '%s'", v);
945 return 0;
947 return git_diff_ui_config(k, v, NULL);
950 int cmd_status(int argc, const char **argv, const char *prefix)
952 struct wt_status s;
954 wt_status_prepare(&s);
955 git_config(git_status_config, &s);
956 if (s.use_color == -1)
957 s.use_color = git_use_color_default;
958 if (diff_use_color_default == -1)
959 diff_use_color_default = git_use_color_default;
961 argc = parse_and_validate_options(argc, argv, builtin_status_usage,
962 prefix, &s);
963 return dry_run_commit(argc, argv, prefix, &s);
966 static void print_summary(const char *prefix, const unsigned char *sha1)
968 struct rev_info rev;
969 struct commit *commit;
970 static const char *format = "format:%h] %s";
971 unsigned char junk_sha1[20];
972 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
974 commit = lookup_commit(sha1);
975 if (!commit)
976 die("couldn't look up newly created commit");
977 if (!commit || parse_commit(commit))
978 die("could not parse newly created commit");
980 init_revisions(&rev, prefix);
981 setup_revisions(0, NULL, &rev, NULL);
983 rev.abbrev = 0;
984 rev.diff = 1;
985 rev.diffopt.output_format =
986 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
988 rev.verbose_header = 1;
989 rev.show_root_diff = 1;
990 get_commit_format(format, &rev);
991 rev.always_show_header = 0;
992 rev.diffopt.detect_rename = 1;
993 rev.diffopt.rename_limit = 100;
994 rev.diffopt.break_opt = 0;
995 diff_setup_done(&rev.diffopt);
997 printf("[%s%s ",
998 !prefixcmp(head, "refs/heads/") ?
999 head + 11 :
1000 !strcmp(head, "HEAD") ?
1001 "detached HEAD" :
1002 head,
1003 initial_commit ? " (root-commit)" : "");
1005 if (!log_tree_commit(&rev, commit)) {
1006 struct pretty_print_context ctx = {0};
1007 struct strbuf buf = STRBUF_INIT;
1008 ctx.date_mode = DATE_NORMAL;
1009 format_commit_message(commit, format + 7, &buf, &ctx);
1010 printf("%s\n", buf.buf);
1011 strbuf_release(&buf);
1015 static int git_commit_config(const char *k, const char *v, void *cb)
1017 struct wt_status *s = cb;
1019 if (!strcmp(k, "commit.template"))
1020 return git_config_pathname(&template_file, k, v);
1022 return git_status_config(k, v, s);
1025 int cmd_commit(int argc, const char **argv, const char *prefix)
1027 struct strbuf sb = STRBUF_INIT;
1028 const char *index_file, *reflog_msg;
1029 char *nl, *p;
1030 unsigned char commit_sha1[20];
1031 struct ref_lock *ref_lock;
1032 struct commit_list *parents = NULL, **pptr = &parents;
1033 struct stat statbuf;
1034 int allow_fast_forward = 1;
1035 struct wt_status s;
1037 wt_status_prepare(&s);
1038 git_config(git_commit_config, &s);
1040 if (s.use_color == -1)
1041 s.use_color = git_use_color_default;
1043 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1044 prefix, &s);
1045 if (dry_run) {
1046 if (diff_use_color_default == -1)
1047 diff_use_color_default = git_use_color_default;
1048 return dry_run_commit(argc, argv, prefix, &s);
1050 index_file = prepare_index(argc, argv, prefix, 0);
1052 /* Set up everything for writing the commit object. This includes
1053 running hooks, writing the trees, and interacting with the user. */
1054 if (!prepare_to_commit(index_file, prefix, &s)) {
1055 rollback_index_files();
1056 return 1;
1059 /* Determine parents */
1060 if (initial_commit) {
1061 reflog_msg = "commit (initial)";
1062 } else if (amend) {
1063 struct commit_list *c;
1064 struct commit *commit;
1066 reflog_msg = "commit (amend)";
1067 commit = lookup_commit(head_sha1);
1068 if (!commit || parse_commit(commit))
1069 die("could not parse HEAD commit");
1071 for (c = commit->parents; c; c = c->next)
1072 pptr = &commit_list_insert(c->item, pptr)->next;
1073 } else if (in_merge) {
1074 struct strbuf m = STRBUF_INIT;
1075 FILE *fp;
1077 reflog_msg = "commit (merge)";
1078 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1079 fp = fopen(git_path("MERGE_HEAD"), "r");
1080 if (fp == NULL)
1081 die_errno("could not open '%s' for reading",
1082 git_path("MERGE_HEAD"));
1083 while (strbuf_getline(&m, fp, '\n') != EOF) {
1084 unsigned char sha1[20];
1085 if (get_sha1_hex(m.buf, sha1) < 0)
1086 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1087 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1089 fclose(fp);
1090 strbuf_release(&m);
1091 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1092 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1093 die_errno("could not read MERGE_MODE");
1094 if (!strcmp(sb.buf, "no-ff"))
1095 allow_fast_forward = 0;
1097 if (allow_fast_forward)
1098 parents = reduce_heads(parents);
1099 } else {
1100 reflog_msg = "commit";
1101 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1104 /* Finally, get the commit message */
1105 strbuf_reset(&sb);
1106 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1107 int saved_errno = errno;
1108 rollback_index_files();
1109 die("could not read commit message: %s", strerror(saved_errno));
1112 /* Truncate the message just before the diff, if any. */
1113 if (verbose) {
1114 p = strstr(sb.buf, "\ndiff --git ");
1115 if (p != NULL)
1116 strbuf_setlen(&sb, p - sb.buf + 1);
1119 if (cleanup_mode != CLEANUP_NONE)
1120 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1121 if (message_is_empty(&sb)) {
1122 rollback_index_files();
1123 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1124 exit(1);
1127 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1128 fmt_ident(author_name, author_email, author_date,
1129 IDENT_ERROR_ON_NO_NAME))) {
1130 rollback_index_files();
1131 die("failed to write commit object");
1134 ref_lock = lock_any_ref_for_update("HEAD",
1135 initial_commit ? NULL : head_sha1,
1138 nl = strchr(sb.buf, '\n');
1139 if (nl)
1140 strbuf_setlen(&sb, nl + 1 - sb.buf);
1141 else
1142 strbuf_addch(&sb, '\n');
1143 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1144 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1146 if (!ref_lock) {
1147 rollback_index_files();
1148 die("cannot lock HEAD ref");
1150 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1151 rollback_index_files();
1152 die("cannot update HEAD ref");
1155 unlink(git_path("MERGE_HEAD"));
1156 unlink(git_path("MERGE_MSG"));
1157 unlink(git_path("MERGE_MODE"));
1158 unlink(git_path("SQUASH_MSG"));
1160 if (commit_index_files())
1161 die ("Repository has been updated, but unable to write\n"
1162 "new_index file. Check that disk is not full or quota is\n"
1163 "not exceeded, and then \"git reset HEAD\" to recover.");
1165 rerere();
1166 run_hook(get_index_file(), "post-commit", NULL);
1167 if (!quiet)
1168 print_summary(prefix, commit_sha1);
1170 return 0;