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