factorize revindex code out of builtin-pack-objects.c
[git/mingw.git] / builtin-commit.c
blobf49c22e64255225e492614bb628c1d1776521424
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 "path-list.h"
25 #include "unpack-trees.h"
27 static const char * const builtin_commit_usage[] = {
28 "git-commit [options] [--] <filepattern>...",
29 NULL
32 static const char * const builtin_status_usage[] = {
33 "git-status [options] [--] <filepattern>...",
34 NULL
37 static unsigned char head_sha1[20], merge_head_sha1[20];
38 static char *use_message_buffer;
39 static const char commit_editmsg[] = "COMMIT_EDITMSG";
40 static struct lock_file index_lock; /* real index */
41 static struct lock_file false_lock; /* used only for partial commits */
42 static enum {
43 COMMIT_AS_IS = 1,
44 COMMIT_NORMAL,
45 COMMIT_PARTIAL,
46 } commit_style;
48 static char *logfile, *force_author, *template_file;
49 static char *edit_message, *use_message;
50 static int all, edit_flag, also, interactive, only, amend, signoff;
51 static int quiet, verbose, untracked_files, no_verify, allow_empty;
53 * The default commit message cleanup mode will remove the lines
54 * beginning with # (shell comments) and leading and trailing
55 * whitespaces (empty lines or containing only whitespaces)
56 * if editor is used, and only the whitespaces if the message
57 * is specified explicitly.
59 static enum {
60 CLEANUP_SPACE,
61 CLEANUP_NONE,
62 CLEANUP_ALL,
63 } cleanup_mode;
64 static char *cleanup_arg;
66 static int use_editor = 1, initial_commit, in_merge;
67 const char *only_include_assumed;
68 struct strbuf message;
70 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
72 struct strbuf *buf = opt->value;
73 if (unset)
74 strbuf_setlen(buf, 0);
75 else {
76 strbuf_addstr(buf, arg);
77 strbuf_addch(buf, '\n');
78 strbuf_addch(buf, '\n');
80 return 0;
83 static struct option builtin_commit_options[] = {
84 OPT__QUIET(&quiet),
85 OPT__VERBOSE(&verbose),
86 OPT_GROUP("Commit message options"),
88 OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
89 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
90 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
91 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
92 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
93 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
94 OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
95 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
97 OPT_GROUP("Commit contents options"),
98 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
99 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
100 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
101 OPT_BOOLEAN('o', "only", &only, ""),
102 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
103 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
104 OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
105 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
106 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
108 OPT_END()
111 static void rollback_index_files(void)
113 switch (commit_style) {
114 case COMMIT_AS_IS:
115 break; /* nothing to do */
116 case COMMIT_NORMAL:
117 rollback_lock_file(&index_lock);
118 break;
119 case COMMIT_PARTIAL:
120 rollback_lock_file(&index_lock);
121 rollback_lock_file(&false_lock);
122 break;
126 static int commit_index_files(void)
128 int err = 0;
130 switch (commit_style) {
131 case COMMIT_AS_IS:
132 break; /* nothing to do */
133 case COMMIT_NORMAL:
134 err = commit_lock_file(&index_lock);
135 break;
136 case COMMIT_PARTIAL:
137 err = commit_lock_file(&index_lock);
138 rollback_lock_file(&false_lock);
139 break;
142 return err;
146 * Take a union of paths in the index and the named tree (typically, "HEAD"),
147 * and return the paths that match the given pattern in list.
149 static int list_paths(struct path_list *list, const char *with_tree,
150 const char *prefix, const char **pattern)
152 int i;
153 char *m;
155 for (i = 0; pattern[i]; i++)
157 m = xcalloc(1, i);
159 if (with_tree)
160 overlay_tree_on_cache(with_tree, prefix);
162 for (i = 0; i < active_nr; i++) {
163 struct cache_entry *ce = active_cache[i];
164 if (ce->ce_flags & CE_UPDATE)
165 continue;
166 if (!pathspec_match(pattern, m, ce->name, 0))
167 continue;
168 path_list_insert(ce->name, list);
171 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
174 static void add_remove_files(struct path_list *list)
176 int i;
177 for (i = 0; i < list->nr; i++) {
178 struct path_list_item *p = &(list->items[i]);
179 if (file_exists(p->path))
180 add_file_to_cache(p->path, 0);
181 else
182 remove_file_from_cache(p->path);
186 static void create_base_index(void)
188 struct tree *tree;
189 struct unpack_trees_options opts;
190 struct tree_desc t;
192 if (initial_commit) {
193 discard_cache();
194 return;
197 memset(&opts, 0, sizeof(opts));
198 opts.head_idx = 1;
199 opts.index_only = 1;
200 opts.merge = 1;
202 opts.fn = oneway_merge;
203 tree = parse_tree_indirect(head_sha1);
204 if (!tree)
205 die("failed to unpack HEAD tree object");
206 parse_tree(tree);
207 init_tree_desc(&t, tree->buffer, tree->size);
208 if (unpack_trees(1, &t, &opts))
209 exit(128); /* We've already reported the error, finish dying */
212 static char *prepare_index(int argc, const char **argv, const char *prefix)
214 int fd;
215 struct path_list partial;
216 const char **pathspec = NULL;
218 if (interactive) {
219 interactive_add(argc, argv, prefix);
220 commit_style = COMMIT_AS_IS;
221 return get_index_file();
224 if (read_cache() < 0)
225 die("index file corrupt");
227 if (*argv)
228 pathspec = get_pathspec(prefix, argv);
231 * Non partial, non as-is commit.
233 * (1) get the real index;
234 * (2) update the_index as necessary;
235 * (3) write the_index out to the real index (still locked);
236 * (4) return the name of the locked index file.
238 * The caller should run hooks on the locked real index, and
239 * (A) if all goes well, commit the real index;
240 * (B) on failure, rollback the real index.
242 if (all || (also && pathspec && *pathspec)) {
243 int fd = hold_locked_index(&index_lock, 1);
244 add_files_to_cache(0, also ? prefix : NULL, pathspec);
245 refresh_cache(REFRESH_QUIET);
246 if (write_cache(fd, active_cache, active_nr) ||
247 close_lock_file(&index_lock))
248 die("unable to write new_index file");
249 commit_style = COMMIT_NORMAL;
250 return index_lock.filename;
254 * As-is commit.
256 * (1) return the name of the real index file.
258 * The caller should run hooks on the real index, and run
259 * hooks on the real index, and create commit from the_index.
260 * We still need to refresh the index here.
262 if (!pathspec || !*pathspec) {
263 fd = hold_locked_index(&index_lock, 1);
264 refresh_cache(REFRESH_QUIET);
265 if (write_cache(fd, active_cache, active_nr) ||
266 commit_locked_index(&index_lock))
267 die("unable to write new_index file");
268 commit_style = COMMIT_AS_IS;
269 return get_index_file();
273 * A partial commit.
275 * (0) find the set of affected paths;
276 * (1) get lock on the real index file;
277 * (2) update the_index with the given paths;
278 * (3) write the_index out to the real index (still locked);
279 * (4) get lock on the false index file;
280 * (5) reset the_index from HEAD;
281 * (6) update the_index the same way as (2);
282 * (7) write the_index out to the false index file;
283 * (8) return the name of the false index file (still locked);
285 * The caller should run hooks on the locked false index, and
286 * create commit from it. Then
287 * (A) if all goes well, commit the real index;
288 * (B) on failure, rollback the real index;
289 * In either case, rollback the false index.
291 commit_style = COMMIT_PARTIAL;
293 if (file_exists(git_path("MERGE_HEAD")))
294 die("cannot do a partial commit during a merge.");
296 memset(&partial, 0, sizeof(partial));
297 partial.strdup_paths = 1;
298 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
299 exit(1);
301 discard_cache();
302 if (read_cache() < 0)
303 die("cannot read the index");
305 fd = hold_locked_index(&index_lock, 1);
306 add_remove_files(&partial);
307 refresh_cache(REFRESH_QUIET);
308 if (write_cache(fd, active_cache, active_nr) ||
309 close_lock_file(&index_lock))
310 die("unable to write new_index file");
312 fd = hold_lock_file_for_update(&false_lock,
313 git_path("next-index-%d", getpid()), 1);
315 create_base_index();
316 add_remove_files(&partial);
317 refresh_cache(REFRESH_QUIET);
319 if (write_cache(fd, active_cache, active_nr) ||
320 close_lock_file(&false_lock))
321 die("unable to write temporary index file");
323 discard_cache();
324 read_cache_from(false_lock.filename);
326 return false_lock.filename;
329 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn)
331 struct wt_status s;
333 wt_status_prepare(&s);
334 if (wt_status_relative_paths)
335 s.prefix = prefix;
337 if (amend) {
338 s.amend = 1;
339 s.reference = "HEAD^1";
341 s.verbose = verbose;
342 s.untracked = untracked_files;
343 s.index_file = index_file;
344 s.fp = fp;
345 s.nowarn = nowarn;
347 wt_status_print(&s);
349 return s.commitable;
352 static int run_hook(const char *index_file, const char *name, ...)
354 struct child_process hook;
355 const char *argv[10], *env[2];
356 char index[PATH_MAX];
357 va_list args;
358 int i;
360 va_start(args, name);
361 argv[0] = git_path("hooks/%s", name);
362 i = 0;
363 do {
364 if (++i >= ARRAY_SIZE(argv))
365 die ("run_hook(): too many arguments");
366 argv[i] = va_arg(args, const char *);
367 } while (argv[i]);
368 va_end(args);
370 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
371 env[0] = index;
372 env[1] = NULL;
374 if (access(argv[0], X_OK) < 0)
375 return 0;
377 memset(&hook, 0, sizeof(hook));
378 hook.argv = argv;
379 hook.no_stdin = 1;
380 hook.stdout_to_stderr = 1;
381 hook.env = env;
383 return run_command(&hook);
386 static int is_a_merge(const unsigned char *sha1)
388 struct commit *commit = lookup_commit(sha1);
389 if (!commit || parse_commit(commit))
390 die("could not parse HEAD commit");
391 return !!(commit->parents && commit->parents->next);
394 static const char sign_off_header[] = "Signed-off-by: ";
396 static int prepare_to_commit(const char *index_file, const char *prefix)
398 struct stat statbuf;
399 int commitable, saved_color_setting;
400 struct strbuf sb;
401 char *buffer;
402 FILE *fp;
403 const char *hook_arg1 = NULL;
404 const char *hook_arg2 = NULL;
406 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
407 return 0;
409 strbuf_init(&sb, 0);
410 if (message.len) {
411 strbuf_addbuf(&sb, &message);
412 hook_arg1 = "message";
413 } else if (logfile && !strcmp(logfile, "-")) {
414 if (isatty(0))
415 fprintf(stderr, "(reading log message from standard input)\n");
416 if (strbuf_read(&sb, 0, 0) < 0)
417 die("could not read log from standard input");
418 hook_arg1 = "message";
419 } else if (logfile) {
420 if (strbuf_read_file(&sb, logfile, 0) < 0)
421 die("could not read log file '%s': %s",
422 logfile, strerror(errno));
423 hook_arg1 = "message";
424 } else if (use_message) {
425 buffer = strstr(use_message_buffer, "\n\n");
426 if (!buffer || buffer[2] == '\0')
427 die("commit has empty message");
428 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
429 hook_arg1 = "commit";
430 hook_arg2 = use_message;
431 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
432 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
433 die("could not read MERGE_MSG: %s", strerror(errno));
434 hook_arg1 = "merge";
435 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
436 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
437 die("could not read SQUASH_MSG: %s", strerror(errno));
438 hook_arg1 = "squash";
439 } else if (template_file && !stat(template_file, &statbuf)) {
440 if (strbuf_read_file(&sb, template_file, 0) < 0)
441 die("could not read %s: %s",
442 template_file, strerror(errno));
443 hook_arg1 = "template";
447 * This final case does not modify the template message,
448 * it just sets the argument to the prepare-commit-msg hook.
450 else if (in_merge)
451 hook_arg1 = "merge";
453 fp = fopen(git_path(commit_editmsg), "w");
454 if (fp == NULL)
455 die("could not open %s", git_path(commit_editmsg));
457 if (cleanup_mode != CLEANUP_NONE)
458 stripspace(&sb, 0);
460 if (signoff) {
461 struct strbuf sob;
462 int i;
464 strbuf_init(&sob, 0);
465 strbuf_addstr(&sob, sign_off_header);
466 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
467 getenv("GIT_COMMITTER_EMAIL")));
468 strbuf_addch(&sob, '\n');
469 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
470 ; /* do nothing */
471 if (prefixcmp(sb.buf + i, sob.buf)) {
472 if (prefixcmp(sb.buf + i, sign_off_header))
473 strbuf_addch(&sb, '\n');
474 strbuf_addbuf(&sb, &sob);
476 strbuf_release(&sob);
479 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
480 die("could not write commit template: %s", strerror(errno));
482 strbuf_release(&sb);
484 if (use_editor) {
485 if (in_merge)
486 fprintf(fp,
487 "#\n"
488 "# It looks like you may be committing a MERGE.\n"
489 "# If this is not correct, please remove the file\n"
490 "# %s\n"
491 "# and try again.\n"
492 "#\n",
493 git_path("MERGE_HEAD"));
495 fprintf(fp,
496 "\n"
497 "# Please enter the commit message for your changes.\n"
498 "# (Comment lines starting with '#' will ");
499 if (cleanup_mode == CLEANUP_ALL)
500 fprintf(fp, "not be included)\n");
501 else /* CLEANUP_SPACE, that is. */
502 fprintf(fp, "be kept.\n"
503 "# You can remove them yourself if you want to)\n");
504 if (only_include_assumed)
505 fprintf(fp, "# %s\n", only_include_assumed);
507 saved_color_setting = wt_status_use_color;
508 wt_status_use_color = 0;
509 commitable = run_status(fp, index_file, prefix, 1);
510 wt_status_use_color = saved_color_setting;
511 } else {
512 struct rev_info rev;
513 unsigned char sha1[20];
514 const char *parent = "HEAD";
516 if (!active_nr && read_cache() < 0)
517 die("Cannot read index");
519 if (amend)
520 parent = "HEAD^1";
522 if (get_sha1(parent, sha1))
523 commitable = !!active_nr;
524 else {
525 init_revisions(&rev, "");
526 rev.abbrev = 0;
527 setup_revisions(0, NULL, &rev, parent);
528 DIFF_OPT_SET(&rev.diffopt, QUIET);
529 DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
530 run_diff_index(&rev, 1 /* cached */);
532 commitable = !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
536 fclose(fp);
538 if (!commitable && !in_merge && !allow_empty &&
539 !(amend && is_a_merge(head_sha1))) {
540 run_status(stdout, index_file, prefix, 0);
541 unlink(commit_editmsg);
542 return 0;
546 * Re-read the index as pre-commit hook could have updated it,
547 * and write it out as a tree. We must do this before we invoke
548 * the editor and after we invoke run_status above.
550 discard_cache();
551 read_cache_from(index_file);
552 if (!active_cache_tree)
553 active_cache_tree = cache_tree();
554 if (cache_tree_update(active_cache_tree,
555 active_cache, active_nr, 0, 0) < 0) {
556 error("Error building trees");
557 return 0;
560 if (run_hook(index_file, "prepare-commit-msg",
561 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
562 return 0;
564 if (use_editor) {
565 char index[PATH_MAX];
566 const char *env[2] = { index, NULL };
567 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
568 launch_editor(git_path(commit_editmsg), NULL, env);
571 if (!no_verify &&
572 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
573 return 0;
576 return 1;
580 * Find out if the message starting at position 'start' in the strbuf
581 * contains only whitespace and Signed-off-by lines.
583 static int message_is_empty(struct strbuf *sb, int start)
585 struct strbuf tmpl;
586 const char *nl;
587 int eol, i;
589 if (cleanup_mode == CLEANUP_NONE && sb->len)
590 return 0;
592 /* See if the template is just a prefix of the message. */
593 strbuf_init(&tmpl, 0);
594 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
595 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
596 if (start + tmpl.len <= sb->len &&
597 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
598 start += tmpl.len;
600 strbuf_release(&tmpl);
602 /* Check if the rest is just whitespace and Signed-of-by's. */
603 for (i = start; i < sb->len; i++) {
604 nl = memchr(sb->buf + i, '\n', sb->len - i);
605 if (nl)
606 eol = nl - sb->buf;
607 else
608 eol = sb->len;
610 if (strlen(sign_off_header) <= eol - i &&
611 !prefixcmp(sb->buf + i, sign_off_header)) {
612 i = eol;
613 continue;
615 while (i < eol)
616 if (!isspace(sb->buf[i++]))
617 return 0;
620 return 1;
623 static void determine_author_info(struct strbuf *sb)
625 char *name, *email, *date;
627 name = getenv("GIT_AUTHOR_NAME");
628 email = getenv("GIT_AUTHOR_EMAIL");
629 date = getenv("GIT_AUTHOR_DATE");
631 if (use_message) {
632 const char *a, *lb, *rb, *eol;
634 a = strstr(use_message_buffer, "\nauthor ");
635 if (!a)
636 die("invalid commit: %s", use_message);
638 lb = strstr(a + 8, " <");
639 rb = strstr(a + 8, "> ");
640 eol = strchr(a + 8, '\n');
641 if (!lb || !rb || !eol)
642 die("invalid commit: %s", use_message);
644 name = xstrndup(a + 8, lb - (a + 8));
645 email = xstrndup(lb + 2, rb - (lb + 2));
646 date = xstrndup(rb + 2, eol - (rb + 2));
649 if (force_author) {
650 const char *lb = strstr(force_author, " <");
651 const char *rb = strchr(force_author, '>');
653 if (!lb || !rb)
654 die("malformed --author parameter");
655 name = xstrndup(force_author, lb - force_author);
656 email = xstrndup(lb + 2, rb - (lb + 2));
659 strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, IDENT_ERROR_ON_NO_NAME));
662 static int parse_and_validate_options(int argc, const char *argv[],
663 const char * const usage[])
665 int f = 0;
667 argc = parse_options(argc, argv, builtin_commit_options, usage, 0);
669 if (logfile || message.len || use_message)
670 use_editor = 0;
671 if (edit_flag)
672 use_editor = 1;
673 if (!use_editor)
674 setenv("GIT_EDITOR", ":", 1);
676 if (get_sha1("HEAD", head_sha1))
677 initial_commit = 1;
679 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
680 in_merge = 1;
682 /* Sanity check options */
683 if (amend && initial_commit)
684 die("You have nothing to amend.");
685 if (amend && in_merge)
686 die("You are in the middle of a merge -- cannot amend.");
688 if (use_message)
689 f++;
690 if (edit_message)
691 f++;
692 if (logfile)
693 f++;
694 if (f > 1)
695 die("Only one of -c/-C/-F can be used.");
696 if (message.len && f > 0)
697 die("Option -m cannot be combined with -c/-C/-F.");
698 if (edit_message)
699 use_message = edit_message;
700 if (amend && !use_message)
701 use_message = "HEAD";
702 if (use_message) {
703 unsigned char sha1[20];
704 static char utf8[] = "UTF-8";
705 const char *out_enc;
706 char *enc, *end;
707 struct commit *commit;
709 if (get_sha1(use_message, sha1))
710 die("could not lookup commit %s", use_message);
711 commit = lookup_commit_reference(sha1);
712 if (!commit || parse_commit(commit))
713 die("could not parse commit %s", use_message);
715 enc = strstr(commit->buffer, "\nencoding");
716 if (enc) {
717 end = strchr(enc + 10, '\n');
718 enc = xstrndup(enc + 10, end - (enc + 10));
719 } else {
720 enc = utf8;
722 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
724 if (strcmp(out_enc, enc))
725 use_message_buffer =
726 reencode_string(commit->buffer, out_enc, enc);
729 * If we failed to reencode the buffer, just copy it
730 * byte for byte so the user can try to fix it up.
731 * This also handles the case where input and output
732 * encodings are identical.
734 if (use_message_buffer == NULL)
735 use_message_buffer = xstrdup(commit->buffer);
736 if (enc != utf8)
737 free(enc);
740 if (!!also + !!only + !!all + !!interactive > 1)
741 die("Only one of --include/--only/--all/--interactive can be used.");
742 if (argc == 0 && (also || (only && !amend)))
743 die("No paths with --include/--only does not make sense.");
744 if (argc == 0 && only && amend)
745 only_include_assumed = "Clever... amending the last one with dirty index.";
746 if (argc > 0 && !also && !only) {
747 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
748 also = 0;
750 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
751 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
752 else if (!strcmp(cleanup_arg, "verbatim"))
753 cleanup_mode = CLEANUP_NONE;
754 else if (!strcmp(cleanup_arg, "whitespace"))
755 cleanup_mode = CLEANUP_SPACE;
756 else if (!strcmp(cleanup_arg, "strip"))
757 cleanup_mode = CLEANUP_ALL;
758 else
759 die("Invalid cleanup mode %s", cleanup_arg);
761 if (all && argc > 0)
762 die("Paths with -a does not make sense.");
763 else if (interactive && argc > 0)
764 die("Paths with --interactive does not make sense.");
766 return argc;
769 int cmd_status(int argc, const char **argv, const char *prefix)
771 const char *index_file;
772 int commitable;
774 git_config(git_status_config);
776 if (wt_status_use_color == -1)
777 wt_status_use_color = git_use_color_default;
779 argc = parse_and_validate_options(argc, argv, builtin_status_usage);
781 index_file = prepare_index(argc, argv, prefix);
783 commitable = run_status(stdout, index_file, prefix, 0);
785 rollback_index_files();
787 return commitable ? 0 : 1;
790 static void print_summary(const char *prefix, const unsigned char *sha1)
792 struct rev_info rev;
793 struct commit *commit;
795 commit = lookup_commit(sha1);
796 if (!commit)
797 die("couldn't look up newly created commit");
798 if (!commit || parse_commit(commit))
799 die("could not parse newly created commit");
801 init_revisions(&rev, prefix);
802 setup_revisions(0, NULL, &rev, NULL);
804 rev.abbrev = 0;
805 rev.diff = 1;
806 rev.diffopt.output_format =
807 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
809 rev.verbose_header = 1;
810 rev.show_root_diff = 1;
811 rev.commit_format = get_commit_format("format:%h: %s");
812 rev.always_show_header = 0;
813 rev.diffopt.detect_rename = 1;
814 rev.diffopt.rename_limit = 100;
815 rev.diffopt.break_opt = 0;
816 diff_setup_done(&rev.diffopt);
818 printf("Created %scommit ", initial_commit ? "initial " : "");
820 if (!log_tree_commit(&rev, commit)) {
821 struct strbuf buf = STRBUF_INIT;
822 format_commit_message(commit, "%h: %s", &buf);
823 printf("%s\n", buf.buf);
824 strbuf_release(&buf);
828 int git_commit_config(const char *k, const char *v)
830 if (!strcmp(k, "commit.template")) {
831 if (!v)
832 return config_error_nonbool(v);
833 template_file = xstrdup(v);
834 return 0;
837 return git_status_config(k, v);
840 static const char commit_utf8_warn[] =
841 "Warning: commit message does not conform to UTF-8.\n"
842 "You may want to amend it after fixing the message, or set the config\n"
843 "variable i18n.commitencoding to the encoding your project uses.\n";
845 static void add_parent(struct strbuf *sb, const unsigned char *sha1)
847 struct object *obj = parse_object(sha1);
848 const char *parent = sha1_to_hex(sha1);
849 if (!obj)
850 die("Unable to find commit parent %s", parent);
851 if (obj->type != OBJ_COMMIT)
852 die("Parent %s isn't a proper commit", parent);
853 strbuf_addf(sb, "parent %s\n", parent);
856 int cmd_commit(int argc, const char **argv, const char *prefix)
858 int header_len;
859 struct strbuf sb;
860 const char *index_file, *reflog_msg;
861 char *nl, *p;
862 unsigned char commit_sha1[20];
863 struct ref_lock *ref_lock;
865 git_config(git_commit_config);
867 argc = parse_and_validate_options(argc, argv, builtin_commit_usage);
869 index_file = prepare_index(argc, argv, prefix);
871 /* Set up everything for writing the commit object. This includes
872 running hooks, writing the trees, and interacting with the user. */
873 if (!prepare_to_commit(index_file, prefix)) {
874 rollback_index_files();
875 return 1;
879 * The commit object
881 strbuf_init(&sb, 0);
882 strbuf_addf(&sb, "tree %s\n",
883 sha1_to_hex(active_cache_tree->sha1));
885 /* Determine parents */
886 if (initial_commit) {
887 reflog_msg = "commit (initial)";
888 } else if (amend) {
889 struct commit_list *c;
890 struct commit *commit;
892 reflog_msg = "commit (amend)";
893 commit = lookup_commit(head_sha1);
894 if (!commit || parse_commit(commit))
895 die("could not parse HEAD commit");
897 for (c = commit->parents; c; c = c->next)
898 add_parent(&sb, c->item->object.sha1);
899 } else if (in_merge) {
900 struct strbuf m;
901 FILE *fp;
903 reflog_msg = "commit (merge)";
904 add_parent(&sb, head_sha1);
905 strbuf_init(&m, 0);
906 fp = fopen(git_path("MERGE_HEAD"), "r");
907 if (fp == NULL)
908 die("could not open %s for reading: %s",
909 git_path("MERGE_HEAD"), strerror(errno));
910 while (strbuf_getline(&m, fp, '\n') != EOF) {
911 unsigned char sha1[20];
912 if (get_sha1_hex(m.buf, sha1) < 0)
913 die("Corrupt MERGE_HEAD file (%s)", m.buf);
914 add_parent(&sb, sha1);
916 fclose(fp);
917 strbuf_release(&m);
918 } else {
919 reflog_msg = "commit";
920 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
923 determine_author_info(&sb);
924 strbuf_addf(&sb, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME));
925 if (!is_encoding_utf8(git_commit_encoding))
926 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
927 strbuf_addch(&sb, '\n');
929 /* Finally, get the commit message */
930 header_len = sb.len;
931 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
932 rollback_index_files();
933 die("could not read commit message");
936 /* Truncate the message just before the diff, if any. */
937 p = strstr(sb.buf, "\ndiff --git a/");
938 if (p != NULL)
939 strbuf_setlen(&sb, p - sb.buf + 1);
941 if (cleanup_mode != CLEANUP_NONE)
942 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
943 if (sb.len < header_len || message_is_empty(&sb, header_len)) {
944 rollback_index_files();
945 die("no commit message? aborting commit.");
947 strbuf_addch(&sb, '\0');
948 if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
949 fprintf(stderr, commit_utf8_warn);
951 if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) {
952 rollback_index_files();
953 die("failed to write commit object");
956 ref_lock = lock_any_ref_for_update("HEAD",
957 initial_commit ? NULL : head_sha1,
960 nl = strchr(sb.buf + header_len, '\n');
961 if (nl)
962 strbuf_setlen(&sb, nl + 1 - sb.buf);
963 else
964 strbuf_addch(&sb, '\n');
965 strbuf_remove(&sb, 0, header_len);
966 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
967 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
969 if (!ref_lock) {
970 rollback_index_files();
971 die("cannot lock HEAD ref");
973 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
974 rollback_index_files();
975 die("cannot update HEAD ref");
978 unlink(git_path("MERGE_HEAD"));
979 unlink(git_path("MERGE_MSG"));
980 unlink(git_path("SQUASH_MSG"));
982 if (commit_index_files())
983 die ("Repository has been updated, but unable to write\n"
984 "new_index file. Check that disk is not full or quota is\n"
985 "not exceeded, and then \"git reset HEAD\" to recover.");
987 rerere();
988 run_hook(get_index_file(), "post-commit", NULL);
989 if (!quiet)
990 print_summary(prefix, commit_sha1);
992 return 0;