Merge branch 'dk/blame-el' into pu
[git/spearce.git] / builtin-commit.c
blobf2fd0a4580820dc3d78681a7bcd3145dc94a0513
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 void short_print(struct wt_status *s, int null_termination);
84 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
86 struct strbuf *buf = opt->value;
87 if (unset)
88 strbuf_setlen(buf, 0);
89 else {
90 strbuf_addstr(buf, arg);
91 strbuf_addstr(buf, "\n\n");
93 return 0;
96 static struct option builtin_commit_options[] = {
97 OPT__QUIET(&quiet),
98 OPT__VERBOSE(&verbose),
99 OPT_GROUP("Commit message options"),
101 OPT_FILENAME('F', "file", &logfile, "read log from file"),
102 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
103 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
104 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
105 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
106 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
107 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
108 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
110 OPT_GROUP("Commit contents options"),
111 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
112 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
113 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
114 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
115 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
116 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
117 OPT_SET_INT(0, "short", &status_format, "show status concisely",
118 STATUS_FORMAT_SHORT),
119 OPT_SET_INT(0, "porcelain", &status_format,
120 "show porcelain output format", STATUS_FORMAT_PORCELAIN),
121 OPT_BOOLEAN('z', "null", &null_termination,
122 "terminate entries with NUL"),
123 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
124 { 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" },
125 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
126 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
128 OPT_END()
131 static void rollback_index_files(void)
133 switch (commit_style) {
134 case COMMIT_AS_IS:
135 break; /* nothing to do */
136 case COMMIT_NORMAL:
137 rollback_lock_file(&index_lock);
138 break;
139 case COMMIT_PARTIAL:
140 rollback_lock_file(&index_lock);
141 rollback_lock_file(&false_lock);
142 break;
146 static int commit_index_files(void)
148 int err = 0;
150 switch (commit_style) {
151 case COMMIT_AS_IS:
152 break; /* nothing to do */
153 case COMMIT_NORMAL:
154 err = commit_lock_file(&index_lock);
155 break;
156 case COMMIT_PARTIAL:
157 err = commit_lock_file(&index_lock);
158 rollback_lock_file(&false_lock);
159 break;
162 return err;
166 * Take a union of paths in the index and the named tree (typically, "HEAD"),
167 * and return the paths that match the given pattern in list.
169 static int list_paths(struct string_list *list, const char *with_tree,
170 const char *prefix, const char **pattern)
172 int i;
173 char *m;
175 for (i = 0; pattern[i]; i++)
177 m = xcalloc(1, i);
179 if (with_tree)
180 overlay_tree_on_cache(with_tree, prefix);
182 for (i = 0; i < active_nr; i++) {
183 struct cache_entry *ce = active_cache[i];
184 if (ce->ce_flags & CE_UPDATE)
185 continue;
186 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
187 continue;
188 string_list_insert(ce->name, list);
191 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
194 static void add_remove_files(struct string_list *list)
196 int i;
197 for (i = 0; i < list->nr; i++) {
198 struct stat st;
199 struct string_list_item *p = &(list->items[i]);
201 if (!lstat(p->string, &st)) {
202 if (add_to_cache(p->string, &st, 0))
203 die("updating files failed");
204 } else
205 remove_file_from_cache(p->string);
209 static void create_base_index(void)
211 struct tree *tree;
212 struct unpack_trees_options opts;
213 struct tree_desc t;
215 if (initial_commit) {
216 discard_cache();
217 return;
220 memset(&opts, 0, sizeof(opts));
221 opts.head_idx = 1;
222 opts.index_only = 1;
223 opts.merge = 1;
224 opts.src_index = &the_index;
225 opts.dst_index = &the_index;
227 opts.fn = oneway_merge;
228 tree = parse_tree_indirect(head_sha1);
229 if (!tree)
230 die("failed to unpack HEAD tree object");
231 parse_tree(tree);
232 init_tree_desc(&t, tree->buffer, tree->size);
233 if (unpack_trees(1, &t, &opts))
234 exit(128); /* We've already reported the error, finish dying */
237 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
239 int fd;
240 struct string_list partial;
241 const char **pathspec = NULL;
242 int refresh_flags = REFRESH_QUIET;
244 if (is_status)
245 refresh_flags |= REFRESH_UNMERGED;
246 if (interactive) {
247 if (interactive_add(argc, argv, prefix) != 0)
248 die("interactive add failed");
249 if (read_cache_preload(NULL) < 0)
250 die("index file corrupt");
251 commit_style = COMMIT_AS_IS;
252 return get_index_file();
255 if (*argv)
256 pathspec = get_pathspec(prefix, argv);
258 if (read_cache_preload(pathspec) < 0)
259 die("index file corrupt");
262 * Non partial, non as-is commit.
264 * (1) get the real index;
265 * (2) update the_index as necessary;
266 * (3) write the_index out to the real index (still locked);
267 * (4) return the name of the locked index file.
269 * The caller should run hooks on the locked real index, and
270 * (A) if all goes well, commit the real index;
271 * (B) on failure, rollback the real index.
273 if (all || (also && pathspec && *pathspec)) {
274 int fd = hold_locked_index(&index_lock, 1);
275 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
276 refresh_cache(refresh_flags);
277 if (write_cache(fd, active_cache, active_nr) ||
278 close_lock_file(&index_lock))
279 die("unable to write new_index file");
280 commit_style = COMMIT_NORMAL;
281 return index_lock.filename;
285 * As-is commit.
287 * (1) return the name of the real index file.
289 * The caller should run hooks on the real index, and run
290 * hooks on the real index, and create commit from the_index.
291 * We still need to refresh the index here.
293 if (!pathspec || !*pathspec) {
294 fd = hold_locked_index(&index_lock, 1);
295 refresh_cache(refresh_flags);
296 if (write_cache(fd, active_cache, active_nr) ||
297 commit_locked_index(&index_lock))
298 die("unable to write new_index file");
299 commit_style = COMMIT_AS_IS;
300 return get_index_file();
304 * A partial commit.
306 * (0) find the set of affected paths;
307 * (1) get lock on the real index file;
308 * (2) update the_index with the given paths;
309 * (3) write the_index out to the real index (still locked);
310 * (4) get lock on the false index file;
311 * (5) reset the_index from HEAD;
312 * (6) update the_index the same way as (2);
313 * (7) write the_index out to the false index file;
314 * (8) return the name of the false index file (still locked);
316 * The caller should run hooks on the locked false index, and
317 * create commit from it. Then
318 * (A) if all goes well, commit the real index;
319 * (B) on failure, rollback the real index;
320 * In either case, rollback the false index.
322 commit_style = COMMIT_PARTIAL;
324 if (file_exists(git_path("MERGE_HEAD")))
325 die("cannot do a partial commit during a merge.");
327 memset(&partial, 0, sizeof(partial));
328 partial.strdup_strings = 1;
329 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
330 exit(1);
332 discard_cache();
333 if (read_cache() < 0)
334 die("cannot read the index");
336 fd = hold_locked_index(&index_lock, 1);
337 add_remove_files(&partial);
338 refresh_cache(REFRESH_QUIET);
339 if (write_cache(fd, active_cache, active_nr) ||
340 close_lock_file(&index_lock))
341 die("unable to write new_index file");
343 fd = hold_lock_file_for_update(&false_lock,
344 git_path("next-index-%"PRIuMAX,
345 (uintmax_t) getpid()),
346 LOCK_DIE_ON_ERROR);
348 create_base_index();
349 add_remove_files(&partial);
350 refresh_cache(REFRESH_QUIET);
352 if (write_cache(fd, active_cache, active_nr) ||
353 close_lock_file(&false_lock))
354 die("unable to write temporary index file");
356 discard_cache();
357 read_cache_from(false_lock.filename);
359 return false_lock.filename;
362 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
363 struct wt_status *s)
365 unsigned char sha1[20];
367 if (s->relative_paths)
368 s->prefix = prefix;
370 if (amend) {
371 s->amend = 1;
372 s->reference = "HEAD^1";
374 s->verbose = verbose;
375 s->index_file = index_file;
376 s->fp = fp;
377 s->nowarn = nowarn;
378 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
380 wt_status_collect(s);
382 switch (status_format) {
383 case STATUS_FORMAT_SHORT:
384 short_print(s, null_termination);
385 break;
386 case STATUS_FORMAT_PORCELAIN:
387 short_print(s, null_termination);
388 break;
389 case STATUS_FORMAT_LONG:
390 wt_status_print(s);
391 break;
394 return s->commitable;
397 static int is_a_merge(const unsigned char *sha1)
399 struct commit *commit = lookup_commit(sha1);
400 if (!commit || parse_commit(commit))
401 die("could not parse HEAD commit");
402 return !!(commit->parents && commit->parents->next);
405 static const char sign_off_header[] = "Signed-off-by: ";
407 static void determine_author_info(void)
409 char *name, *email, *date;
411 name = getenv("GIT_AUTHOR_NAME");
412 email = getenv("GIT_AUTHOR_EMAIL");
413 date = getenv("GIT_AUTHOR_DATE");
415 if (use_message) {
416 const char *a, *lb, *rb, *eol;
418 a = strstr(use_message_buffer, "\nauthor ");
419 if (!a)
420 die("invalid commit: %s", use_message);
422 lb = strstr(a + 8, " <");
423 rb = strstr(a + 8, "> ");
424 eol = strchr(a + 8, '\n');
425 if (!lb || !rb || !eol)
426 die("invalid commit: %s", use_message);
428 name = xstrndup(a + 8, lb - (a + 8));
429 email = xstrndup(lb + 2, rb - (lb + 2));
430 date = xstrndup(rb + 2, eol - (rb + 2));
433 if (force_author) {
434 const char *lb = strstr(force_author, " <");
435 const char *rb = strchr(force_author, '>');
437 if (!lb || !rb)
438 die("malformed --author parameter");
439 name = xstrndup(force_author, lb - force_author);
440 email = xstrndup(lb + 2, rb - (lb + 2));
443 author_name = name;
444 author_email = email;
445 author_date = date;
448 static int prepare_to_commit(const char *index_file, const char *prefix,
449 struct wt_status *s)
451 struct stat statbuf;
452 int commitable, saved_color_setting;
453 struct strbuf sb = STRBUF_INIT;
454 char *buffer;
455 FILE *fp;
456 const char *hook_arg1 = NULL;
457 const char *hook_arg2 = NULL;
458 int ident_shown = 0;
460 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
461 return 0;
463 if (message.len) {
464 strbuf_addbuf(&sb, &message);
465 hook_arg1 = "message";
466 } else if (logfile && !strcmp(logfile, "-")) {
467 if (isatty(0))
468 fprintf(stderr, "(reading log message from standard input)\n");
469 if (strbuf_read(&sb, 0, 0) < 0)
470 die_errno("could not read log from standard input");
471 hook_arg1 = "message";
472 } else if (logfile) {
473 if (strbuf_read_file(&sb, logfile, 0) < 0)
474 die_errno("could not read log file '%s'",
475 logfile);
476 hook_arg1 = "message";
477 } else if (use_message) {
478 buffer = strstr(use_message_buffer, "\n\n");
479 if (!buffer || buffer[2] == '\0')
480 die("commit has empty message");
481 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
482 hook_arg1 = "commit";
483 hook_arg2 = use_message;
484 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
485 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
486 die_errno("could not read MERGE_MSG");
487 hook_arg1 = "merge";
488 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
489 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
490 die_errno("could not read SQUASH_MSG");
491 hook_arg1 = "squash";
492 } else if (template_file && !stat(template_file, &statbuf)) {
493 if (strbuf_read_file(&sb, template_file, 0) < 0)
494 die_errno("could not read '%s'", template_file);
495 hook_arg1 = "template";
499 * This final case does not modify the template message,
500 * it just sets the argument to the prepare-commit-msg hook.
502 else if (in_merge)
503 hook_arg1 = "merge";
505 fp = fopen(git_path(commit_editmsg), "w");
506 if (fp == NULL)
507 die_errno("could not open '%s'", git_path(commit_editmsg));
509 if (cleanup_mode != CLEANUP_NONE)
510 stripspace(&sb, 0);
512 if (signoff) {
513 struct strbuf sob = STRBUF_INIT;
514 int i;
516 strbuf_addstr(&sob, sign_off_header);
517 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
518 getenv("GIT_COMMITTER_EMAIL")));
519 strbuf_addch(&sob, '\n');
520 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
521 ; /* do nothing */
522 if (prefixcmp(sb.buf + i, sob.buf)) {
523 if (prefixcmp(sb.buf + i, sign_off_header))
524 strbuf_addch(&sb, '\n');
525 strbuf_addbuf(&sb, &sob);
527 strbuf_release(&sob);
530 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
531 die_errno("could not write commit template");
533 strbuf_release(&sb);
535 determine_author_info();
537 /* This checks if committer ident is explicitly given */
538 git_committer_info(0);
539 if (use_editor) {
540 char *author_ident;
541 const char *committer_ident;
543 if (in_merge)
544 fprintf(fp,
545 "#\n"
546 "# It looks like you may be committing a MERGE.\n"
547 "# If this is not correct, please remove the file\n"
548 "# %s\n"
549 "# and try again.\n"
550 "#\n",
551 git_path("MERGE_HEAD"));
553 fprintf(fp,
554 "\n"
555 "# Please enter the commit message for your changes.");
556 if (cleanup_mode == CLEANUP_ALL)
557 fprintf(fp,
558 " Lines starting\n"
559 "# with '#' will be ignored, and an empty"
560 " message aborts the commit.\n");
561 else /* CLEANUP_SPACE, that is. */
562 fprintf(fp,
563 " Lines starting\n"
564 "# with '#' will be kept; you may remove them"
565 " yourself if you want to.\n"
566 "# An empty message aborts the commit.\n");
567 if (only_include_assumed)
568 fprintf(fp, "# %s\n", only_include_assumed);
570 author_ident = xstrdup(fmt_name(author_name, author_email));
571 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
572 getenv("GIT_COMMITTER_EMAIL"));
573 if (strcmp(author_ident, committer_ident))
574 fprintf(fp,
575 "%s"
576 "# Author: %s\n",
577 ident_shown++ ? "" : "#\n",
578 author_ident);
579 free(author_ident);
581 if (!user_ident_explicitly_given)
582 fprintf(fp,
583 "%s"
584 "# Committer: %s\n",
585 ident_shown++ ? "" : "#\n",
586 committer_ident);
588 if (ident_shown)
589 fprintf(fp, "#\n");
591 saved_color_setting = s->use_color;
592 s->use_color = 0;
593 commitable = run_status(fp, index_file, prefix, 1, s);
594 s->use_color = saved_color_setting;
595 } else {
596 unsigned char sha1[20];
597 const char *parent = "HEAD";
599 if (!active_nr && read_cache() < 0)
600 die("Cannot read index");
602 if (amend)
603 parent = "HEAD^1";
605 if (get_sha1(parent, sha1))
606 commitable = !!active_nr;
607 else
608 commitable = index_differs_from(parent, 0);
611 fclose(fp);
613 if (!commitable && !in_merge && !allow_empty &&
614 !(amend && is_a_merge(head_sha1))) {
615 run_status(stdout, index_file, prefix, 0, s);
616 return 0;
620 * Re-read the index as pre-commit hook could have updated it,
621 * and write it out as a tree. We must do this before we invoke
622 * the editor and after we invoke run_status above.
624 discard_cache();
625 read_cache_from(index_file);
626 if (!active_cache_tree)
627 active_cache_tree = cache_tree();
628 if (cache_tree_update(active_cache_tree,
629 active_cache, active_nr, 0, 0) < 0) {
630 error("Error building trees");
631 return 0;
634 if (run_hook(index_file, "prepare-commit-msg",
635 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
636 return 0;
638 if (use_editor) {
639 char index[PATH_MAX];
640 const char *env[2] = { index, NULL };
641 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
642 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
643 fprintf(stderr,
644 "Please supply the message using either -m or -F option.\n");
645 exit(1);
649 if (!no_verify &&
650 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
651 return 0;
654 return 1;
658 * Find out if the message in the strbuf contains only whitespace and
659 * Signed-off-by lines.
661 static int message_is_empty(struct strbuf *sb)
663 struct strbuf tmpl = STRBUF_INIT;
664 const char *nl;
665 int eol, i, start = 0;
667 if (cleanup_mode == CLEANUP_NONE && sb->len)
668 return 0;
670 /* See if the template is just a prefix of the message. */
671 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
672 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
673 if (start + tmpl.len <= sb->len &&
674 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
675 start += tmpl.len;
677 strbuf_release(&tmpl);
679 /* Check if the rest is just whitespace and Signed-of-by's. */
680 for (i = start; i < sb->len; i++) {
681 nl = memchr(sb->buf + i, '\n', sb->len - i);
682 if (nl)
683 eol = nl - sb->buf;
684 else
685 eol = sb->len;
687 if (strlen(sign_off_header) <= eol - i &&
688 !prefixcmp(sb->buf + i, sign_off_header)) {
689 i = eol;
690 continue;
692 while (i < eol)
693 if (!isspace(sb->buf[i++]))
694 return 0;
697 return 1;
700 static const char *find_author_by_nickname(const char *name)
702 struct rev_info revs;
703 struct commit *commit;
704 struct strbuf buf = STRBUF_INIT;
705 const char *av[20];
706 int ac = 0;
708 init_revisions(&revs, NULL);
709 strbuf_addf(&buf, "--author=%s", name);
710 av[++ac] = "--all";
711 av[++ac] = "-i";
712 av[++ac] = buf.buf;
713 av[++ac] = NULL;
714 setup_revisions(ac, av, &revs, NULL);
715 prepare_revision_walk(&revs);
716 commit = get_revision(&revs);
717 if (commit) {
718 strbuf_release(&buf);
719 format_commit_message(commit, "%an <%ae>", &buf, DATE_NORMAL);
720 return strbuf_detach(&buf, NULL);
722 die("No existing author found with '%s'", name);
726 static void handle_untracked_files_arg(struct wt_status *s)
728 if (!untracked_files_arg)
729 ; /* default already initialized */
730 else if (!strcmp(untracked_files_arg, "no"))
731 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
732 else if (!strcmp(untracked_files_arg, "normal"))
733 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
734 else if (!strcmp(untracked_files_arg, "all"))
735 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
736 else
737 die("Invalid untracked files mode '%s'", untracked_files_arg);
740 static int parse_and_validate_options(int argc, const char *argv[],
741 const char * const usage[],
742 const char *prefix,
743 struct wt_status *s)
745 int f = 0;
747 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
750 if (force_author && !strchr(force_author, '>'))
751 force_author = find_author_by_nickname(force_author);
753 if (logfile || message.len || use_message)
754 use_editor = 0;
755 if (edit_flag)
756 use_editor = 1;
757 if (!use_editor)
758 setenv("GIT_EDITOR", ":", 1);
760 if (get_sha1("HEAD", head_sha1))
761 initial_commit = 1;
763 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
764 in_merge = 1;
766 /* Sanity check options */
767 if (amend && initial_commit)
768 die("You have nothing to amend.");
769 if (amend && in_merge)
770 die("You are in the middle of a merge -- cannot amend.");
772 if (use_message)
773 f++;
774 if (edit_message)
775 f++;
776 if (logfile)
777 f++;
778 if (f > 1)
779 die("Only one of -c/-C/-F can be used.");
780 if (message.len && f > 0)
781 die("Option -m cannot be combined with -c/-C/-F.");
782 if (edit_message)
783 use_message = edit_message;
784 if (amend && !use_message)
785 use_message = "HEAD";
786 if (use_message) {
787 unsigned char sha1[20];
788 static char utf8[] = "UTF-8";
789 const char *out_enc;
790 char *enc, *end;
791 struct commit *commit;
793 if (get_sha1(use_message, sha1))
794 die("could not lookup commit %s", use_message);
795 commit = lookup_commit_reference(sha1);
796 if (!commit || parse_commit(commit))
797 die("could not parse commit %s", use_message);
799 enc = strstr(commit->buffer, "\nencoding");
800 if (enc) {
801 end = strchr(enc + 10, '\n');
802 enc = xstrndup(enc + 10, end - (enc + 10));
803 } else {
804 enc = utf8;
806 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
808 if (strcmp(out_enc, enc))
809 use_message_buffer =
810 reencode_string(commit->buffer, out_enc, enc);
813 * If we failed to reencode the buffer, just copy it
814 * byte for byte so the user can try to fix it up.
815 * This also handles the case where input and output
816 * encodings are identical.
818 if (use_message_buffer == NULL)
819 use_message_buffer = xstrdup(commit->buffer);
820 if (enc != utf8)
821 free(enc);
824 if (!!also + !!only + !!all + !!interactive > 1)
825 die("Only one of --include/--only/--all/--interactive can be used.");
826 if (argc == 0 && (also || (only && !amend)))
827 die("No paths with --include/--only does not make sense.");
828 if (argc == 0 && only && amend)
829 only_include_assumed = "Clever... amending the last one with dirty index.";
830 if (argc > 0 && !also && !only)
831 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
832 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
833 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
834 else if (!strcmp(cleanup_arg, "verbatim"))
835 cleanup_mode = CLEANUP_NONE;
836 else if (!strcmp(cleanup_arg, "whitespace"))
837 cleanup_mode = CLEANUP_SPACE;
838 else if (!strcmp(cleanup_arg, "strip"))
839 cleanup_mode = CLEANUP_ALL;
840 else
841 die("Invalid cleanup mode %s", cleanup_arg);
843 handle_untracked_files_arg(s);
845 if (all && argc > 0)
846 die("Paths with -a does not make sense.");
847 else if (interactive && argc > 0)
848 die("Paths with --interactive does not make sense.");
850 if (null_termination && status_format == STATUS_FORMAT_LONG)
851 status_format = STATUS_FORMAT_PORCELAIN;
852 if (status_format != STATUS_FORMAT_LONG)
853 dry_run = 1;
855 return argc;
858 static int dry_run_commit(int argc, const char **argv, const char *prefix,
859 struct wt_status *s)
861 int commitable;
862 const char *index_file;
864 index_file = prepare_index(argc, argv, prefix, 1);
865 commitable = run_status(stdout, index_file, prefix, 0, s);
866 rollback_index_files();
868 return commitable ? 0 : 1;
871 static int parse_status_slot(const char *var, int offset)
873 if (!strcasecmp(var+offset, "header"))
874 return WT_STATUS_HEADER;
875 if (!strcasecmp(var+offset, "updated")
876 || !strcasecmp(var+offset, "added"))
877 return WT_STATUS_UPDATED;
878 if (!strcasecmp(var+offset, "changed"))
879 return WT_STATUS_CHANGED;
880 if (!strcasecmp(var+offset, "untracked"))
881 return WT_STATUS_UNTRACKED;
882 if (!strcasecmp(var+offset, "nobranch"))
883 return WT_STATUS_NOBRANCH;
884 if (!strcasecmp(var+offset, "unmerged"))
885 return WT_STATUS_UNMERGED;
886 die("bad config variable '%s'", var);
889 static int git_status_config(const char *k, const char *v, void *cb)
891 struct wt_status *s = cb;
893 if (!strcmp(k, "status.submodulesummary")) {
894 int is_bool;
895 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
896 if (is_bool && s->submodule_summary)
897 s->submodule_summary = -1;
898 return 0;
900 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
901 s->use_color = git_config_colorbool(k, v, -1);
902 return 0;
904 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
905 int slot = parse_status_slot(k, 13);
906 if (!v)
907 return config_error_nonbool(k);
908 color_parse(v, k, s->color_palette[slot]);
909 return 0;
911 if (!strcmp(k, "status.relativepaths")) {
912 s->relative_paths = git_config_bool(k, v);
913 return 0;
915 if (!strcmp(k, "status.showuntrackedfiles")) {
916 if (!v)
917 return config_error_nonbool(k);
918 else if (!strcmp(v, "no"))
919 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
920 else if (!strcmp(v, "normal"))
921 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
922 else if (!strcmp(v, "all"))
923 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
924 else
925 return error("Invalid untracked files mode '%s'", v);
926 return 0;
928 return git_diff_ui_config(k, v, NULL);
931 #define quote_path quote_path_relative
933 static void short_unmerged(int null_termination, struct string_list_item *it,
934 struct wt_status *s)
936 struct wt_status_change_data *d = it->util;
937 const char *how = "??";
939 switch (d->stagemask) {
940 case 1: how = "DD"; break; /* both deleted */
941 case 2: how = "AU"; break; /* added by us */
942 case 3: how = "UD"; break; /* deleted by them */
943 case 4: how = "UA"; break; /* added by them */
944 case 5: how = "DU"; break; /* deleted by us */
945 case 6: how = "AA"; break; /* both added */
946 case 7: how = "UU"; break; /* both modified */
948 printf("%s ", how);
949 if (null_termination) {
950 fprintf(stdout, "%s%c", it->string, 0);
951 } else {
952 struct strbuf onebuf = STRBUF_INIT;
953 const char *one;
954 one = quote_path(it->string, -1, &onebuf, s->prefix);
955 printf("%s\n", one);
956 strbuf_release(&onebuf);
960 static void short_status(int null_termination, struct string_list_item *it,
961 struct wt_status *s)
963 struct wt_status_change_data *d = it->util;
965 printf("%c%c ",
966 !d->index_status ? ' ' : d->index_status,
967 !d->worktree_status ? ' ' : d->worktree_status);
968 if (null_termination) {
969 fprintf(stdout, "%s%c", it->string, 0);
970 if (d->head_path)
971 fprintf(stdout, "%s%c", d->head_path, 0);
972 } else {
973 struct strbuf onebuf = STRBUF_INIT;
974 const char *one;
975 if (d->head_path) {
976 one = quote_path(d->head_path, -1, &onebuf, s->prefix);
977 printf("%s -> ", one);
978 strbuf_release(&onebuf);
980 one = quote_path(it->string, -1, &onebuf, s->prefix);
981 printf("%s\n", one);
982 strbuf_release(&onebuf);
986 static void short_untracked(int null_termination, struct string_list_item *it,
987 struct wt_status *s)
989 if (null_termination) {
990 fprintf(stdout, "?? %s%c", it->string, 0);
991 } else {
992 struct strbuf onebuf = STRBUF_INIT;
993 const char *one;
994 one = quote_path(it->string, -1, &onebuf, s->prefix);
995 printf("?? %s\n", one);
996 strbuf_release(&onebuf);
1000 static void short_print(struct wt_status *s, int null_termination)
1002 int i;
1003 for (i = 0; i < s->change.nr; i++) {
1004 struct wt_status_change_data *d;
1005 struct string_list_item *it;
1007 it = &(s->change.items[i]);
1008 d = it->util;
1009 if (d->stagemask)
1010 short_unmerged(null_termination, it, s);
1011 else
1012 short_status(null_termination, it, s);
1014 for (i = 0; i < s->untracked.nr; i++) {
1015 struct string_list_item *it;
1017 it = &(s->untracked.items[i]);
1018 short_untracked(null_termination, it, s);
1022 int cmd_status(int argc, const char **argv, const char *prefix)
1024 struct wt_status s;
1025 unsigned char sha1[20];
1026 static struct option builtin_status_options[] = {
1027 OPT__VERBOSE(&verbose),
1028 OPT_SET_INT('s', "short", &status_format,
1029 "show status concisely", STATUS_FORMAT_SHORT),
1030 OPT_SET_INT(0, "porcelain", &status_format,
1031 "show porcelain output format",
1032 STATUS_FORMAT_PORCELAIN),
1033 OPT_BOOLEAN('z', "null", &null_termination,
1034 "terminate entries with NUL"),
1035 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1036 "mode",
1037 "show untracked files, optional modes: all, normal, no. (Default: all)",
1038 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1039 OPT_END(),
1042 if (null_termination && status_format == STATUS_FORMAT_LONG)
1043 status_format = STATUS_FORMAT_PORCELAIN;
1045 wt_status_prepare(&s);
1046 git_config(git_status_config, &s);
1047 argc = parse_options(argc, argv, prefix,
1048 builtin_status_options,
1049 builtin_status_usage, 0);
1050 handle_untracked_files_arg(&s);
1052 if (*argv)
1053 s.pathspec = get_pathspec(prefix, argv);
1055 read_cache();
1056 refresh_cache(REFRESH_QUIET|REFRESH_UNMERGED);
1057 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1058 wt_status_collect(&s);
1060 switch (status_format) {
1061 case STATUS_FORMAT_SHORT:
1062 short_print(&s, null_termination);
1063 break;
1064 case STATUS_FORMAT_PORCELAIN:
1065 short_print(&s, null_termination);
1066 break;
1067 case STATUS_FORMAT_LONG:
1068 s.verbose = verbose;
1069 if (s.relative_paths)
1070 s.prefix = prefix;
1071 if (s.use_color == -1)
1072 s.use_color = git_use_color_default;
1073 if (diff_use_color_default == -1)
1074 diff_use_color_default = git_use_color_default;
1075 wt_status_print(&s);
1076 break;
1078 return 0;
1081 static void print_summary(const char *prefix, const unsigned char *sha1)
1083 struct rev_info rev;
1084 struct commit *commit;
1085 static const char *format = "format:%h] %s";
1086 unsigned char junk_sha1[20];
1087 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1089 commit = lookup_commit(sha1);
1090 if (!commit)
1091 die("couldn't look up newly created commit");
1092 if (!commit || parse_commit(commit))
1093 die("could not parse newly created commit");
1095 init_revisions(&rev, prefix);
1096 setup_revisions(0, NULL, &rev, NULL);
1098 rev.abbrev = 0;
1099 rev.diff = 1;
1100 rev.diffopt.output_format =
1101 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1103 rev.verbose_header = 1;
1104 rev.show_root_diff = 1;
1105 get_commit_format(format, &rev);
1106 rev.always_show_header = 0;
1107 rev.diffopt.detect_rename = 1;
1108 rev.diffopt.rename_limit = 100;
1109 rev.diffopt.break_opt = 0;
1110 diff_setup_done(&rev.diffopt);
1112 printf("[%s%s ",
1113 !prefixcmp(head, "refs/heads/") ?
1114 head + 11 :
1115 !strcmp(head, "HEAD") ?
1116 "detached HEAD" :
1117 head,
1118 initial_commit ? " (root-commit)" : "");
1120 if (!log_tree_commit(&rev, commit)) {
1121 struct strbuf buf = STRBUF_INIT;
1122 format_commit_message(commit, format + 7, &buf, DATE_NORMAL);
1123 printf("%s\n", buf.buf);
1124 strbuf_release(&buf);
1128 static int git_commit_config(const char *k, const char *v, void *cb)
1130 struct wt_status *s = cb;
1132 if (!strcmp(k, "commit.template"))
1133 return git_config_string(&template_file, k, v);
1135 return git_status_config(k, v, s);
1138 int cmd_commit(int argc, const char **argv, const char *prefix)
1140 struct strbuf sb = STRBUF_INIT;
1141 const char *index_file, *reflog_msg;
1142 char *nl, *p;
1143 unsigned char commit_sha1[20];
1144 struct ref_lock *ref_lock;
1145 struct commit_list *parents = NULL, **pptr = &parents;
1146 struct stat statbuf;
1147 int allow_fast_forward = 1;
1148 struct wt_status s;
1150 wt_status_prepare(&s);
1151 git_config(git_commit_config, &s);
1153 if (s.use_color == -1)
1154 s.use_color = git_use_color_default;
1156 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1157 prefix, &s);
1158 if (dry_run) {
1159 if (diff_use_color_default == -1)
1160 diff_use_color_default = git_use_color_default;
1161 return dry_run_commit(argc, argv, prefix, &s);
1163 index_file = prepare_index(argc, argv, prefix, 0);
1165 /* Set up everything for writing the commit object. This includes
1166 running hooks, writing the trees, and interacting with the user. */
1167 if (!prepare_to_commit(index_file, prefix, &s)) {
1168 rollback_index_files();
1169 return 1;
1172 /* Determine parents */
1173 if (initial_commit) {
1174 reflog_msg = "commit (initial)";
1175 } else if (amend) {
1176 struct commit_list *c;
1177 struct commit *commit;
1179 reflog_msg = "commit (amend)";
1180 commit = lookup_commit(head_sha1);
1181 if (!commit || parse_commit(commit))
1182 die("could not parse HEAD commit");
1184 for (c = commit->parents; c; c = c->next)
1185 pptr = &commit_list_insert(c->item, pptr)->next;
1186 } else if (in_merge) {
1187 struct strbuf m = STRBUF_INIT;
1188 FILE *fp;
1190 reflog_msg = "commit (merge)";
1191 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1192 fp = fopen(git_path("MERGE_HEAD"), "r");
1193 if (fp == NULL)
1194 die_errno("could not open '%s' for reading",
1195 git_path("MERGE_HEAD"));
1196 while (strbuf_getline(&m, fp, '\n') != EOF) {
1197 unsigned char sha1[20];
1198 if (get_sha1_hex(m.buf, sha1) < 0)
1199 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1200 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1202 fclose(fp);
1203 strbuf_release(&m);
1204 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1205 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1206 die_errno("could not read MERGE_MODE");
1207 if (!strcmp(sb.buf, "no-ff"))
1208 allow_fast_forward = 0;
1210 if (allow_fast_forward)
1211 parents = reduce_heads(parents);
1212 } else {
1213 reflog_msg = "commit";
1214 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1217 /* Finally, get the commit message */
1218 strbuf_reset(&sb);
1219 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1220 int saved_errno = errno;
1221 rollback_index_files();
1222 die("could not read commit message: %s", strerror(saved_errno));
1225 /* Truncate the message just before the diff, if any. */
1226 if (verbose) {
1227 p = strstr(sb.buf, "\ndiff --git ");
1228 if (p != NULL)
1229 strbuf_setlen(&sb, p - sb.buf + 1);
1232 if (cleanup_mode != CLEANUP_NONE)
1233 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1234 if (message_is_empty(&sb)) {
1235 rollback_index_files();
1236 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1237 exit(1);
1240 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1241 fmt_ident(author_name, author_email, author_date,
1242 IDENT_ERROR_ON_NO_NAME))) {
1243 rollback_index_files();
1244 die("failed to write commit object");
1247 ref_lock = lock_any_ref_for_update("HEAD",
1248 initial_commit ? NULL : head_sha1,
1251 nl = strchr(sb.buf, '\n');
1252 if (nl)
1253 strbuf_setlen(&sb, nl + 1 - sb.buf);
1254 else
1255 strbuf_addch(&sb, '\n');
1256 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1257 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1259 if (!ref_lock) {
1260 rollback_index_files();
1261 die("cannot lock HEAD ref");
1263 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1264 rollback_index_files();
1265 die("cannot update HEAD ref");
1268 unlink(git_path("MERGE_HEAD"));
1269 unlink(git_path("MERGE_MSG"));
1270 unlink(git_path("MERGE_MODE"));
1271 unlink(git_path("SQUASH_MSG"));
1273 if (commit_index_files())
1274 die ("Repository has been updated, but unable to write\n"
1275 "new_index file. Check that disk is not full or quota is\n"
1276 "not exceeded, and then \"git reset HEAD\" to recover.");
1278 rerere();
1279 run_hook(get_index_file(), "post-commit", NULL);
1280 if (!quiet)
1281 print_summary(prefix, commit_sha1);
1283 return 0;