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