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