branch: warn and refuse to set a branch as a tracking branch of itself.
[git/dscho.git] / builtin-commit.c
blobe64487121059b1b4a618828095375c1a42e4e93e
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];
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, renew_authorship;
56 static char *untracked_files_arg, *force_date;
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, include_status = 1;
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),
98 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_STRING(0, "date", &force_date, "DATE", "override date for commit"),
102 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
103 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
104 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
105 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
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"),
109 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
110 OPT_BOOLEAN(0, "status", &include_status, "include status in commit message template"),
111 /* end commit message options */
113 OPT_GROUP("Commit contents options"),
114 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
115 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
116 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
117 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
118 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
119 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
120 OPT_SET_INT(0, "short", &status_format, "show status concisely",
121 STATUS_FORMAT_SHORT),
122 OPT_SET_INT(0, "porcelain", &status_format,
123 "show porcelain output format", STATUS_FORMAT_PORCELAIN),
124 OPT_BOOLEAN('z', "null", &null_termination,
125 "terminate entries with NUL"),
126 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
127 { 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" },
128 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
129 /* end commit contents options */
131 OPT_END()
134 static void rollback_index_files(void)
136 switch (commit_style) {
137 case COMMIT_AS_IS:
138 break; /* nothing to do */
139 case COMMIT_NORMAL:
140 rollback_lock_file(&index_lock);
141 break;
142 case COMMIT_PARTIAL:
143 rollback_lock_file(&index_lock);
144 rollback_lock_file(&false_lock);
145 break;
149 static int commit_index_files(void)
151 int err = 0;
153 switch (commit_style) {
154 case COMMIT_AS_IS:
155 break; /* nothing to do */
156 case COMMIT_NORMAL:
157 err = commit_lock_file(&index_lock);
158 break;
159 case COMMIT_PARTIAL:
160 err = commit_lock_file(&index_lock);
161 rollback_lock_file(&false_lock);
162 break;
165 return err;
169 * Take a union of paths in the index and the named tree (typically, "HEAD"),
170 * and return the paths that match the given pattern in list.
172 static int list_paths(struct string_list *list, const char *with_tree,
173 const char *prefix, const char **pattern)
175 int i;
176 char *m;
178 for (i = 0; pattern[i]; i++)
180 m = xcalloc(1, i);
182 if (with_tree)
183 overlay_tree_on_cache(with_tree, prefix);
185 for (i = 0; i < active_nr; i++) {
186 struct cache_entry *ce = active_cache[i];
187 struct string_list_item *item;
189 if (ce->ce_flags & CE_UPDATE)
190 continue;
191 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
192 continue;
193 item = string_list_insert(ce->name, list);
194 if (ce_skip_worktree(ce))
195 item->util = item; /* better a valid pointer than a fake one */
198 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
201 static void add_remove_files(struct string_list *list)
203 int i;
204 for (i = 0; i < list->nr; i++) {
205 struct stat st;
206 struct string_list_item *p = &(list->items[i]);
208 /* p->util is skip-worktree */
209 if (p->util)
210 continue;
212 if (!lstat(p->string, &st)) {
213 if (add_to_cache(p->string, &st, 0))
214 die("updating files failed");
215 } else
216 remove_file_from_cache(p->string);
220 static void create_base_index(void)
222 struct tree *tree;
223 struct unpack_trees_options opts;
224 struct tree_desc t;
226 if (initial_commit) {
227 discard_cache();
228 return;
231 memset(&opts, 0, sizeof(opts));
232 opts.head_idx = 1;
233 opts.index_only = 1;
234 opts.merge = 1;
235 opts.src_index = &the_index;
236 opts.dst_index = &the_index;
238 opts.fn = oneway_merge;
239 tree = parse_tree_indirect(head_sha1);
240 if (!tree)
241 die("failed to unpack HEAD tree object");
242 parse_tree(tree);
243 init_tree_desc(&t, tree->buffer, tree->size);
244 if (unpack_trees(1, &t, &opts))
245 exit(128); /* We've already reported the error, finish dying */
248 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
250 int fd;
251 struct string_list partial;
252 const char **pathspec = NULL;
253 int refresh_flags = REFRESH_QUIET;
255 if (is_status)
256 refresh_flags |= REFRESH_UNMERGED;
257 if (interactive) {
258 if (interactive_add(argc, argv, prefix) != 0)
259 die("interactive add failed");
260 if (read_cache_preload(NULL) < 0)
261 die("index file corrupt");
262 commit_style = COMMIT_AS_IS;
263 return get_index_file();
266 if (*argv)
267 pathspec = get_pathspec(prefix, argv);
269 if (read_cache_preload(pathspec) < 0)
270 die("index file corrupt");
273 * Non partial, non as-is commit.
275 * (1) get the real index;
276 * (2) update the_index as necessary;
277 * (3) write the_index out to the real index (still locked);
278 * (4) return the name of the locked index file.
280 * The caller should run hooks on the locked real index, and
281 * (A) if all goes well, commit the real index;
282 * (B) on failure, rollback the real index.
284 if (all || (also && pathspec && *pathspec)) {
285 int fd = hold_locked_index(&index_lock, 1);
286 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
287 refresh_cache(refresh_flags);
288 if (write_cache(fd, active_cache, active_nr) ||
289 close_lock_file(&index_lock))
290 die("unable to write new_index file");
291 commit_style = COMMIT_NORMAL;
292 return index_lock.filename;
296 * As-is commit.
298 * (1) return the name of the real index file.
300 * The caller should run hooks on the real index, and run
301 * hooks on the real index, and create commit from the_index.
302 * We still need to refresh the index here.
304 if (!pathspec || !*pathspec) {
305 fd = hold_locked_index(&index_lock, 1);
306 refresh_cache(refresh_flags);
307 if (write_cache(fd, active_cache, active_nr) ||
308 commit_locked_index(&index_lock))
309 die("unable to write new_index file");
310 commit_style = COMMIT_AS_IS;
311 return get_index_file();
315 * A partial commit.
317 * (0) find the set of affected paths;
318 * (1) get lock on the real index file;
319 * (2) update the_index with the given paths;
320 * (3) write the_index out to the real index (still locked);
321 * (4) get lock on the false index file;
322 * (5) reset the_index from HEAD;
323 * (6) update the_index the same way as (2);
324 * (7) write the_index out to the false index file;
325 * (8) return the name of the false index file (still locked);
327 * The caller should run hooks on the locked false index, and
328 * create commit from it. Then
329 * (A) if all goes well, commit the real index;
330 * (B) on failure, rollback the real index;
331 * In either case, rollback the false index.
333 commit_style = COMMIT_PARTIAL;
335 if (in_merge)
336 die("cannot do a partial commit during a merge.");
338 memset(&partial, 0, sizeof(partial));
339 partial.strdup_strings = 1;
340 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
341 exit(1);
343 discard_cache();
344 if (read_cache() < 0)
345 die("cannot read the index");
347 fd = hold_locked_index(&index_lock, 1);
348 add_remove_files(&partial);
349 refresh_cache(REFRESH_QUIET);
350 if (write_cache(fd, active_cache, active_nr) ||
351 close_lock_file(&index_lock))
352 die("unable to write new_index file");
354 fd = hold_lock_file_for_update(&false_lock,
355 git_path("next-index-%"PRIuMAX,
356 (uintmax_t) getpid()),
357 LOCK_DIE_ON_ERROR);
359 create_base_index();
360 add_remove_files(&partial);
361 refresh_cache(REFRESH_QUIET);
363 if (write_cache(fd, active_cache, active_nr) ||
364 close_lock_file(&false_lock))
365 die("unable to write temporary index file");
367 discard_cache();
368 read_cache_from(false_lock.filename);
370 return false_lock.filename;
373 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
374 struct wt_status *s)
376 unsigned char sha1[20];
378 if (s->relative_paths)
379 s->prefix = prefix;
381 if (amend) {
382 s->amend = 1;
383 s->reference = "HEAD^1";
385 s->verbose = verbose;
386 s->index_file = index_file;
387 s->fp = fp;
388 s->nowarn = nowarn;
389 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
391 wt_status_collect(s);
393 switch (status_format) {
394 case STATUS_FORMAT_SHORT:
395 wt_shortstatus_print(s, null_termination);
396 break;
397 case STATUS_FORMAT_PORCELAIN:
398 wt_porcelain_print(s, null_termination);
399 break;
400 case STATUS_FORMAT_LONG:
401 wt_status_print(s);
402 break;
405 return s->commitable;
408 static int is_a_merge(const unsigned char *sha1)
410 struct commit *commit = lookup_commit(sha1);
411 if (!commit || parse_commit(commit))
412 die("could not parse HEAD commit");
413 return !!(commit->parents && commit->parents->next);
416 static const char sign_off_header[] = "Signed-off-by: ";
418 static void determine_author_info(void)
420 char *name, *email, *date;
422 name = getenv("GIT_AUTHOR_NAME");
423 email = getenv("GIT_AUTHOR_EMAIL");
424 date = getenv("GIT_AUTHOR_DATE");
426 if (use_message && !renew_authorship) {
427 const char *a, *lb, *rb, *eol;
429 a = strstr(use_message_buffer, "\nauthor ");
430 if (!a)
431 die("invalid commit: %s", use_message);
433 lb = strstr(a + 8, " <");
434 rb = strstr(a + 8, "> ");
435 eol = strchr(a + 8, '\n');
436 if (!lb || !rb || !eol)
437 die("invalid commit: %s", use_message);
439 name = xstrndup(a + 8, lb - (a + 8));
440 email = xstrndup(lb + 2, rb - (lb + 2));
441 date = xstrndup(rb + 2, eol - (rb + 2));
444 if (force_author) {
445 const char *lb = strstr(force_author, " <");
446 const char *rb = strchr(force_author, '>');
448 if (!lb || !rb)
449 die("malformed --author parameter");
450 name = xstrndup(force_author, lb - force_author);
451 email = xstrndup(lb + 2, rb - (lb + 2));
454 if (force_date)
455 date = force_date;
457 author_name = name;
458 author_email = email;
459 author_date = date;
462 static int ends_rfc2822_footer(struct strbuf *sb)
464 int ch;
465 int hit = 0;
466 int i, j, k;
467 int len = sb->len;
468 int first = 1;
469 const char *buf = sb->buf;
471 for (i = len - 1; i > 0; i--) {
472 if (hit && buf[i] == '\n')
473 break;
474 hit = (buf[i] == '\n');
477 while (i < len - 1 && buf[i] == '\n')
478 i++;
480 for (; i < len; i = k) {
481 for (k = i; k < len && buf[k] != '\n'; k++)
482 ; /* do nothing */
483 k++;
485 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
486 continue;
488 first = 0;
490 for (j = 0; i + j < len; j++) {
491 ch = buf[i + j];
492 if (ch == ':')
493 break;
494 if (isalnum(ch) ||
495 (ch == '-'))
496 continue;
497 return 0;
500 return 1;
503 static int prepare_to_commit(const char *index_file, const char *prefix,
504 struct wt_status *s)
506 struct stat statbuf;
507 int commitable, saved_color_setting;
508 struct strbuf sb = STRBUF_INIT;
509 char *buffer;
510 FILE *fp;
511 const char *hook_arg1 = NULL;
512 const char *hook_arg2 = NULL;
513 int ident_shown = 0;
515 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
516 return 0;
518 if (message.len) {
519 strbuf_addbuf(&sb, &message);
520 hook_arg1 = "message";
521 } else if (logfile && !strcmp(logfile, "-")) {
522 if (isatty(0))
523 fprintf(stderr, "(reading log message from standard input)\n");
524 if (strbuf_read(&sb, 0, 0) < 0)
525 die_errno("could not read log from standard input");
526 hook_arg1 = "message";
527 } else if (logfile) {
528 if (strbuf_read_file(&sb, logfile, 0) < 0)
529 die_errno("could not read log file '%s'",
530 logfile);
531 hook_arg1 = "message";
532 } else if (use_message) {
533 buffer = strstr(use_message_buffer, "\n\n");
534 if (!buffer || buffer[2] == '\0')
535 die("commit has empty message");
536 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
537 hook_arg1 = "commit";
538 hook_arg2 = use_message;
539 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
540 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
541 die_errno("could not read MERGE_MSG");
542 hook_arg1 = "merge";
543 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
544 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
545 die_errno("could not read SQUASH_MSG");
546 hook_arg1 = "squash";
547 } else if (template_file && !stat(template_file, &statbuf)) {
548 if (strbuf_read_file(&sb, template_file, 0) < 0)
549 die_errno("could not read '%s'", template_file);
550 hook_arg1 = "template";
554 * This final case does not modify the template message,
555 * it just sets the argument to the prepare-commit-msg hook.
557 else if (in_merge)
558 hook_arg1 = "merge";
560 fp = fopen(git_path(commit_editmsg), "w");
561 if (fp == NULL)
562 die_errno("could not open '%s'", git_path(commit_editmsg));
564 if (cleanup_mode != CLEANUP_NONE)
565 stripspace(&sb, 0);
567 if (signoff) {
568 struct strbuf sob = STRBUF_INIT;
569 int i;
571 strbuf_addstr(&sob, sign_off_header);
572 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
573 getenv("GIT_COMMITTER_EMAIL")));
574 strbuf_addch(&sob, '\n');
575 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
576 ; /* do nothing */
577 if (prefixcmp(sb.buf + i, sob.buf)) {
578 if (!i || !ends_rfc2822_footer(&sb))
579 strbuf_addch(&sb, '\n');
580 strbuf_addbuf(&sb, &sob);
582 strbuf_release(&sob);
585 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
586 die_errno("could not write commit template");
588 strbuf_release(&sb);
590 determine_author_info();
592 /* This checks if committer ident is explicitly given */
593 git_committer_info(0);
594 if (use_editor && include_status) {
595 char *author_ident;
596 const char *committer_ident;
598 if (in_merge)
599 fprintf(fp,
600 "#\n"
601 "# It looks like you may be committing a MERGE.\n"
602 "# If this is not correct, please remove the file\n"
603 "# %s\n"
604 "# and try again.\n"
605 "#\n",
606 git_path("MERGE_HEAD"));
608 fprintf(fp,
609 "\n"
610 "# Please enter the commit message for your changes.");
611 if (cleanup_mode == CLEANUP_ALL)
612 fprintf(fp,
613 " Lines starting\n"
614 "# with '#' will be ignored, and an empty"
615 " message aborts the commit.\n");
616 else /* CLEANUP_SPACE, that is. */
617 fprintf(fp,
618 " Lines starting\n"
619 "# with '#' will be kept; you may remove them"
620 " yourself if you want to.\n"
621 "# An empty message aborts the commit.\n");
622 if (only_include_assumed)
623 fprintf(fp, "# %s\n", only_include_assumed);
625 author_ident = xstrdup(fmt_name(author_name, author_email));
626 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
627 getenv("GIT_COMMITTER_EMAIL"));
628 if (strcmp(author_ident, committer_ident))
629 fprintf(fp,
630 "%s"
631 "# Author: %s\n",
632 ident_shown++ ? "" : "#\n",
633 author_ident);
634 free(author_ident);
636 if (!user_ident_explicitly_given)
637 fprintf(fp,
638 "%s"
639 "# Committer: %s\n",
640 ident_shown++ ? "" : "#\n",
641 committer_ident);
643 if (ident_shown)
644 fprintf(fp, "#\n");
646 saved_color_setting = s->use_color;
647 s->use_color = 0;
648 commitable = run_status(fp, index_file, prefix, 1, s);
649 s->use_color = saved_color_setting;
650 } else {
651 unsigned char sha1[20];
652 const char *parent = "HEAD";
654 if (!active_nr && read_cache() < 0)
655 die("Cannot read index");
657 if (amend)
658 parent = "HEAD^1";
660 if (get_sha1(parent, sha1))
661 commitable = !!active_nr;
662 else
663 commitable = index_differs_from(parent, 0);
666 fclose(fp);
668 if (!commitable && !in_merge && !allow_empty &&
669 !(amend && is_a_merge(head_sha1))) {
670 run_status(stdout, index_file, prefix, 0, s);
671 return 0;
675 * Re-read the index as pre-commit hook could have updated it,
676 * and write it out as a tree. We must do this before we invoke
677 * the editor and after we invoke run_status above.
679 discard_cache();
680 read_cache_from(index_file);
681 if (!active_cache_tree)
682 active_cache_tree = cache_tree();
683 if (cache_tree_update(active_cache_tree,
684 active_cache, active_nr, 0, 0) < 0) {
685 error("Error building trees");
686 return 0;
689 if (run_hook(index_file, "prepare-commit-msg",
690 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
691 return 0;
693 if (use_editor) {
694 char index[PATH_MAX];
695 const char *env[2] = { index, NULL };
696 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
697 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
698 fprintf(stderr,
699 "Please supply the message using either -m or -F option.\n");
700 exit(1);
704 if (!no_verify &&
705 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
706 return 0;
709 return 1;
713 * Find out if the message in the strbuf contains only whitespace and
714 * Signed-off-by lines.
716 static int message_is_empty(struct strbuf *sb)
718 struct strbuf tmpl = STRBUF_INIT;
719 const char *nl;
720 int eol, i, start = 0;
722 if (cleanup_mode == CLEANUP_NONE && sb->len)
723 return 0;
725 /* See if the template is just a prefix of the message. */
726 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
727 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
728 if (start + tmpl.len <= sb->len &&
729 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
730 start += tmpl.len;
732 strbuf_release(&tmpl);
734 /* Check if the rest is just whitespace and Signed-of-by's. */
735 for (i = start; i < sb->len; i++) {
736 nl = memchr(sb->buf + i, '\n', sb->len - i);
737 if (nl)
738 eol = nl - sb->buf;
739 else
740 eol = sb->len;
742 if (strlen(sign_off_header) <= eol - i &&
743 !prefixcmp(sb->buf + i, sign_off_header)) {
744 i = eol;
745 continue;
747 while (i < eol)
748 if (!isspace(sb->buf[i++]))
749 return 0;
752 return 1;
755 static const char *find_author_by_nickname(const char *name)
757 struct rev_info revs;
758 struct commit *commit;
759 struct strbuf buf = STRBUF_INIT;
760 const char *av[20];
761 int ac = 0;
763 init_revisions(&revs, NULL);
764 strbuf_addf(&buf, "--author=%s", name);
765 av[++ac] = "--all";
766 av[++ac] = "-i";
767 av[++ac] = buf.buf;
768 av[++ac] = NULL;
769 setup_revisions(ac, av, &revs, NULL);
770 prepare_revision_walk(&revs);
771 commit = get_revision(&revs);
772 if (commit) {
773 struct pretty_print_context ctx = {0};
774 ctx.date_mode = DATE_NORMAL;
775 strbuf_release(&buf);
776 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
777 return strbuf_detach(&buf, NULL);
779 die("No existing author found with '%s'", name);
783 static void handle_untracked_files_arg(struct wt_status *s)
785 if (!untracked_files_arg)
786 ; /* default already initialized */
787 else if (!strcmp(untracked_files_arg, "no"))
788 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
789 else if (!strcmp(untracked_files_arg, "normal"))
790 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
791 else if (!strcmp(untracked_files_arg, "all"))
792 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
793 else
794 die("Invalid untracked files mode '%s'", untracked_files_arg);
797 static int parse_and_validate_options(int argc, const char *argv[],
798 const char * const usage[],
799 const char *prefix,
800 struct wt_status *s)
802 int f = 0;
804 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
807 if (force_author && !strchr(force_author, '>'))
808 force_author = find_author_by_nickname(force_author);
810 if (force_author && renew_authorship)
811 die("Using both --reset-author and --author does not make sense");
813 if (logfile || message.len || use_message)
814 use_editor = 0;
815 if (edit_flag)
816 use_editor = 1;
817 if (!use_editor)
818 setenv("GIT_EDITOR", ":", 1);
820 if (get_sha1("HEAD", head_sha1))
821 initial_commit = 1;
823 /* Sanity check options */
824 if (amend && initial_commit)
825 die("You have nothing to amend.");
826 if (amend && in_merge)
827 die("You are in the middle of a merge -- cannot amend.");
829 if (use_message)
830 f++;
831 if (edit_message)
832 f++;
833 if (logfile)
834 f++;
835 if (f > 1)
836 die("Only one of -c/-C/-F can be used.");
837 if (message.len && f > 0)
838 die("Option -m cannot be combined with -c/-C/-F.");
839 if (edit_message)
840 use_message = edit_message;
841 if (amend && !use_message)
842 use_message = "HEAD";
843 if (!use_message && renew_authorship)
844 die("--reset-author can be used only with -C, -c or --amend.");
845 if (use_message) {
846 unsigned char sha1[20];
847 static char utf8[] = "UTF-8";
848 const char *out_enc;
849 char *enc, *end;
850 struct commit *commit;
852 if (get_sha1(use_message, sha1))
853 die("could not lookup commit %s", use_message);
854 commit = lookup_commit_reference(sha1);
855 if (!commit || parse_commit(commit))
856 die("could not parse commit %s", use_message);
858 enc = strstr(commit->buffer, "\nencoding");
859 if (enc) {
860 end = strchr(enc + 10, '\n');
861 enc = xstrndup(enc + 10, end - (enc + 10));
862 } else {
863 enc = utf8;
865 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
867 if (strcmp(out_enc, enc))
868 use_message_buffer =
869 reencode_string(commit->buffer, out_enc, enc);
872 * If we failed to reencode the buffer, just copy it
873 * byte for byte so the user can try to fix it up.
874 * This also handles the case where input and output
875 * encodings are identical.
877 if (use_message_buffer == NULL)
878 use_message_buffer = xstrdup(commit->buffer);
879 if (enc != utf8)
880 free(enc);
883 if (!!also + !!only + !!all + !!interactive > 1)
884 die("Only one of --include/--only/--all/--interactive can be used.");
885 if (argc == 0 && (also || (only && !amend)))
886 die("No paths with --include/--only does not make sense.");
887 if (argc == 0 && only && amend)
888 only_include_assumed = "Clever... amending the last one with dirty index.";
889 if (argc > 0 && !also && !only)
890 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
891 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
892 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
893 else if (!strcmp(cleanup_arg, "verbatim"))
894 cleanup_mode = CLEANUP_NONE;
895 else if (!strcmp(cleanup_arg, "whitespace"))
896 cleanup_mode = CLEANUP_SPACE;
897 else if (!strcmp(cleanup_arg, "strip"))
898 cleanup_mode = CLEANUP_ALL;
899 else
900 die("Invalid cleanup mode %s", cleanup_arg);
902 handle_untracked_files_arg(s);
904 if (all && argc > 0)
905 die("Paths with -a does not make sense.");
906 else if (interactive && argc > 0)
907 die("Paths with --interactive does not make sense.");
909 if (null_termination && status_format == STATUS_FORMAT_LONG)
910 status_format = STATUS_FORMAT_PORCELAIN;
911 if (status_format != STATUS_FORMAT_LONG)
912 dry_run = 1;
914 return argc;
917 static int dry_run_commit(int argc, const char **argv, const char *prefix,
918 struct wt_status *s)
920 int commitable;
921 const char *index_file;
923 index_file = prepare_index(argc, argv, prefix, 1);
924 commitable = run_status(stdout, index_file, prefix, 0, s);
925 rollback_index_files();
927 return commitable ? 0 : 1;
930 static int parse_status_slot(const char *var, int offset)
932 if (!strcasecmp(var+offset, "header"))
933 return WT_STATUS_HEADER;
934 if (!strcasecmp(var+offset, "updated")
935 || !strcasecmp(var+offset, "added"))
936 return WT_STATUS_UPDATED;
937 if (!strcasecmp(var+offset, "changed"))
938 return WT_STATUS_CHANGED;
939 if (!strcasecmp(var+offset, "untracked"))
940 return WT_STATUS_UNTRACKED;
941 if (!strcasecmp(var+offset, "nobranch"))
942 return WT_STATUS_NOBRANCH;
943 if (!strcasecmp(var+offset, "unmerged"))
944 return WT_STATUS_UNMERGED;
945 return -1;
948 static int git_status_config(const char *k, const char *v, void *cb)
950 struct wt_status *s = cb;
952 if (!strcmp(k, "status.submodulesummary")) {
953 int is_bool;
954 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
955 if (is_bool && s->submodule_summary)
956 s->submodule_summary = -1;
957 return 0;
959 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
960 s->use_color = git_config_colorbool(k, v, -1);
961 return 0;
963 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
964 int slot = parse_status_slot(k, 13);
965 if (slot < 0)
966 return 0;
967 if (!v)
968 return config_error_nonbool(k);
969 color_parse(v, k, s->color_palette[slot]);
970 return 0;
972 if (!strcmp(k, "status.relativepaths")) {
973 s->relative_paths = git_config_bool(k, v);
974 return 0;
976 if (!strcmp(k, "status.showuntrackedfiles")) {
977 if (!v)
978 return config_error_nonbool(k);
979 else if (!strcmp(v, "no"))
980 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
981 else if (!strcmp(v, "normal"))
982 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
983 else if (!strcmp(v, "all"))
984 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
985 else
986 return error("Invalid untracked files mode '%s'", v);
987 return 0;
989 return git_diff_ui_config(k, v, NULL);
992 int cmd_status(int argc, const char **argv, const char *prefix)
994 struct wt_status s;
995 unsigned char sha1[20];
996 static struct option builtin_status_options[] = {
997 OPT__VERBOSE(&verbose),
998 OPT_SET_INT('s', "short", &status_format,
999 "show status concisely", STATUS_FORMAT_SHORT),
1000 OPT_SET_INT(0, "porcelain", &status_format,
1001 "show porcelain output format",
1002 STATUS_FORMAT_PORCELAIN),
1003 OPT_BOOLEAN('z', "null", &null_termination,
1004 "terminate entries with NUL"),
1005 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1006 "mode",
1007 "show untracked files, optional modes: all, normal, no. (Default: all)",
1008 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1009 OPT_END(),
1012 if (null_termination && status_format == STATUS_FORMAT_LONG)
1013 status_format = STATUS_FORMAT_PORCELAIN;
1015 wt_status_prepare(&s);
1016 git_config(git_status_config, &s);
1017 in_merge = file_exists(git_path("MERGE_HEAD"));
1018 argc = parse_options(argc, argv, prefix,
1019 builtin_status_options,
1020 builtin_status_usage, 0);
1021 handle_untracked_files_arg(&s);
1023 if (*argv)
1024 s.pathspec = get_pathspec(prefix, argv);
1026 read_cache();
1027 refresh_cache(REFRESH_QUIET|REFRESH_UNMERGED);
1028 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1029 s.in_merge = in_merge;
1030 wt_status_collect(&s);
1032 if (s.relative_paths)
1033 s.prefix = prefix;
1034 if (s.use_color == -1)
1035 s.use_color = git_use_color_default;
1036 if (diff_use_color_default == -1)
1037 diff_use_color_default = git_use_color_default;
1039 switch (status_format) {
1040 case STATUS_FORMAT_SHORT:
1041 wt_shortstatus_print(&s, null_termination);
1042 break;
1043 case STATUS_FORMAT_PORCELAIN:
1044 wt_porcelain_print(&s, null_termination);
1045 break;
1046 case STATUS_FORMAT_LONG:
1047 s.verbose = verbose;
1048 wt_status_print(&s);
1049 break;
1051 return 0;
1054 static void print_summary(const char *prefix, const unsigned char *sha1)
1056 struct rev_info rev;
1057 struct commit *commit;
1058 static const char *format = "format:%h] %s";
1059 unsigned char junk_sha1[20];
1060 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1062 commit = lookup_commit(sha1);
1063 if (!commit)
1064 die("couldn't look up newly created commit");
1065 if (!commit || parse_commit(commit))
1066 die("could not parse newly created commit");
1068 init_revisions(&rev, prefix);
1069 setup_revisions(0, NULL, &rev, NULL);
1071 rev.abbrev = 0;
1072 rev.diff = 1;
1073 rev.diffopt.output_format =
1074 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1076 rev.verbose_header = 1;
1077 rev.show_root_diff = 1;
1078 get_commit_format(format, &rev);
1079 rev.always_show_header = 0;
1080 rev.diffopt.detect_rename = 1;
1081 rev.diffopt.rename_limit = 100;
1082 rev.diffopt.break_opt = 0;
1083 diff_setup_done(&rev.diffopt);
1085 printf("[%s%s ",
1086 !prefixcmp(head, "refs/heads/") ?
1087 head + 11 :
1088 !strcmp(head, "HEAD") ?
1089 "detached HEAD" :
1090 head,
1091 initial_commit ? " (root-commit)" : "");
1093 if (!log_tree_commit(&rev, commit)) {
1094 struct pretty_print_context ctx = {0};
1095 struct strbuf buf = STRBUF_INIT;
1096 ctx.date_mode = DATE_NORMAL;
1097 format_commit_message(commit, format + 7, &buf, &ctx);
1098 printf("%s\n", buf.buf);
1099 strbuf_release(&buf);
1103 static int git_commit_config(const char *k, const char *v, void *cb)
1105 struct wt_status *s = cb;
1107 if (!strcmp(k, "commit.template"))
1108 return git_config_pathname(&template_file, k, v);
1109 if (!strcmp(k, "commit.status")) {
1110 include_status = git_config_bool(k, v);
1111 return 0;
1114 return git_status_config(k, v, s);
1117 int cmd_commit(int argc, const char **argv, const char *prefix)
1119 struct strbuf sb = STRBUF_INIT;
1120 const char *index_file, *reflog_msg;
1121 char *nl, *p;
1122 unsigned char commit_sha1[20];
1123 struct ref_lock *ref_lock;
1124 struct commit_list *parents = NULL, **pptr = &parents;
1125 struct stat statbuf;
1126 int allow_fast_forward = 1;
1127 struct wt_status s;
1129 wt_status_prepare(&s);
1130 git_config(git_commit_config, &s);
1131 in_merge = file_exists(git_path("MERGE_HEAD"));
1132 s.in_merge = in_merge;
1134 if (s.use_color == -1)
1135 s.use_color = git_use_color_default;
1136 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1137 prefix, &s);
1138 if (dry_run) {
1139 if (diff_use_color_default == -1)
1140 diff_use_color_default = git_use_color_default;
1141 return dry_run_commit(argc, argv, prefix, &s);
1143 index_file = prepare_index(argc, argv, prefix, 0);
1145 /* Set up everything for writing the commit object. This includes
1146 running hooks, writing the trees, and interacting with the user. */
1147 if (!prepare_to_commit(index_file, prefix, &s)) {
1148 rollback_index_files();
1149 return 1;
1152 /* Determine parents */
1153 if (initial_commit) {
1154 reflog_msg = "commit (initial)";
1155 } else if (amend) {
1156 struct commit_list *c;
1157 struct commit *commit;
1159 reflog_msg = "commit (amend)";
1160 commit = lookup_commit(head_sha1);
1161 if (!commit || parse_commit(commit))
1162 die("could not parse HEAD commit");
1164 for (c = commit->parents; c; c = c->next)
1165 pptr = &commit_list_insert(c->item, pptr)->next;
1166 } else if (in_merge) {
1167 struct strbuf m = STRBUF_INIT;
1168 FILE *fp;
1170 reflog_msg = "commit (merge)";
1171 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1172 fp = fopen(git_path("MERGE_HEAD"), "r");
1173 if (fp == NULL)
1174 die_errno("could not open '%s' for reading",
1175 git_path("MERGE_HEAD"));
1176 while (strbuf_getline(&m, fp, '\n') != EOF) {
1177 unsigned char sha1[20];
1178 if (get_sha1_hex(m.buf, sha1) < 0)
1179 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1180 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1182 fclose(fp);
1183 strbuf_release(&m);
1184 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1185 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1186 die_errno("could not read MERGE_MODE");
1187 if (!strcmp(sb.buf, "no-ff"))
1188 allow_fast_forward = 0;
1190 if (allow_fast_forward)
1191 parents = reduce_heads(parents);
1192 } else {
1193 reflog_msg = "commit";
1194 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1197 /* Finally, get the commit message */
1198 strbuf_reset(&sb);
1199 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1200 int saved_errno = errno;
1201 rollback_index_files();
1202 die("could not read commit message: %s", strerror(saved_errno));
1205 /* Truncate the message just before the diff, if any. */
1206 if (verbose) {
1207 p = strstr(sb.buf, "\ndiff --git ");
1208 if (p != NULL)
1209 strbuf_setlen(&sb, p - sb.buf + 1);
1212 if (cleanup_mode != CLEANUP_NONE)
1213 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1214 if (message_is_empty(&sb)) {
1215 rollback_index_files();
1216 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1217 exit(1);
1220 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1221 fmt_ident(author_name, author_email, author_date,
1222 IDENT_ERROR_ON_NO_NAME))) {
1223 rollback_index_files();
1224 die("failed to write commit object");
1227 ref_lock = lock_any_ref_for_update("HEAD",
1228 initial_commit ? NULL : head_sha1,
1231 nl = strchr(sb.buf, '\n');
1232 if (nl)
1233 strbuf_setlen(&sb, nl + 1 - sb.buf);
1234 else
1235 strbuf_addch(&sb, '\n');
1236 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1237 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1239 if (!ref_lock) {
1240 rollback_index_files();
1241 die("cannot lock HEAD ref");
1243 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1244 rollback_index_files();
1245 die("cannot update HEAD ref");
1248 unlink(git_path("MERGE_HEAD"));
1249 unlink(git_path("MERGE_MSG"));
1250 unlink(git_path("MERGE_MODE"));
1251 unlink(git_path("SQUASH_MSG"));
1253 if (commit_index_files())
1254 die ("Repository has been updated, but unable to write\n"
1255 "new_index file. Check that disk is not full or quota is\n"
1256 "not exceeded, and then \"git reset HEAD\" to recover.");
1258 rerere();
1259 run_hook(get_index_file(), "post-commit", NULL);
1260 if (!quiet)
1261 print_summary(prefix, commit_sha1);
1263 return 0;