commit: correctly respect skip-worktree bit
[alt-git.git] / builtin-commit.c
blob9d596903bfa2118e1385ebce9625bc14a63d53e7
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;
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('s', "signoff", &signoff, "add Signed-off-by:"),
97 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
98 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
100 OPT_GROUP("Commit contents options"),
101 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
102 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
103 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
104 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
105 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
106 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
107 { 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" },
108 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
109 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
111 OPT_END()
114 static void rollback_index_files(void)
116 switch (commit_style) {
117 case COMMIT_AS_IS:
118 break; /* nothing to do */
119 case COMMIT_NORMAL:
120 rollback_lock_file(&index_lock);
121 break;
122 case COMMIT_PARTIAL:
123 rollback_lock_file(&index_lock);
124 rollback_lock_file(&false_lock);
125 break;
129 static int commit_index_files(void)
131 int err = 0;
133 switch (commit_style) {
134 case COMMIT_AS_IS:
135 break; /* nothing to do */
136 case COMMIT_NORMAL:
137 err = commit_lock_file(&index_lock);
138 break;
139 case COMMIT_PARTIAL:
140 err = commit_lock_file(&index_lock);
141 rollback_lock_file(&false_lock);
142 break;
145 return err;
149 * Take a union of paths in the index and the named tree (typically, "HEAD"),
150 * and return the paths that match the given pattern in list.
152 static int list_paths(struct string_list *list, const char *with_tree,
153 const char *prefix, const char **pattern)
155 int i;
156 char *m;
158 for (i = 0; pattern[i]; i++)
160 m = xcalloc(1, i);
162 if (with_tree)
163 overlay_tree_on_cache(with_tree, prefix);
165 for (i = 0; i < active_nr; i++) {
166 struct cache_entry *ce = active_cache[i];
167 struct string_list_item *item;
169 if (ce->ce_flags & CE_UPDATE)
170 continue;
171 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
172 continue;
173 item = string_list_insert(ce->name, list);
174 if (ce_skip_worktree(ce))
175 item->util = item; /* better a valid pointer than a fake one */
178 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
181 static void add_remove_files(struct string_list *list)
183 int i;
184 for (i = 0; i < list->nr; i++) {
185 struct stat st;
186 struct string_list_item *p = &(list->items[i]);
188 /* p->util is skip-worktree */
189 if (p->util)
190 continue;
192 if (!lstat(p->string, &st)) {
193 if (add_to_cache(p->string, &st, 0))
194 die("updating files failed");
195 } else
196 remove_file_from_cache(p->string);
200 static void create_base_index(void)
202 struct tree *tree;
203 struct unpack_trees_options opts;
204 struct tree_desc t;
206 if (initial_commit) {
207 discard_cache();
208 return;
211 memset(&opts, 0, sizeof(opts));
212 opts.head_idx = 1;
213 opts.index_only = 1;
214 opts.merge = 1;
215 opts.src_index = &the_index;
216 opts.dst_index = &the_index;
218 opts.fn = oneway_merge;
219 tree = parse_tree_indirect(head_sha1);
220 if (!tree)
221 die("failed to unpack HEAD tree object");
222 parse_tree(tree);
223 init_tree_desc(&t, tree->buffer, tree->size);
224 if (unpack_trees(1, &t, &opts))
225 exit(128); /* We've already reported the error, finish dying */
228 static char *prepare_index(int argc, const char **argv, const char *prefix)
230 int fd;
231 struct string_list partial;
232 const char **pathspec = NULL;
234 if (interactive) {
235 if (interactive_add(argc, argv, prefix) != 0)
236 die("interactive add failed");
237 if (read_cache_preload(NULL) < 0)
238 die("index file corrupt");
239 commit_style = COMMIT_AS_IS;
240 return get_index_file();
243 if (*argv)
244 pathspec = get_pathspec(prefix, argv);
246 if (read_cache_preload(pathspec) < 0)
247 die("index file corrupt");
250 * Non partial, non as-is commit.
252 * (1) get the real index;
253 * (2) update the_index as necessary;
254 * (3) write the_index out to the real index (still locked);
255 * (4) return the name of the locked index file.
257 * The caller should run hooks on the locked real index, and
258 * (A) if all goes well, commit the real index;
259 * (B) on failure, rollback the real index.
261 if (all || (also && pathspec && *pathspec)) {
262 int fd = hold_locked_index(&index_lock, 1);
263 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
264 refresh_cache(REFRESH_QUIET);
265 if (write_cache(fd, active_cache, active_nr) ||
266 close_lock_file(&index_lock))
267 die("unable to write new_index file");
268 commit_style = COMMIT_NORMAL;
269 return index_lock.filename;
273 * As-is commit.
275 * (1) return the name of the real index file.
277 * The caller should run hooks on the real index, and run
278 * hooks on the real index, and create commit from the_index.
279 * We still need to refresh the index here.
281 if (!pathspec || !*pathspec) {
282 fd = hold_locked_index(&index_lock, 1);
283 refresh_cache(REFRESH_QUIET);
284 if (write_cache(fd, active_cache, active_nr) ||
285 commit_locked_index(&index_lock))
286 die("unable to write new_index file");
287 commit_style = COMMIT_AS_IS;
288 return get_index_file();
292 * A partial commit.
294 * (0) find the set of affected paths;
295 * (1) get lock on the real index file;
296 * (2) update the_index with the given paths;
297 * (3) write the_index out to the real index (still locked);
298 * (4) get lock on the false index file;
299 * (5) reset the_index from HEAD;
300 * (6) update the_index the same way as (2);
301 * (7) write the_index out to the false index file;
302 * (8) return the name of the false index file (still locked);
304 * The caller should run hooks on the locked false index, and
305 * create commit from it. Then
306 * (A) if all goes well, commit the real index;
307 * (B) on failure, rollback the real index;
308 * In either case, rollback the false index.
310 commit_style = COMMIT_PARTIAL;
312 if (file_exists(git_path("MERGE_HEAD")))
313 die("cannot do a partial commit during a merge.");
315 memset(&partial, 0, sizeof(partial));
316 partial.strdup_strings = 1;
317 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
318 exit(1);
320 discard_cache();
321 if (read_cache() < 0)
322 die("cannot read the index");
324 fd = hold_locked_index(&index_lock, 1);
325 add_remove_files(&partial);
326 refresh_cache(REFRESH_QUIET);
327 if (write_cache(fd, active_cache, active_nr) ||
328 close_lock_file(&index_lock))
329 die("unable to write new_index file");
331 fd = hold_lock_file_for_update(&false_lock,
332 git_path("next-index-%"PRIuMAX,
333 (uintmax_t) getpid()),
334 LOCK_DIE_ON_ERROR);
336 create_base_index();
337 add_remove_files(&partial);
338 refresh_cache(REFRESH_QUIET);
340 if (write_cache(fd, active_cache, active_nr) ||
341 close_lock_file(&false_lock))
342 die("unable to write temporary index file");
344 discard_cache();
345 read_cache_from(false_lock.filename);
347 return false_lock.filename;
350 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn)
352 struct wt_status s;
354 wt_status_prepare(&s);
355 if (wt_status_relative_paths)
356 s.prefix = prefix;
358 if (amend) {
359 s.amend = 1;
360 s.reference = "HEAD^1";
362 s.verbose = verbose;
363 s.untracked = (show_untracked_files == SHOW_ALL_UNTRACKED_FILES);
364 s.index_file = index_file;
365 s.fp = fp;
366 s.nowarn = nowarn;
368 wt_status_print(&s);
370 return s.commitable;
373 static int is_a_merge(const unsigned char *sha1)
375 struct commit *commit = lookup_commit(sha1);
376 if (!commit || parse_commit(commit))
377 die("could not parse HEAD commit");
378 return !!(commit->parents && commit->parents->next);
381 static const char sign_off_header[] = "Signed-off-by: ";
383 static void determine_author_info(void)
385 char *name, *email, *date;
387 name = getenv("GIT_AUTHOR_NAME");
388 email = getenv("GIT_AUTHOR_EMAIL");
389 date = getenv("GIT_AUTHOR_DATE");
391 if (use_message) {
392 const char *a, *lb, *rb, *eol;
394 a = strstr(use_message_buffer, "\nauthor ");
395 if (!a)
396 die("invalid commit: %s", use_message);
398 lb = strstr(a + 8, " <");
399 rb = strstr(a + 8, "> ");
400 eol = strchr(a + 8, '\n');
401 if (!lb || !rb || !eol)
402 die("invalid commit: %s", use_message);
404 name = xstrndup(a + 8, lb - (a + 8));
405 email = xstrndup(lb + 2, rb - (lb + 2));
406 date = xstrndup(rb + 2, eol - (rb + 2));
409 if (force_author) {
410 const char *lb = strstr(force_author, " <");
411 const char *rb = strchr(force_author, '>');
413 if (!lb || !rb)
414 die("malformed --author parameter");
415 name = xstrndup(force_author, lb - force_author);
416 email = xstrndup(lb + 2, rb - (lb + 2));
419 author_name = name;
420 author_email = email;
421 author_date = date;
424 static int prepare_to_commit(const char *index_file, const char *prefix)
426 struct stat statbuf;
427 int commitable, saved_color_setting;
428 struct strbuf sb = STRBUF_INIT;
429 char *buffer;
430 FILE *fp;
431 const char *hook_arg1 = NULL;
432 const char *hook_arg2 = NULL;
433 int ident_shown = 0;
435 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
436 return 0;
438 if (message.len) {
439 strbuf_addbuf(&sb, &message);
440 hook_arg1 = "message";
441 } else if (logfile && !strcmp(logfile, "-")) {
442 if (isatty(0))
443 fprintf(stderr, "(reading log message from standard input)\n");
444 if (strbuf_read(&sb, 0, 0) < 0)
445 die_errno("could not read log from standard input");
446 hook_arg1 = "message";
447 } else if (logfile) {
448 if (strbuf_read_file(&sb, logfile, 0) < 0)
449 die_errno("could not read log file '%s'",
450 logfile);
451 hook_arg1 = "message";
452 } else if (use_message) {
453 buffer = strstr(use_message_buffer, "\n\n");
454 if (!buffer || buffer[2] == '\0')
455 die("commit has empty message");
456 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
457 hook_arg1 = "commit";
458 hook_arg2 = use_message;
459 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
460 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
461 die_errno("could not read MERGE_MSG");
462 hook_arg1 = "merge";
463 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
464 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
465 die_errno("could not read SQUASH_MSG");
466 hook_arg1 = "squash";
467 } else if (template_file && !stat(template_file, &statbuf)) {
468 if (strbuf_read_file(&sb, template_file, 0) < 0)
469 die_errno("could not read '%s'", template_file);
470 hook_arg1 = "template";
474 * This final case does not modify the template message,
475 * it just sets the argument to the prepare-commit-msg hook.
477 else if (in_merge)
478 hook_arg1 = "merge";
480 fp = fopen(git_path(commit_editmsg), "w");
481 if (fp == NULL)
482 die_errno("could not open '%s'", git_path(commit_editmsg));
484 if (cleanup_mode != CLEANUP_NONE)
485 stripspace(&sb, 0);
487 if (signoff) {
488 struct strbuf sob = STRBUF_INIT;
489 int i;
491 strbuf_addstr(&sob, sign_off_header);
492 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
493 getenv("GIT_COMMITTER_EMAIL")));
494 strbuf_addch(&sob, '\n');
495 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
496 ; /* do nothing */
497 if (prefixcmp(sb.buf + i, sob.buf)) {
498 if (prefixcmp(sb.buf + i, sign_off_header))
499 strbuf_addch(&sb, '\n');
500 strbuf_addbuf(&sb, &sob);
502 strbuf_release(&sob);
505 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
506 die_errno("could not write commit template");
508 strbuf_release(&sb);
510 determine_author_info();
512 /* This checks if committer ident is explicitly given */
513 git_committer_info(0);
514 if (use_editor) {
515 char *author_ident;
516 const char *committer_ident;
518 if (in_merge)
519 fprintf(fp,
520 "#\n"
521 "# It looks like you may be committing a MERGE.\n"
522 "# If this is not correct, please remove the file\n"
523 "# %s\n"
524 "# and try again.\n"
525 "#\n",
526 git_path("MERGE_HEAD"));
528 fprintf(fp,
529 "\n"
530 "# Please enter the commit message for your changes.");
531 if (cleanup_mode == CLEANUP_ALL)
532 fprintf(fp,
533 " Lines starting\n"
534 "# with '#' will be ignored, and an empty"
535 " message aborts the commit.\n");
536 else /* CLEANUP_SPACE, that is. */
537 fprintf(fp,
538 " Lines starting\n"
539 "# with '#' will be kept; you may remove them"
540 " yourself if you want to.\n"
541 "# An empty message aborts the commit.\n");
542 if (only_include_assumed)
543 fprintf(fp, "# %s\n", only_include_assumed);
545 author_ident = xstrdup(fmt_name(author_name, author_email));
546 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
547 getenv("GIT_COMMITTER_EMAIL"));
548 if (strcmp(author_ident, committer_ident))
549 fprintf(fp,
550 "%s"
551 "# Author: %s\n",
552 ident_shown++ ? "" : "#\n",
553 author_ident);
554 free(author_ident);
556 if (!user_ident_explicitly_given)
557 fprintf(fp,
558 "%s"
559 "# Committer: %s\n",
560 ident_shown++ ? "" : "#\n",
561 committer_ident);
563 if (ident_shown)
564 fprintf(fp, "#\n");
566 saved_color_setting = wt_status_use_color;
567 wt_status_use_color = 0;
568 commitable = run_status(fp, index_file, prefix, 1);
569 wt_status_use_color = saved_color_setting;
570 } else {
571 unsigned char sha1[20];
572 const char *parent = "HEAD";
574 if (!active_nr && read_cache() < 0)
575 die("Cannot read index");
577 if (amend)
578 parent = "HEAD^1";
580 if (get_sha1(parent, sha1))
581 commitable = !!active_nr;
582 else
583 commitable = index_differs_from(parent, 0);
586 fclose(fp);
588 if (!commitable && !in_merge && !allow_empty &&
589 !(amend && is_a_merge(head_sha1))) {
590 run_status(stdout, index_file, prefix, 0);
591 return 0;
595 * Re-read the index as pre-commit hook could have updated it,
596 * and write it out as a tree. We must do this before we invoke
597 * the editor and after we invoke run_status above.
599 discard_cache();
600 read_cache_from(index_file);
601 if (!active_cache_tree)
602 active_cache_tree = cache_tree();
603 if (cache_tree_update(active_cache_tree,
604 active_cache, active_nr, 0, 0) < 0) {
605 error("Error building trees");
606 return 0;
609 if (run_hook(index_file, "prepare-commit-msg",
610 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
611 return 0;
613 if (use_editor) {
614 char index[PATH_MAX];
615 const char *env[2] = { index, NULL };
616 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
617 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
618 fprintf(stderr,
619 "Please supply the message using either -m or -F option.\n");
620 exit(1);
624 if (!no_verify &&
625 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
626 return 0;
629 return 1;
633 * Find out if the message in the strbuf contains only whitespace and
634 * Signed-off-by lines.
636 static int message_is_empty(struct strbuf *sb)
638 struct strbuf tmpl = STRBUF_INIT;
639 const char *nl;
640 int eol, i, start = 0;
642 if (cleanup_mode == CLEANUP_NONE && sb->len)
643 return 0;
645 /* See if the template is just a prefix of the message. */
646 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
647 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
648 if (start + tmpl.len <= sb->len &&
649 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
650 start += tmpl.len;
652 strbuf_release(&tmpl);
654 /* Check if the rest is just whitespace and Signed-of-by's. */
655 for (i = start; i < sb->len; i++) {
656 nl = memchr(sb->buf + i, '\n', sb->len - i);
657 if (nl)
658 eol = nl - sb->buf;
659 else
660 eol = sb->len;
662 if (strlen(sign_off_header) <= eol - i &&
663 !prefixcmp(sb->buf + i, sign_off_header)) {
664 i = eol;
665 continue;
667 while (i < eol)
668 if (!isspace(sb->buf[i++]))
669 return 0;
672 return 1;
675 static const char *find_author_by_nickname(const char *name)
677 struct rev_info revs;
678 struct commit *commit;
679 struct strbuf buf = STRBUF_INIT;
680 const char *av[20];
681 int ac = 0;
683 init_revisions(&revs, NULL);
684 strbuf_addf(&buf, "--author=%s", name);
685 av[++ac] = "--all";
686 av[++ac] = "-i";
687 av[++ac] = buf.buf;
688 av[++ac] = NULL;
689 setup_revisions(ac, av, &revs, NULL);
690 prepare_revision_walk(&revs);
691 commit = get_revision(&revs);
692 if (commit) {
693 strbuf_release(&buf);
694 format_commit_message(commit, "%an <%ae>", &buf, DATE_NORMAL);
695 return strbuf_detach(&buf, NULL);
697 die("No existing author found with '%s'", name);
700 static int parse_and_validate_options(int argc, const char *argv[],
701 const char * const usage[],
702 const char *prefix)
704 int f = 0;
706 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
709 if (force_author && !strchr(force_author, '>'))
710 force_author = find_author_by_nickname(force_author);
712 if (logfile || message.len || use_message)
713 use_editor = 0;
714 if (edit_flag)
715 use_editor = 1;
716 if (!use_editor)
717 setenv("GIT_EDITOR", ":", 1);
719 if (get_sha1("HEAD", head_sha1))
720 initial_commit = 1;
722 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
723 in_merge = 1;
725 /* Sanity check options */
726 if (amend && initial_commit)
727 die("You have nothing to amend.");
728 if (amend && in_merge)
729 die("You are in the middle of a merge -- cannot amend.");
731 if (use_message)
732 f++;
733 if (edit_message)
734 f++;
735 if (logfile)
736 f++;
737 if (f > 1)
738 die("Only one of -c/-C/-F can be used.");
739 if (message.len && f > 0)
740 die("Option -m cannot be combined with -c/-C/-F.");
741 if (edit_message)
742 use_message = edit_message;
743 if (amend && !use_message)
744 use_message = "HEAD";
745 if (use_message) {
746 unsigned char sha1[20];
747 static char utf8[] = "UTF-8";
748 const char *out_enc;
749 char *enc, *end;
750 struct commit *commit;
752 if (get_sha1(use_message, sha1))
753 die("could not lookup commit %s", use_message);
754 commit = lookup_commit_reference(sha1);
755 if (!commit || parse_commit(commit))
756 die("could not parse commit %s", use_message);
758 enc = strstr(commit->buffer, "\nencoding");
759 if (enc) {
760 end = strchr(enc + 10, '\n');
761 enc = xstrndup(enc + 10, end - (enc + 10));
762 } else {
763 enc = utf8;
765 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
767 if (strcmp(out_enc, enc))
768 use_message_buffer =
769 reencode_string(commit->buffer, out_enc, enc);
772 * If we failed to reencode the buffer, just copy it
773 * byte for byte so the user can try to fix it up.
774 * This also handles the case where input and output
775 * encodings are identical.
777 if (use_message_buffer == NULL)
778 use_message_buffer = xstrdup(commit->buffer);
779 if (enc != utf8)
780 free(enc);
783 if (!!also + !!only + !!all + !!interactive > 1)
784 die("Only one of --include/--only/--all/--interactive can be used.");
785 if (argc == 0 && (also || (only && !amend)))
786 die("No paths with --include/--only does not make sense.");
787 if (argc == 0 && only && amend)
788 only_include_assumed = "Clever... amending the last one with dirty index.";
789 if (argc > 0 && !also && !only)
790 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
791 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
792 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
793 else if (!strcmp(cleanup_arg, "verbatim"))
794 cleanup_mode = CLEANUP_NONE;
795 else if (!strcmp(cleanup_arg, "whitespace"))
796 cleanup_mode = CLEANUP_SPACE;
797 else if (!strcmp(cleanup_arg, "strip"))
798 cleanup_mode = CLEANUP_ALL;
799 else
800 die("Invalid cleanup mode %s", cleanup_arg);
802 if (!untracked_files_arg)
803 ; /* default already initialized */
804 else if (!strcmp(untracked_files_arg, "no"))
805 show_untracked_files = SHOW_NO_UNTRACKED_FILES;
806 else if (!strcmp(untracked_files_arg, "normal"))
807 show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
808 else if (!strcmp(untracked_files_arg, "all"))
809 show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
810 else
811 die("Invalid untracked files mode '%s'", untracked_files_arg);
813 if (all && argc > 0)
814 die("Paths with -a does not make sense.");
815 else if (interactive && argc > 0)
816 die("Paths with --interactive does not make sense.");
818 return argc;
821 int cmd_status(int argc, const char **argv, const char *prefix)
823 const char *index_file;
824 int commitable;
826 git_config(git_status_config, NULL);
828 if (wt_status_use_color == -1)
829 wt_status_use_color = git_use_color_default;
831 if (diff_use_color_default == -1)
832 diff_use_color_default = git_use_color_default;
834 argc = parse_and_validate_options(argc, argv, builtin_status_usage, prefix);
836 index_file = prepare_index(argc, argv, prefix);
838 commitable = run_status(stdout, index_file, prefix, 0);
840 rollback_index_files();
842 return commitable ? 0 : 1;
845 static void print_summary(const char *prefix, const unsigned char *sha1)
847 struct rev_info rev;
848 struct commit *commit;
849 static const char *format = "format:%h] %s";
850 unsigned char junk_sha1[20];
851 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
853 commit = lookup_commit(sha1);
854 if (!commit)
855 die("couldn't look up newly created commit");
856 if (!commit || parse_commit(commit))
857 die("could not parse newly created commit");
859 init_revisions(&rev, prefix);
860 setup_revisions(0, NULL, &rev, NULL);
862 rev.abbrev = 0;
863 rev.diff = 1;
864 rev.diffopt.output_format =
865 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
867 rev.verbose_header = 1;
868 rev.show_root_diff = 1;
869 get_commit_format(format, &rev);
870 rev.always_show_header = 0;
871 rev.diffopt.detect_rename = 1;
872 rev.diffopt.rename_limit = 100;
873 rev.diffopt.break_opt = 0;
874 diff_setup_done(&rev.diffopt);
876 printf("[%s%s ",
877 !prefixcmp(head, "refs/heads/") ?
878 head + 11 :
879 !strcmp(head, "HEAD") ?
880 "detached HEAD" :
881 head,
882 initial_commit ? " (root-commit)" : "");
884 if (!log_tree_commit(&rev, commit)) {
885 struct strbuf buf = STRBUF_INIT;
886 format_commit_message(commit, format + 7, &buf, DATE_NORMAL);
887 printf("%s\n", buf.buf);
888 strbuf_release(&buf);
892 static int git_commit_config(const char *k, const char *v, void *cb)
894 if (!strcmp(k, "commit.template"))
895 return git_config_string(&template_file, k, v);
897 return git_status_config(k, v, cb);
900 int cmd_commit(int argc, const char **argv, const char *prefix)
902 struct strbuf sb = STRBUF_INIT;
903 const char *index_file, *reflog_msg;
904 char *nl, *p;
905 unsigned char commit_sha1[20];
906 struct ref_lock *ref_lock;
907 struct commit_list *parents = NULL, **pptr = &parents;
908 struct stat statbuf;
909 int allow_fast_forward = 1;
911 git_config(git_commit_config, NULL);
913 if (wt_status_use_color == -1)
914 wt_status_use_color = git_use_color_default;
916 argc = parse_and_validate_options(argc, argv, builtin_commit_usage, prefix);
918 index_file = prepare_index(argc, argv, prefix);
920 /* Set up everything for writing the commit object. This includes
921 running hooks, writing the trees, and interacting with the user. */
922 if (!prepare_to_commit(index_file, prefix)) {
923 rollback_index_files();
924 return 1;
927 /* Determine parents */
928 if (initial_commit) {
929 reflog_msg = "commit (initial)";
930 } else if (amend) {
931 struct commit_list *c;
932 struct commit *commit;
934 reflog_msg = "commit (amend)";
935 commit = lookup_commit(head_sha1);
936 if (!commit || parse_commit(commit))
937 die("could not parse HEAD commit");
939 for (c = commit->parents; c; c = c->next)
940 pptr = &commit_list_insert(c->item, pptr)->next;
941 } else if (in_merge) {
942 struct strbuf m = STRBUF_INIT;
943 FILE *fp;
945 reflog_msg = "commit (merge)";
946 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
947 fp = fopen(git_path("MERGE_HEAD"), "r");
948 if (fp == NULL)
949 die_errno("could not open '%s' for reading",
950 git_path("MERGE_HEAD"));
951 while (strbuf_getline(&m, fp, '\n') != EOF) {
952 unsigned char sha1[20];
953 if (get_sha1_hex(m.buf, sha1) < 0)
954 die("Corrupt MERGE_HEAD file (%s)", m.buf);
955 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
957 fclose(fp);
958 strbuf_release(&m);
959 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
960 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
961 die_errno("could not read MERGE_MODE");
962 if (!strcmp(sb.buf, "no-ff"))
963 allow_fast_forward = 0;
965 if (allow_fast_forward)
966 parents = reduce_heads(parents);
967 } else {
968 reflog_msg = "commit";
969 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
972 /* Finally, get the commit message */
973 strbuf_reset(&sb);
974 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
975 int saved_errno = errno;
976 rollback_index_files();
977 die("could not read commit message: %s", strerror(saved_errno));
980 /* Truncate the message just before the diff, if any. */
981 if (verbose) {
982 p = strstr(sb.buf, "\ndiff --git ");
983 if (p != NULL)
984 strbuf_setlen(&sb, p - sb.buf + 1);
987 if (cleanup_mode != CLEANUP_NONE)
988 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
989 if (message_is_empty(&sb)) {
990 rollback_index_files();
991 fprintf(stderr, "Aborting commit due to empty commit message.\n");
992 exit(1);
995 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
996 fmt_ident(author_name, author_email, author_date,
997 IDENT_ERROR_ON_NO_NAME))) {
998 rollback_index_files();
999 die("failed to write commit object");
1002 ref_lock = lock_any_ref_for_update("HEAD",
1003 initial_commit ? NULL : head_sha1,
1006 nl = strchr(sb.buf, '\n');
1007 if (nl)
1008 strbuf_setlen(&sb, nl + 1 - sb.buf);
1009 else
1010 strbuf_addch(&sb, '\n');
1011 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1012 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1014 if (!ref_lock) {
1015 rollback_index_files();
1016 die("cannot lock HEAD ref");
1018 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1019 rollback_index_files();
1020 die("cannot update HEAD ref");
1023 unlink(git_path("MERGE_HEAD"));
1024 unlink(git_path("MERGE_MSG"));
1025 unlink(git_path("MERGE_MODE"));
1026 unlink(git_path("SQUASH_MSG"));
1028 if (commit_index_files())
1029 die ("Repository has been updated, but unable to write\n"
1030 "new_index file. Check that disk is not full or quota is\n"
1031 "not exceeded, and then \"git reset HEAD\" to recover.");
1033 rerere();
1034 run_hook(get_index_file(), "post-commit", NULL);
1035 if (!quiet)
1036 print_summary(prefix, commit_sha1);
1038 return 0;