status: reduce duplicated setup code
[git/dscho.git] / builtin-commit.c
blobb39295fbf25233570ceaf0205682874d5c873d13
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"
27 #include "quote.h"
29 static const char * const builtin_commit_usage[] = {
30 "git commit [options] [--] <filepattern>...",
31 NULL
34 static const char * const builtin_status_usage[] = {
35 "git status [options] [--] <filepattern>...",
36 NULL
39 static unsigned char head_sha1[20], merge_head_sha1[20];
40 static char *use_message_buffer;
41 static const char commit_editmsg[] = "COMMIT_EDITMSG";
42 static struct lock_file index_lock; /* real index */
43 static struct lock_file false_lock; /* used only for partial commits */
44 static enum {
45 COMMIT_AS_IS = 1,
46 COMMIT_NORMAL,
47 COMMIT_PARTIAL,
48 } commit_style;
50 static const char *logfile, *force_author;
51 static const char *template_file;
52 static char *edit_message, *use_message;
53 static char *author_name, *author_email, *author_date;
54 static int all, edit_flag, also, interactive, only, amend, signoff;
55 static int quiet, verbose, no_verify, allow_empty, dry_run;
56 static char *untracked_files_arg;
58 * The default commit message cleanup mode will remove the lines
59 * beginning with # (shell comments) and leading and trailing
60 * whitespaces (empty lines or containing only whitespaces)
61 * if editor is used, and only the whitespaces if the message
62 * is specified explicitly.
64 static enum {
65 CLEANUP_SPACE,
66 CLEANUP_NONE,
67 CLEANUP_ALL,
68 } cleanup_mode;
69 static char *cleanup_arg;
71 static int use_editor = 1, initial_commit, in_merge;
72 static const char *only_include_assumed;
73 static struct strbuf message;
75 static int null_termination;
76 static enum {
77 STATUS_FORMAT_LONG,
78 STATUS_FORMAT_SHORT,
79 STATUS_FORMAT_PORCELAIN,
80 } status_format = STATUS_FORMAT_LONG;
82 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
84 struct strbuf *buf = opt->value;
85 if (unset)
86 strbuf_setlen(buf, 0);
87 else {
88 strbuf_addstr(buf, arg);
89 strbuf_addstr(buf, "\n\n");
91 return 0;
94 static struct option builtin_commit_options[] = {
95 OPT__QUIET(&quiet),
96 OPT__VERBOSE(&verbose),
97 OPT_GROUP("Commit message options"),
99 OPT_FILENAME('F', "file", &logfile, "read log from file"),
100 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
101 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
102 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
103 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
104 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
105 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
106 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
108 OPT_GROUP("Commit contents options"),
109 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
110 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
111 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
112 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
113 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
114 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
115 OPT_SET_INT(0, "short", &status_format, "show status concisely",
116 STATUS_FORMAT_SHORT),
117 OPT_SET_INT(0, "porcelain", &status_format,
118 "show porcelain output format", STATUS_FORMAT_PORCELAIN),
119 OPT_BOOLEAN('z', "null", &null_termination,
120 "terminate entries with NUL"),
121 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
122 { 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" },
123 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
124 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
126 OPT_END()
129 static void rollback_index_files(void)
131 switch (commit_style) {
132 case COMMIT_AS_IS:
133 break; /* nothing to do */
134 case COMMIT_NORMAL:
135 rollback_lock_file(&index_lock);
136 break;
137 case COMMIT_PARTIAL:
138 rollback_lock_file(&index_lock);
139 rollback_lock_file(&false_lock);
140 break;
144 static int commit_index_files(void)
146 int err = 0;
148 switch (commit_style) {
149 case COMMIT_AS_IS:
150 break; /* nothing to do */
151 case COMMIT_NORMAL:
152 err = commit_lock_file(&index_lock);
153 break;
154 case COMMIT_PARTIAL:
155 err = commit_lock_file(&index_lock);
156 rollback_lock_file(&false_lock);
157 break;
160 return err;
164 * Take a union of paths in the index and the named tree (typically, "HEAD"),
165 * and return the paths that match the given pattern in list.
167 static int list_paths(struct string_list *list, const char *with_tree,
168 const char *prefix, const char **pattern)
170 int i;
171 char *m;
173 for (i = 0; pattern[i]; i++)
175 m = xcalloc(1, i);
177 if (with_tree)
178 overlay_tree_on_cache(with_tree, prefix);
180 for (i = 0; i < active_nr; i++) {
181 struct cache_entry *ce = active_cache[i];
182 if (ce->ce_flags & CE_UPDATE)
183 continue;
184 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
185 continue;
186 string_list_insert(ce->name, list);
189 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
192 static void add_remove_files(struct string_list *list)
194 int i;
195 for (i = 0; i < list->nr; i++) {
196 struct stat st;
197 struct string_list_item *p = &(list->items[i]);
199 if (!lstat(p->string, &st)) {
200 if (add_to_cache(p->string, &st, 0))
201 die("updating files failed");
202 } else
203 remove_file_from_cache(p->string);
207 static void create_base_index(void)
209 struct tree *tree;
210 struct unpack_trees_options opts;
211 struct tree_desc t;
213 if (initial_commit) {
214 discard_cache();
215 return;
218 memset(&opts, 0, sizeof(opts));
219 opts.head_idx = 1;
220 opts.index_only = 1;
221 opts.merge = 1;
222 opts.src_index = &the_index;
223 opts.dst_index = &the_index;
225 opts.fn = oneway_merge;
226 tree = parse_tree_indirect(head_sha1);
227 if (!tree)
228 die("failed to unpack HEAD tree object");
229 parse_tree(tree);
230 init_tree_desc(&t, tree->buffer, tree->size);
231 if (unpack_trees(1, &t, &opts))
232 exit(128); /* We've already reported the error, finish dying */
235 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
237 int fd;
238 struct string_list partial;
239 const char **pathspec = NULL;
240 int refresh_flags = REFRESH_QUIET;
242 if (is_status)
243 refresh_flags |= REFRESH_UNMERGED;
244 if (interactive) {
245 if (interactive_add(argc, argv, prefix) != 0)
246 die("interactive add failed");
247 if (read_cache_preload(NULL) < 0)
248 die("index file corrupt");
249 commit_style = COMMIT_AS_IS;
250 return get_index_file();
253 if (*argv)
254 pathspec = get_pathspec(prefix, argv);
256 if (read_cache_preload(pathspec) < 0)
257 die("index file corrupt");
260 * Non partial, non as-is commit.
262 * (1) get the real index;
263 * (2) update the_index as necessary;
264 * (3) write the_index out to the real index (still locked);
265 * (4) return the name of the locked index file.
267 * The caller should run hooks on the locked real index, and
268 * (A) if all goes well, commit the real index;
269 * (B) on failure, rollback the real index.
271 if (all || (also && pathspec && *pathspec)) {
272 int fd = hold_locked_index(&index_lock, 1);
273 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
274 refresh_cache(refresh_flags);
275 if (write_cache(fd, active_cache, active_nr) ||
276 close_lock_file(&index_lock))
277 die("unable to write new_index file");
278 commit_style = COMMIT_NORMAL;
279 return index_lock.filename;
283 * As-is commit.
285 * (1) return the name of the real index file.
287 * The caller should run hooks on the real index, and run
288 * hooks on the real index, and create commit from the_index.
289 * We still need to refresh the index here.
291 if (!pathspec || !*pathspec) {
292 fd = hold_locked_index(&index_lock, 1);
293 refresh_cache(refresh_flags);
294 if (write_cache(fd, active_cache, active_nr) ||
295 commit_locked_index(&index_lock))
296 die("unable to write new_index file");
297 commit_style = COMMIT_AS_IS;
298 return get_index_file();
302 * A partial commit.
304 * (0) find the set of affected paths;
305 * (1) get lock on the real index file;
306 * (2) update the_index with the given paths;
307 * (3) write the_index out to the real index (still locked);
308 * (4) get lock on the false index file;
309 * (5) reset the_index from HEAD;
310 * (6) update the_index the same way as (2);
311 * (7) write the_index out to the false index file;
312 * (8) return the name of the false index file (still locked);
314 * The caller should run hooks on the locked false index, and
315 * create commit from it. Then
316 * (A) if all goes well, commit the real index;
317 * (B) on failure, rollback the real index;
318 * In either case, rollback the false index.
320 commit_style = COMMIT_PARTIAL;
322 if (file_exists(git_path("MERGE_HEAD")))
323 die("cannot do a partial commit during a merge.");
325 memset(&partial, 0, sizeof(partial));
326 partial.strdup_strings = 1;
327 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
328 exit(1);
330 discard_cache();
331 if (read_cache() < 0)
332 die("cannot read the index");
334 fd = hold_locked_index(&index_lock, 1);
335 add_remove_files(&partial);
336 refresh_cache(REFRESH_QUIET);
337 if (write_cache(fd, active_cache, active_nr) ||
338 close_lock_file(&index_lock))
339 die("unable to write new_index file");
341 fd = hold_lock_file_for_update(&false_lock,
342 git_path("next-index-%"PRIuMAX,
343 (uintmax_t) getpid()),
344 LOCK_DIE_ON_ERROR);
346 create_base_index();
347 add_remove_files(&partial);
348 refresh_cache(REFRESH_QUIET);
350 if (write_cache(fd, active_cache, active_nr) ||
351 close_lock_file(&false_lock))
352 die("unable to write temporary index file");
354 discard_cache();
355 read_cache_from(false_lock.filename);
357 return false_lock.filename;
360 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
361 struct wt_status *s)
363 unsigned char sha1[20];
365 if (s->relative_paths)
366 s->prefix = prefix;
368 if (amend) {
369 s->amend = 1;
370 s->reference = "HEAD^1";
372 s->verbose = verbose;
373 s->index_file = index_file;
374 s->fp = fp;
375 s->nowarn = nowarn;
376 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
378 wt_status_collect(s);
380 switch (status_format) {
381 case STATUS_FORMAT_SHORT:
382 wt_shortstatus_print(s, null_termination);
383 break;
384 case STATUS_FORMAT_PORCELAIN:
385 wt_porcelain_print(s, null_termination);
386 break;
387 case STATUS_FORMAT_LONG:
388 wt_status_print(s);
389 break;
392 return s->commitable;
395 static int is_a_merge(const unsigned char *sha1)
397 struct commit *commit = lookup_commit(sha1);
398 if (!commit || parse_commit(commit))
399 die("could not parse HEAD commit");
400 return !!(commit->parents && commit->parents->next);
403 static const char sign_off_header[] = "Signed-off-by: ";
405 static void determine_author_info(void)
407 char *name, *email, *date;
409 name = getenv("GIT_AUTHOR_NAME");
410 email = getenv("GIT_AUTHOR_EMAIL");
411 date = getenv("GIT_AUTHOR_DATE");
413 if (use_message) {
414 const char *a, *lb, *rb, *eol;
416 a = strstr(use_message_buffer, "\nauthor ");
417 if (!a)
418 die("invalid commit: %s", use_message);
420 lb = strstr(a + 8, " <");
421 rb = strstr(a + 8, "> ");
422 eol = strchr(a + 8, '\n');
423 if (!lb || !rb || !eol)
424 die("invalid commit: %s", use_message);
426 name = xstrndup(a + 8, lb - (a + 8));
427 email = xstrndup(lb + 2, rb - (lb + 2));
428 date = xstrndup(rb + 2, eol - (rb + 2));
431 if (force_author) {
432 const char *lb = strstr(force_author, " <");
433 const char *rb = strchr(force_author, '>');
435 if (!lb || !rb)
436 die("malformed --author parameter");
437 name = xstrndup(force_author, lb - force_author);
438 email = xstrndup(lb + 2, rb - (lb + 2));
441 author_name = name;
442 author_email = email;
443 author_date = date;
446 static int prepare_to_commit(const char *index_file, const char *prefix,
447 struct wt_status *s)
449 struct stat statbuf;
450 int commitable, saved_color_setting;
451 struct strbuf sb = STRBUF_INIT;
452 char *buffer;
453 FILE *fp;
454 const char *hook_arg1 = NULL;
455 const char *hook_arg2 = NULL;
456 int ident_shown = 0;
458 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
459 return 0;
461 if (message.len) {
462 strbuf_addbuf(&sb, &message);
463 hook_arg1 = "message";
464 } else if (logfile && !strcmp(logfile, "-")) {
465 if (isatty(0))
466 fprintf(stderr, "(reading log message from standard input)\n");
467 if (strbuf_read(&sb, 0, 0) < 0)
468 die_errno("could not read log from standard input");
469 hook_arg1 = "message";
470 } else if (logfile) {
471 if (strbuf_read_file(&sb, logfile, 0) < 0)
472 die_errno("could not read log file '%s'",
473 logfile);
474 hook_arg1 = "message";
475 } else if (use_message) {
476 buffer = strstr(use_message_buffer, "\n\n");
477 if (!buffer || buffer[2] == '\0')
478 die("commit has empty message");
479 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
480 hook_arg1 = "commit";
481 hook_arg2 = use_message;
482 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
483 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
484 die_errno("could not read MERGE_MSG");
485 hook_arg1 = "merge";
486 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
487 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
488 die_errno("could not read SQUASH_MSG");
489 hook_arg1 = "squash";
490 } else if (template_file && !stat(template_file, &statbuf)) {
491 if (strbuf_read_file(&sb, template_file, 0) < 0)
492 die_errno("could not read '%s'", template_file);
493 hook_arg1 = "template";
497 * This final case does not modify the template message,
498 * it just sets the argument to the prepare-commit-msg hook.
500 else if (in_merge)
501 hook_arg1 = "merge";
503 fp = fopen(git_path(commit_editmsg), "w");
504 if (fp == NULL)
505 die_errno("could not open '%s'", git_path(commit_editmsg));
507 if (cleanup_mode != CLEANUP_NONE)
508 stripspace(&sb, 0);
510 if (signoff) {
511 struct strbuf sob = STRBUF_INIT;
512 int i;
514 strbuf_addstr(&sob, sign_off_header);
515 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
516 getenv("GIT_COMMITTER_EMAIL")));
517 strbuf_addch(&sob, '\n');
518 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
519 ; /* do nothing */
520 if (prefixcmp(sb.buf + i, sob.buf)) {
521 if (prefixcmp(sb.buf + i, sign_off_header))
522 strbuf_addch(&sb, '\n');
523 strbuf_addbuf(&sb, &sob);
525 strbuf_release(&sob);
528 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
529 die_errno("could not write commit template");
531 strbuf_release(&sb);
533 determine_author_info();
535 /* This checks if committer ident is explicitly given */
536 git_committer_info(0);
537 if (use_editor) {
538 char *author_ident;
539 const char *committer_ident;
541 if (in_merge)
542 fprintf(fp,
543 "#\n"
544 "# It looks like you may be committing a MERGE.\n"
545 "# If this is not correct, please remove the file\n"
546 "# %s\n"
547 "# and try again.\n"
548 "#\n",
549 git_path("MERGE_HEAD"));
551 fprintf(fp,
552 "\n"
553 "# Please enter the commit message for your changes.");
554 if (cleanup_mode == CLEANUP_ALL)
555 fprintf(fp,
556 " Lines starting\n"
557 "# with '#' will be ignored, and an empty"
558 " message aborts the commit.\n");
559 else /* CLEANUP_SPACE, that is. */
560 fprintf(fp,
561 " Lines starting\n"
562 "# with '#' will be kept; you may remove them"
563 " yourself if you want to.\n"
564 "# An empty message aborts the commit.\n");
565 if (only_include_assumed)
566 fprintf(fp, "# %s\n", only_include_assumed);
568 author_ident = xstrdup(fmt_name(author_name, author_email));
569 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
570 getenv("GIT_COMMITTER_EMAIL"));
571 if (strcmp(author_ident, committer_ident))
572 fprintf(fp,
573 "%s"
574 "# Author: %s\n",
575 ident_shown++ ? "" : "#\n",
576 author_ident);
577 free(author_ident);
579 if (!user_ident_explicitly_given)
580 fprintf(fp,
581 "%s"
582 "# Committer: %s\n",
583 ident_shown++ ? "" : "#\n",
584 committer_ident);
586 if (ident_shown)
587 fprintf(fp, "#\n");
589 saved_color_setting = s->use_color;
590 s->use_color = 0;
591 commitable = run_status(fp, index_file, prefix, 1, s);
592 s->use_color = saved_color_setting;
593 } else {
594 unsigned char sha1[20];
595 const char *parent = "HEAD";
597 if (!active_nr && read_cache() < 0)
598 die("Cannot read index");
600 if (amend)
601 parent = "HEAD^1";
603 if (get_sha1(parent, sha1))
604 commitable = !!active_nr;
605 else
606 commitable = index_differs_from(parent, 0);
609 fclose(fp);
611 if (!commitable && !in_merge && !allow_empty &&
612 !(amend && is_a_merge(head_sha1))) {
613 run_status(stdout, index_file, prefix, 0, s);
614 return 0;
618 * Re-read the index as pre-commit hook could have updated it,
619 * and write it out as a tree. We must do this before we invoke
620 * the editor and after we invoke run_status above.
622 discard_cache();
623 read_cache_from(index_file);
624 if (!active_cache_tree)
625 active_cache_tree = cache_tree();
626 if (cache_tree_update(active_cache_tree,
627 active_cache, active_nr, 0, 0) < 0) {
628 error("Error building trees");
629 return 0;
632 if (run_hook(index_file, "prepare-commit-msg",
633 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
634 return 0;
636 if (use_editor) {
637 char index[PATH_MAX];
638 const char *env[2] = { index, NULL };
639 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
640 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
641 fprintf(stderr,
642 "Please supply the message using either -m or -F option.\n");
643 exit(1);
647 if (!no_verify &&
648 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
649 return 0;
652 return 1;
656 * Find out if the message in the strbuf contains only whitespace and
657 * Signed-off-by lines.
659 static int message_is_empty(struct strbuf *sb)
661 struct strbuf tmpl = STRBUF_INIT;
662 const char *nl;
663 int eol, i, start = 0;
665 if (cleanup_mode == CLEANUP_NONE && sb->len)
666 return 0;
668 /* See if the template is just a prefix of the message. */
669 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
670 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
671 if (start + tmpl.len <= sb->len &&
672 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
673 start += tmpl.len;
675 strbuf_release(&tmpl);
677 /* Check if the rest is just whitespace and Signed-of-by's. */
678 for (i = start; i < sb->len; i++) {
679 nl = memchr(sb->buf + i, '\n', sb->len - i);
680 if (nl)
681 eol = nl - sb->buf;
682 else
683 eol = sb->len;
685 if (strlen(sign_off_header) <= eol - i &&
686 !prefixcmp(sb->buf + i, sign_off_header)) {
687 i = eol;
688 continue;
690 while (i < eol)
691 if (!isspace(sb->buf[i++]))
692 return 0;
695 return 1;
698 static const char *find_author_by_nickname(const char *name)
700 struct rev_info revs;
701 struct commit *commit;
702 struct strbuf buf = STRBUF_INIT;
703 const char *av[20];
704 int ac = 0;
706 init_revisions(&revs, NULL);
707 strbuf_addf(&buf, "--author=%s", name);
708 av[++ac] = "--all";
709 av[++ac] = "-i";
710 av[++ac] = buf.buf;
711 av[++ac] = NULL;
712 setup_revisions(ac, av, &revs, NULL);
713 prepare_revision_walk(&revs);
714 commit = get_revision(&revs);
715 if (commit) {
716 strbuf_release(&buf);
717 format_commit_message(commit, "%an <%ae>", &buf, DATE_NORMAL);
718 return strbuf_detach(&buf, NULL);
720 die("No existing author found with '%s'", name);
724 static void handle_untracked_files_arg(struct wt_status *s)
726 if (!untracked_files_arg)
727 ; /* default already initialized */
728 else if (!strcmp(untracked_files_arg, "no"))
729 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
730 else if (!strcmp(untracked_files_arg, "normal"))
731 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
732 else if (!strcmp(untracked_files_arg, "all"))
733 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
734 else
735 die("Invalid untracked files mode '%s'", untracked_files_arg);
738 static int parse_and_validate_options(int argc, const char *argv[],
739 const char * const usage[],
740 const char *prefix,
741 struct wt_status *s)
743 int f = 0;
745 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
748 if (force_author && !strchr(force_author, '>'))
749 force_author = find_author_by_nickname(force_author);
751 if (logfile || message.len || use_message)
752 use_editor = 0;
753 if (edit_flag)
754 use_editor = 1;
755 if (!use_editor)
756 setenv("GIT_EDITOR", ":", 1);
758 if (get_sha1("HEAD", head_sha1))
759 initial_commit = 1;
761 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
762 in_merge = 1;
764 /* Sanity check options */
765 if (amend && initial_commit)
766 die("You have nothing to amend.");
767 if (amend && in_merge)
768 die("You are in the middle of a merge -- cannot amend.");
770 if (use_message)
771 f++;
772 if (edit_message)
773 f++;
774 if (logfile)
775 f++;
776 if (f > 1)
777 die("Only one of -c/-C/-F can be used.");
778 if (message.len && f > 0)
779 die("Option -m cannot be combined with -c/-C/-F.");
780 if (edit_message)
781 use_message = edit_message;
782 if (amend && !use_message)
783 use_message = "HEAD";
784 if (use_message) {
785 unsigned char sha1[20];
786 static char utf8[] = "UTF-8";
787 const char *out_enc;
788 char *enc, *end;
789 struct commit *commit;
791 if (get_sha1(use_message, sha1))
792 die("could not lookup commit %s", use_message);
793 commit = lookup_commit_reference(sha1);
794 if (!commit || parse_commit(commit))
795 die("could not parse commit %s", use_message);
797 enc = strstr(commit->buffer, "\nencoding");
798 if (enc) {
799 end = strchr(enc + 10, '\n');
800 enc = xstrndup(enc + 10, end - (enc + 10));
801 } else {
802 enc = utf8;
804 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
806 if (strcmp(out_enc, enc))
807 use_message_buffer =
808 reencode_string(commit->buffer, out_enc, enc);
811 * If we failed to reencode the buffer, just copy it
812 * byte for byte so the user can try to fix it up.
813 * This also handles the case where input and output
814 * encodings are identical.
816 if (use_message_buffer == NULL)
817 use_message_buffer = xstrdup(commit->buffer);
818 if (enc != utf8)
819 free(enc);
822 if (!!also + !!only + !!all + !!interactive > 1)
823 die("Only one of --include/--only/--all/--interactive can be used.");
824 if (argc == 0 && (also || (only && !amend)))
825 die("No paths with --include/--only does not make sense.");
826 if (argc == 0 && only && amend)
827 only_include_assumed = "Clever... amending the last one with dirty index.";
828 if (argc > 0 && !also && !only)
829 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
830 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
831 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
832 else if (!strcmp(cleanup_arg, "verbatim"))
833 cleanup_mode = CLEANUP_NONE;
834 else if (!strcmp(cleanup_arg, "whitespace"))
835 cleanup_mode = CLEANUP_SPACE;
836 else if (!strcmp(cleanup_arg, "strip"))
837 cleanup_mode = CLEANUP_ALL;
838 else
839 die("Invalid cleanup mode %s", cleanup_arg);
841 handle_untracked_files_arg(s);
843 if (all && argc > 0)
844 die("Paths with -a does not make sense.");
845 else if (interactive && argc > 0)
846 die("Paths with --interactive does not make sense.");
848 if (null_termination && status_format == STATUS_FORMAT_LONG)
849 status_format = STATUS_FORMAT_PORCELAIN;
850 if (status_format != STATUS_FORMAT_LONG)
851 dry_run = 1;
853 return argc;
856 static int dry_run_commit(int argc, const char **argv, const char *prefix,
857 struct wt_status *s)
859 int commitable;
860 const char *index_file;
862 index_file = prepare_index(argc, argv, prefix, 1);
863 commitable = run_status(stdout, index_file, prefix, 0, s);
864 rollback_index_files();
866 return commitable ? 0 : 1;
869 static int parse_status_slot(const char *var, int offset)
871 if (!strcasecmp(var+offset, "header"))
872 return WT_STATUS_HEADER;
873 if (!strcasecmp(var+offset, "updated")
874 || !strcasecmp(var+offset, "added"))
875 return WT_STATUS_UPDATED;
876 if (!strcasecmp(var+offset, "changed"))
877 return WT_STATUS_CHANGED;
878 if (!strcasecmp(var+offset, "untracked"))
879 return WT_STATUS_UNTRACKED;
880 if (!strcasecmp(var+offset, "nobranch"))
881 return WT_STATUS_NOBRANCH;
882 if (!strcasecmp(var+offset, "unmerged"))
883 return WT_STATUS_UNMERGED;
884 die("bad config variable '%s'", var);
887 static int git_status_config(const char *k, const char *v, void *cb)
889 struct wt_status *s = cb;
891 if (!strcmp(k, "status.submodulesummary")) {
892 int is_bool;
893 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
894 if (is_bool && s->submodule_summary)
895 s->submodule_summary = -1;
896 return 0;
898 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
899 s->use_color = git_config_colorbool(k, v, -1);
900 return 0;
902 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
903 int slot = parse_status_slot(k, 13);
904 if (!v)
905 return config_error_nonbool(k);
906 color_parse(v, k, s->color_palette[slot]);
907 return 0;
909 if (!strcmp(k, "status.relativepaths")) {
910 s->relative_paths = git_config_bool(k, v);
911 return 0;
913 if (!strcmp(k, "status.showuntrackedfiles")) {
914 if (!v)
915 return config_error_nonbool(k);
916 else if (!strcmp(v, "no"))
917 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
918 else if (!strcmp(v, "normal"))
919 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
920 else if (!strcmp(v, "all"))
921 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
922 else
923 return error("Invalid untracked files mode '%s'", v);
924 return 0;
926 return git_diff_ui_config(k, v, NULL);
929 int cmd_status(int argc, const char **argv, const char *prefix)
931 struct wt_status s;
932 unsigned char sha1[20];
933 static struct option builtin_status_options[] = {
934 OPT__VERBOSE(&verbose),
935 OPT_SET_INT('s', "short", &status_format,
936 "show status concisely", STATUS_FORMAT_SHORT),
937 OPT_SET_INT(0, "porcelain", &status_format,
938 "show porcelain output format",
939 STATUS_FORMAT_PORCELAIN),
940 OPT_BOOLEAN('z', "null", &null_termination,
941 "terminate entries with NUL"),
942 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
943 "mode",
944 "show untracked files, optional modes: all, normal, no. (Default: all)",
945 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
946 OPT_END(),
949 if (null_termination && status_format == STATUS_FORMAT_LONG)
950 status_format = STATUS_FORMAT_PORCELAIN;
952 wt_status_prepare(&s);
953 git_config(git_status_config, &s);
954 argc = parse_options(argc, argv, prefix,
955 builtin_status_options,
956 builtin_status_usage, 0);
957 handle_untracked_files_arg(&s);
959 if (*argv)
960 s.pathspec = get_pathspec(prefix, argv);
962 read_cache();
963 refresh_cache(REFRESH_QUIET|REFRESH_UNMERGED);
964 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
965 wt_status_collect(&s);
967 if (s.relative_paths)
968 s.prefix = prefix;
969 if (s.use_color == -1)
970 s.use_color = git_use_color_default;
971 if (diff_use_color_default == -1)
972 diff_use_color_default = git_use_color_default;
974 switch (status_format) {
975 case STATUS_FORMAT_SHORT:
976 wt_shortstatus_print(&s, null_termination);
977 break;
978 case STATUS_FORMAT_PORCELAIN:
979 wt_porcelain_print(&s, null_termination);
980 break;
981 case STATUS_FORMAT_LONG:
982 s.verbose = verbose;
983 wt_status_print(&s);
984 break;
986 return 0;
989 static void print_summary(const char *prefix, const unsigned char *sha1)
991 struct rev_info rev;
992 struct commit *commit;
993 static const char *format = "format:%h] %s";
994 unsigned char junk_sha1[20];
995 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
997 commit = lookup_commit(sha1);
998 if (!commit)
999 die("couldn't look up newly created commit");
1000 if (!commit || parse_commit(commit))
1001 die("could not parse newly created commit");
1003 init_revisions(&rev, prefix);
1004 setup_revisions(0, NULL, &rev, NULL);
1006 rev.abbrev = 0;
1007 rev.diff = 1;
1008 rev.diffopt.output_format =
1009 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1011 rev.verbose_header = 1;
1012 rev.show_root_diff = 1;
1013 get_commit_format(format, &rev);
1014 rev.always_show_header = 0;
1015 rev.diffopt.detect_rename = 1;
1016 rev.diffopt.rename_limit = 100;
1017 rev.diffopt.break_opt = 0;
1018 diff_setup_done(&rev.diffopt);
1020 printf("[%s%s ",
1021 !prefixcmp(head, "refs/heads/") ?
1022 head + 11 :
1023 !strcmp(head, "HEAD") ?
1024 "detached HEAD" :
1025 head,
1026 initial_commit ? " (root-commit)" : "");
1028 if (!log_tree_commit(&rev, commit)) {
1029 struct strbuf buf = STRBUF_INIT;
1030 format_commit_message(commit, format + 7, &buf, DATE_NORMAL);
1031 printf("%s\n", buf.buf);
1032 strbuf_release(&buf);
1036 static int git_commit_config(const char *k, const char *v, void *cb)
1038 struct wt_status *s = cb;
1040 if (!strcmp(k, "commit.template"))
1041 return git_config_string(&template_file, k, v);
1043 return git_status_config(k, v, s);
1046 int cmd_commit(int argc, const char **argv, const char *prefix)
1048 struct strbuf sb = STRBUF_INIT;
1049 const char *index_file, *reflog_msg;
1050 char *nl, *p;
1051 unsigned char commit_sha1[20];
1052 struct ref_lock *ref_lock;
1053 struct commit_list *parents = NULL, **pptr = &parents;
1054 struct stat statbuf;
1055 int allow_fast_forward = 1;
1056 struct wt_status s;
1058 wt_status_prepare(&s);
1059 git_config(git_commit_config, &s);
1061 if (s.use_color == -1)
1062 s.use_color = git_use_color_default;
1064 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1065 prefix, &s);
1066 if (dry_run) {
1067 if (diff_use_color_default == -1)
1068 diff_use_color_default = git_use_color_default;
1069 return dry_run_commit(argc, argv, prefix, &s);
1071 index_file = prepare_index(argc, argv, prefix, 0);
1073 /* Set up everything for writing the commit object. This includes
1074 running hooks, writing the trees, and interacting with the user. */
1075 if (!prepare_to_commit(index_file, prefix, &s)) {
1076 rollback_index_files();
1077 return 1;
1080 /* Determine parents */
1081 if (initial_commit) {
1082 reflog_msg = "commit (initial)";
1083 } else if (amend) {
1084 struct commit_list *c;
1085 struct commit *commit;
1087 reflog_msg = "commit (amend)";
1088 commit = lookup_commit(head_sha1);
1089 if (!commit || parse_commit(commit))
1090 die("could not parse HEAD commit");
1092 for (c = commit->parents; c; c = c->next)
1093 pptr = &commit_list_insert(c->item, pptr)->next;
1094 } else if (in_merge) {
1095 struct strbuf m = STRBUF_INIT;
1096 FILE *fp;
1098 reflog_msg = "commit (merge)";
1099 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1100 fp = fopen(git_path("MERGE_HEAD"), "r");
1101 if (fp == NULL)
1102 die_errno("could not open '%s' for reading",
1103 git_path("MERGE_HEAD"));
1104 while (strbuf_getline(&m, fp, '\n') != EOF) {
1105 unsigned char sha1[20];
1106 if (get_sha1_hex(m.buf, sha1) < 0)
1107 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1108 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1110 fclose(fp);
1111 strbuf_release(&m);
1112 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1113 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1114 die_errno("could not read MERGE_MODE");
1115 if (!strcmp(sb.buf, "no-ff"))
1116 allow_fast_forward = 0;
1118 if (allow_fast_forward)
1119 parents = reduce_heads(parents);
1120 } else {
1121 reflog_msg = "commit";
1122 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1125 /* Finally, get the commit message */
1126 strbuf_reset(&sb);
1127 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1128 int saved_errno = errno;
1129 rollback_index_files();
1130 die("could not read commit message: %s", strerror(saved_errno));
1133 /* Truncate the message just before the diff, if any. */
1134 if (verbose) {
1135 p = strstr(sb.buf, "\ndiff --git ");
1136 if (p != NULL)
1137 strbuf_setlen(&sb, p - sb.buf + 1);
1140 if (cleanup_mode != CLEANUP_NONE)
1141 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1142 if (message_is_empty(&sb)) {
1143 rollback_index_files();
1144 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1145 exit(1);
1148 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1149 fmt_ident(author_name, author_email, author_date,
1150 IDENT_ERROR_ON_NO_NAME))) {
1151 rollback_index_files();
1152 die("failed to write commit object");
1155 ref_lock = lock_any_ref_for_update("HEAD",
1156 initial_commit ? NULL : head_sha1,
1159 nl = strchr(sb.buf, '\n');
1160 if (nl)
1161 strbuf_setlen(&sb, nl + 1 - sb.buf);
1162 else
1163 strbuf_addch(&sb, '\n');
1164 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1165 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1167 if (!ref_lock) {
1168 rollback_index_files();
1169 die("cannot lock HEAD ref");
1171 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1172 rollback_index_files();
1173 die("cannot update HEAD ref");
1176 unlink(git_path("MERGE_HEAD"));
1177 unlink(git_path("MERGE_MSG"));
1178 unlink(git_path("MERGE_MODE"));
1179 unlink(git_path("SQUASH_MSG"));
1181 if (commit_index_files())
1182 die ("Repository has been updated, but unable to write\n"
1183 "new_index file. Check that disk is not full or quota is\n"
1184 "not exceeded, and then \"git reset HEAD\" to recover.");
1186 rerere();
1187 run_hook(get_index_file(), "post-commit", NULL);
1188 if (!quiet)
1189 print_summary(prefix, commit_sha1);
1191 return 0;