file_exists(): dangling symlinks do exist
[git/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"
10#include "builtin.h"
11#include "diff.h"
12#include "diffcore.h"
13#include "commit.h"
14#include "revision.h"
15#include "wt-status.h"
16#include "run-command.h"
17#include "refs.h"
18#include "log-tree.h"
19#include "strbuf.h"
20#include "utf8.h"
21#include "parse-options.h"
22
23static const char * const builtin_commit_usage[] = {
24 "git-commit [options] [--] <filepattern>...",
25 NULL
26};
27
28static unsigned char head_sha1[20], merge_head_sha1[20];
29static char *use_message_buffer;
30static const char commit_editmsg[] = "COMMIT_EDITMSG";
31static struct lock_file lock_file;
32
f9568530 33static char *logfile, *force_author, *template_file;
f5bbc322
KH
34static char *edit_message, *use_message;
35static int all, edit_flag, also, interactive, only, amend, signoff;
36static int quiet, verbose, untracked_files, no_verify;
37
38static int no_edit, initial_commit, in_merge;
39const char *only_include_assumed;
f9568530
JS
40struct strbuf message;
41
42static int opt_parse_m(const struct option *opt, const char *arg, int unset)
43{
44 struct strbuf *buf = opt->value;
45 if (unset)
46 strbuf_setlen(buf, 0);
47 else {
48 strbuf_addstr(buf, arg);
49 strbuf_addch(buf, '\n');
50 strbuf_addch(buf, '\n');
51 }
52 return 0;
53}
f5bbc322
KH
54
55static struct option builtin_commit_options[] = {
56 OPT__QUIET(&quiet),
57 OPT__VERBOSE(&verbose),
58 OPT_GROUP("Commit message options"),
59
60 OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
61 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
f9568530 62 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
f5bbc322
KH
63 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
64 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
65 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
66 OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
67 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
68
69 OPT_GROUP("Commit contents options"),
70 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
71 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
72 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
73 OPT_BOOLEAN('o', "only", &only, ""),
74 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
75 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
76 OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
77
78 OPT_END()
79};
80
81static char *prepare_index(const char **files, const char *prefix)
82{
83 int fd;
84 struct tree *tree;
85 struct lock_file *next_index_lock;
86
87 if (interactive) {
88 interactive_add();
89 return get_index_file();
90 }
91
92 fd = hold_locked_index(&lock_file, 1);
93 if (read_cache() < 0)
94 die("index file corrupt");
95
96 if (all || also) {
97 add_files_to_cache(verbose, also ? prefix : NULL, files);
d37d3203 98 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
99 if (write_cache(fd, active_cache, active_nr) || close(fd))
100 die("unable to write new_index file");
101 return lock_file.filename;
102 }
103
104 if (*files == NULL) {
105 /* Commit index as-is. */
106 rollback_lock_file(&lock_file);
107 return get_index_file();
108 }
109
110 /* update the user index file */
111 add_files_to_cache(verbose, prefix, files);
ef12b50d 112 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
113 if (write_cache(fd, active_cache, active_nr) || close(fd))
114 die("unable to write new_index file");
115
116 if (!initial_commit) {
117 tree = parse_tree_indirect(head_sha1);
118 if (!tree)
119 die("failed to unpack HEAD tree object");
120 if (read_tree(tree, 0, NULL))
121 die("failed to read HEAD tree object");
122 }
123
124 /* Use a lock file to garbage collect the temporary index file. */
125 next_index_lock = xmalloc(sizeof(*next_index_lock));
126 fd = hold_lock_file_for_update(next_index_lock,
127 git_path("next-index-%d", getpid()), 1);
128 add_files_to_cache(verbose, prefix, files);
d37d3203 129 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
130 if (write_cache(fd, active_cache, active_nr) || close(fd))
131 die("unable to write new_index file");
132
133 return next_index_lock->filename;
134}
135
367c9886 136static int run_status(FILE *fp, const char *index_file, const char *prefix)
f5bbc322
KH
137{
138 struct wt_status s;
139
140 wt_status_prepare(&s);
367c9886 141 s.prefix = prefix;
f5bbc322
KH
142
143 if (amend) {
144 s.amend = 1;
145 s.reference = "HEAD^1";
146 }
147 s.verbose = verbose;
148 s.untracked = untracked_files;
149 s.index_file = index_file;
150 s.fp = fp;
151
152 wt_status_print(&s);
153
154 return s.commitable;
155}
156
157static const char sign_off_header[] = "Signed-off-by: ";
158
367c9886 159static int prepare_log_message(const char *index_file, const char *prefix)
f5bbc322
KH
160{
161 struct stat statbuf;
162 int commitable;
163 struct strbuf sb;
164 char *buffer;
165 FILE *fp;
166
167 strbuf_init(&sb, 0);
f9568530
JS
168 if (message.len) {
169 strbuf_addbuf(&sb, &message);
f5bbc322
KH
170 } else if (logfile && !strcmp(logfile, "-")) {
171 if (isatty(0))
172 fprintf(stderr, "(reading log message from standard input)\n");
173 if (strbuf_read(&sb, 0, 0) < 0)
174 die("could not read log from standard input");
175 } else if (logfile) {
176 if (strbuf_read_file(&sb, logfile, 0) < 0)
177 die("could not read log file '%s': %s",
178 logfile, strerror(errno));
179 } else if (use_message) {
180 buffer = strstr(use_message_buffer, "\n\n");
181 if (!buffer || buffer[2] == '\0')
182 die("commit has empty message");
183 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
184 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
185 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
186 die("could not read MERGE_MSG: %s", strerror(errno));
187 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
188 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
189 die("could not read SQUASH_MSG: %s", strerror(errno));
190 } else if (template_file && !stat(template_file, &statbuf)) {
191 if (strbuf_read_file(&sb, template_file, 0) < 0)
192 die("could not read %s: %s",
193 template_file, strerror(errno));
194 }
195
196 fp = fopen(git_path(commit_editmsg), "w");
197 if (fp == NULL)
198 die("could not open %s\n", git_path(commit_editmsg));
199
200 stripspace(&sb, 0);
f5bbc322
KH
201
202 if (signoff) {
13208572
JS
203 struct strbuf sob;
204 int i;
205
206 strbuf_init(&sob, 0);
207 strbuf_addstr(&sob, sign_off_header);
208 strbuf_addstr(&sob, fmt_ident(getenv("GIT_COMMITTER_NAME"),
209 getenv("GIT_COMMITTER_EMAIL"),
210 "", 1));
211 strbuf_addch(&sob, '\n');
212
213 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
214 ; /* do nothing */
2150554b
JS
215 if (prefixcmp(sb.buf + i, sob.buf)) {
216 if (prefixcmp(sb.buf + i, sign_off_header))
217 strbuf_addch(&sb, '\n');
13208572 218 strbuf_addbuf(&sb, &sob);
2150554b 219 }
13208572 220 strbuf_release(&sob);
f5bbc322
KH
221 }
222
13208572
JS
223 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
224 die("could not write commit template: %s\n",
225 strerror(errno));
226
f5bbc322
KH
227 strbuf_release(&sb);
228
229 if (in_merge && !no_edit)
230 fprintf(fp,
231 "#\n"
232 "# It looks like you may be committing a MERGE.\n"
233 "# If this is not correct, please remove the file\n"
234 "# %s\n"
235 "# and try again.\n"
236 "#\n",
237 git_path("MERGE_HEAD"));
238
239 fprintf(fp,
240 "\n"
241 "# Please enter the commit message for your changes.\n"
242 "# (Comment lines starting with '#' will not be included)\n");
243 if (only_include_assumed)
244 fprintf(fp, "# %s\n", only_include_assumed);
245
367c9886 246 commitable = run_status(fp, index_file, prefix);
f5bbc322
KH
247
248 fclose(fp);
249
250 return commitable;
251}
252
253/*
254 * Find out if the message starting at position 'start' in the strbuf
255 * contains only whitespace and Signed-off-by lines.
256 */
257static int message_is_empty(struct strbuf *sb, int start)
258{
259 struct strbuf tmpl;
260 const char *nl;
261 int eol, i;
262
263 /* See if the template is just a prefix of the message. */
264 strbuf_init(&tmpl, 0);
265 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
266 stripspace(&tmpl, 1);
267 if (start + tmpl.len <= sb->len &&
268 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
269 start += tmpl.len;
270 }
271 strbuf_release(&tmpl);
272
273 /* Check if the rest is just whitespace and Signed-of-by's. */
274 for (i = start; i < sb->len; i++) {
275 nl = memchr(sb->buf + i, '\n', sb->len - i);
276 if (nl)
277 eol = nl - sb->buf;
278 else
279 eol = sb->len;
280
281 if (strlen(sign_off_header) <= eol - i &&
282 !prefixcmp(sb->buf + i, sign_off_header)) {
283 i = eol;
284 continue;
285 }
286 while (i < eol)
287 if (!isspace(sb->buf[i++]))
288 return 0;
289 }
290
291 return 1;
292}
293
294static void determine_author_info(struct strbuf *sb)
295{
296 char *name, *email, *date;
297
298 name = getenv("GIT_AUTHOR_NAME");
299 email = getenv("GIT_AUTHOR_EMAIL");
300 date = getenv("GIT_AUTHOR_DATE");
301
302 if (use_message) {
303 const char *a, *lb, *rb, *eol;
304
305 a = strstr(use_message_buffer, "\nauthor ");
306 if (!a)
307 die("invalid commit: %s\n", use_message);
308
309 lb = strstr(a + 8, " <");
310 rb = strstr(a + 8, "> ");
311 eol = strchr(a + 8, '\n');
312 if (!lb || !rb || !eol)
313 die("invalid commit: %s\n", use_message);
314
315 name = xstrndup(a + 8, lb - (a + 8));
316 email = xstrndup(lb + 2, rb - (lb + 2));
317 date = xstrndup(rb + 2, eol - (rb + 2));
318 }
319
320 if (force_author) {
321 const char *lb = strstr(force_author, " <");
322 const char *rb = strchr(force_author, '>');
323
324 if (!lb || !rb)
325 die("malformed --author parameter\n");
326 name = xstrndup(force_author, lb - force_author);
327 email = xstrndup(lb + 2, rb - (lb + 2));
328 }
329
330 strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, 1));
331}
332
333static int parse_and_validate_options(int argc, const char *argv[])
334{
335 int f = 0;
336
337 argc = parse_options(argc, argv, builtin_commit_options,
338 builtin_commit_usage, 0);
339
f9568530 340 if (logfile || message.len || use_message)
f5bbc322
KH
341 no_edit = 1;
342 if (edit_flag)
343 no_edit = 0;
344
345 if (get_sha1("HEAD", head_sha1))
346 initial_commit = 1;
347
348 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
349 in_merge = 1;
350
351 /* Sanity check options */
352 if (amend && initial_commit)
353 die("You have nothing to amend.");
354 if (amend && in_merge)
355 die("You are in the middle of a merger -- cannot amend.");
356
357 if (use_message)
358 f++;
359 if (edit_message)
360 f++;
361 if (logfile)
362 f++;
363 if (f > 1)
364 die("Only one of -c/-C/-F can be used.");
f9568530 365 if (message.len && f > 0)
f5bbc322
KH
366 die("Option -m cannot be combined with -c/-C/-F.");
367 if (edit_message)
368 use_message = edit_message;
369 if (amend)
370 use_message = "HEAD";
371 if (use_message) {
372 unsigned char sha1[20];
373 static char utf8[] = "UTF-8";
374 const char *out_enc;
375 char *enc, *end;
376 struct commit *commit;
377
378 if (get_sha1(use_message, sha1))
379 die("could not lookup commit %s", use_message);
380 commit = lookup_commit(sha1);
381 if (!commit || parse_commit(commit))
382 die("could not parse commit %s", use_message);
383
384 enc = strstr(commit->buffer, "\nencoding");
385 if (enc) {
386 end = strchr(enc + 10, '\n');
387 enc = xstrndup(enc + 10, end - (enc + 10));
388 } else {
389 enc = utf8;
390 }
391 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
392
393 if (strcmp(out_enc, enc))
394 use_message_buffer =
395 reencode_string(commit->buffer, out_enc, enc);
396
397 /*
398 * If we failed to reencode the buffer, just copy it
399 * byte for byte so the user can try to fix it up.
400 * This also handles the case where input and output
401 * encodings are identical.
402 */
403 if (use_message_buffer == NULL)
404 use_message_buffer = xstrdup(commit->buffer);
405 if (enc != utf8)
406 free(enc);
407 }
408
409 if (!!also + !!only + !!all + !!interactive > 1)
410 die("Only one of --include/--only/--all/--interactive can be used.");
411 if (argc == 0 && (also || (only && !amend)))
412 die("No paths with --include/--only does not make sense.");
413 if (argc == 0 && only && amend)
414 only_include_assumed = "Clever... amending the last one with dirty index.";
415 if (argc > 0 && !also && !only) {
416 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
417 also = 0;
418 }
419
420 if (all && argc > 0)
421 die("Paths with -a does not make sense.");
422 else if (interactive && argc > 0)
423 die("Paths with --interactive does not make sense.");
424
425 return argc;
426}
427
428int cmd_status(int argc, const char **argv, const char *prefix)
429{
430 const char *index_file;
431 int commitable;
432
433 git_config(git_status_config);
434
435 argc = parse_and_validate_options(argc, argv);
436
437 index_file = prepare_index(argv, prefix);
438
367c9886 439 commitable = run_status(stdout, index_file, prefix);
f5bbc322
KH
440
441 rollback_lock_file(&lock_file);
442
443 return commitable ? 0 : 1;
444}
445
446static int run_hook(const char *index_file, const char *name, const char *arg)
447{
448 struct child_process hook;
449 const char *argv[3], *env[2];
450 char index[PATH_MAX];
451
452 argv[0] = git_path("hooks/%s", name);
453 argv[1] = arg;
454 argv[2] = NULL;
455 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
456 env[0] = index;
457 env[1] = NULL;
458
459 if (access(argv[0], X_OK) < 0)
460 return 0;
461
462 memset(&hook, 0, sizeof(hook));
463 hook.argv = argv;
464 hook.no_stdin = 1;
465 hook.stdout_to_stderr = 1;
466 hook.env = env;
467
468 return run_command(&hook);
469}
470
471static void print_summary(const char *prefix, const unsigned char *sha1)
472{
473 struct rev_info rev;
474 struct commit *commit;
475
476 commit = lookup_commit(sha1);
477 if (!commit)
478 die("couldn't look up newly created commit\n");
479 if (!commit || parse_commit(commit))
480 die("could not parse newly created commit");
481
482 init_revisions(&rev, prefix);
483 setup_revisions(0, NULL, &rev, NULL);
484
485 rev.abbrev = 0;
486 rev.diff = 1;
487 rev.diffopt.output_format =
488 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
489
490 rev.verbose_header = 1;
491 rev.show_root_diff = 1;
492 rev.commit_format = get_commit_format("format:%h: %s");
493 rev.always_show_header = 1;
494
495 printf("Created %scommit ", initial_commit ? "initial " : "");
496
497 log_tree_commit(&rev, commit);
129fa606 498 printf("\n");
f5bbc322
KH
499}
500
501int git_commit_config(const char *k, const char *v)
502{
503 if (!strcmp(k, "commit.template")) {
504 template_file = xstrdup(v);
505 return 0;
506 }
507
508 return git_status_config(k, v);
509}
510
511static const char commit_utf8_warn[] =
512"Warning: commit message does not conform to UTF-8.\n"
513"You may want to amend it after fixing the message, or set the config\n"
514"variable i18n.commitencoding to the encoding your project uses.\n";
515
516int cmd_commit(int argc, const char **argv, const char *prefix)
517{
18abc2db 518 int header_len;
f5bbc322
KH
519 struct strbuf sb;
520 const char *index_file, *reflog_msg;
741707b1 521 char *nl;
f5bbc322
KH
522 unsigned char commit_sha1[20];
523 struct ref_lock *ref_lock;
524
525 git_config(git_commit_config);
526
527 argc = parse_and_validate_options(argc, argv);
528
529 index_file = prepare_index(argv, prefix);
530
531 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
532 exit(1);
533
367c9886
JS
534 if (!prepare_log_message(index_file, prefix) && !in_merge) {
535 run_status(stdout, index_file, prefix);
f5bbc322
KH
536 unlink(commit_editmsg);
537 return 1;
538 }
539
540 strbuf_init(&sb, 0);
541
542 /* Start building up the commit header */
543 read_cache_from(index_file);
544 active_cache_tree = cache_tree();
545 if (cache_tree_update(active_cache_tree,
546 active_cache, active_nr, 0, 0) < 0)
547 die("Error building trees");
548 strbuf_addf(&sb, "tree %s\n",
549 sha1_to_hex(active_cache_tree->sha1));
550
551 /* Determine parents */
552 if (initial_commit) {
553 reflog_msg = "commit (initial)";
f5bbc322
KH
554 } else if (amend) {
555 struct commit_list *c;
556 struct commit *commit;
557
558 reflog_msg = "commit (amend)";
559 commit = lookup_commit(head_sha1);
560 if (!commit || parse_commit(commit))
561 die("could not parse HEAD commit");
562
563 for (c = commit->parents; c; c = c->next)
564 strbuf_addf(&sb, "parent %s\n",
565 sha1_to_hex(c->item->object.sha1));
566 } else if (in_merge) {
567 struct strbuf m;
568 FILE *fp;
569
570 reflog_msg = "commit (merge)";
571 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
572 strbuf_init(&m, 0);
573 fp = fopen(git_path("MERGE_HEAD"), "r");
574 if (fp == NULL)
575 die("could not open %s for reading: %s",
576 git_path("MERGE_HEAD"), strerror(errno));
577 while (strbuf_getline(&m, fp, '\n') != EOF)
578 strbuf_addf(&sb, "parent %s\n", m.buf);
579 fclose(fp);
580 strbuf_release(&m);
581 } else {
582 reflog_msg = "commit";
583 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
584 }
585
586 determine_author_info(&sb);
587 strbuf_addf(&sb, "committer %s\n", git_committer_info(1));
588 if (!is_encoding_utf8(git_commit_encoding))
589 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
590 strbuf_addch(&sb, '\n');
591
592 /* Get the commit message and validate it */
593 header_len = sb.len;
18abc2db 594 if (!no_edit)
f5bbc322 595 launch_editor(git_path(commit_editmsg), &sb);
18abc2db 596 else if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0)
f5bbc322
KH
597 die("could not read commit message\n");
598 if (run_hook(index_file, "commit-msg", commit_editmsg))
599 exit(1);
600 stripspace(&sb, 1);
601 if (sb.len < header_len ||
602 message_is_empty(&sb, header_len))
603 die("* no commit message? aborting commit.");
604 strbuf_addch(&sb, '\0');
605 if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
606 fprintf(stderr, commit_utf8_warn);
607
608 if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1))
609 die("failed to write commit object");
610
611 ref_lock = lock_any_ref_for_update("HEAD",
612 initial_commit ? NULL : head_sha1,
613 0);
614
615 nl = strchr(sb.buf + header_len, '\n');
741707b1
JS
616 if (nl)
617 strbuf_setlen(&sb, nl + 1 - sb.buf);
618 else
619 strbuf_addch(&sb, '\n');
620 strbuf_remove(&sb, 0, header_len);
621 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
622 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
f5bbc322
KH
623
624 if (!ref_lock)
625 die("cannot lock HEAD ref");
626 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0)
627 die("cannot update HEAD ref");
628
629 unlink(git_path("MERGE_HEAD"));
630 unlink(git_path("MERGE_MSG"));
631
632 if (lock_file.filename[0] && commit_locked_index(&lock_file))
633 die("failed to write new index");
634
635 rerere();
636
637 run_hook(index_file, "post-commit", NULL);
638
639 if (!quiet)
640 print_summary(prefix, commit_sha1);
641
642 return 0;
643}