builtin-commit.con commit Do not generate full commit log message if it is not going to be used (7168624)
   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 "dir.h"
  11#include "builtin.h"
  12#include "diff.h"
  13#include "diffcore.h"
  14#include "commit.h"
  15#include "revision.h"
  16#include "wt-status.h"
  17#include "run-command.h"
  18#include "refs.h"
  19#include "log-tree.h"
  20#include "strbuf.h"
  21#include "utf8.h"
  22#include "parse-options.h"
  23#include "path-list.h"
  24
  25static const char * const builtin_commit_usage[] = {
  26        "git-commit [options] [--] <filepattern>...",
  27        NULL
  28};
  29
  30static unsigned char head_sha1[20], merge_head_sha1[20];
  31static char *use_message_buffer;
  32static const char commit_editmsg[] = "COMMIT_EDITMSG";
  33static struct lock_file index_lock; /* real index */
  34static struct lock_file false_lock; /* used only for partial commits */
  35static enum {
  36        COMMIT_AS_IS = 1,
  37        COMMIT_NORMAL,
  38        COMMIT_PARTIAL,
  39} commit_style;
  40
  41static char *logfile, *force_author, *template_file;
  42static char *edit_message, *use_message;
  43static int all, edit_flag, also, interactive, only, amend, signoff;
  44static int quiet, verbose, untracked_files, no_verify;
  45
  46static int no_edit, initial_commit, in_merge;
  47const char *only_include_assumed;
  48struct strbuf message;
  49
  50static int opt_parse_m(const struct option *opt, const char *arg, int unset)
  51{
  52        struct strbuf *buf = opt->value;
  53        if (unset)
  54                strbuf_setlen(buf, 0);
  55        else {
  56                strbuf_addstr(buf, arg);
  57                strbuf_addch(buf, '\n');
  58                strbuf_addch(buf, '\n');
  59        }
  60        return 0;
  61}
  62
  63static struct option builtin_commit_options[] = {
  64        OPT__QUIET(&quiet),
  65        OPT__VERBOSE(&verbose),
  66        OPT_GROUP("Commit message options"),
  67
  68        OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
  69        OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
  70        OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
  71        OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
  72        OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
  73        OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
  74        OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
  75        OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
  76
  77        OPT_GROUP("Commit contents options"),
  78        OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
  79        OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
  80        OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
  81        OPT_BOOLEAN('o', "only", &only, ""),
  82        OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
  83        OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
  84        OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
  85
  86        OPT_END()
  87};
  88
  89static void rollback_index_files(void)
  90{
  91        switch (commit_style) {
  92        case COMMIT_AS_IS:
  93                break; /* nothing to do */
  94        case COMMIT_NORMAL:
  95                rollback_lock_file(&index_lock);
  96                break;
  97        case COMMIT_PARTIAL:
  98                rollback_lock_file(&index_lock);
  99                rollback_lock_file(&false_lock);
 100                break;
 101        }
 102}
 103
 104static void commit_index_files(void)
 105{
 106        switch (commit_style) {
 107        case COMMIT_AS_IS:
 108                break; /* nothing to do */
 109        case COMMIT_NORMAL:
 110                commit_lock_file(&index_lock);
 111                break;
 112        case COMMIT_PARTIAL:
 113                commit_lock_file(&index_lock);
 114                rollback_lock_file(&false_lock);
 115                break;
 116        }
 117}
 118
 119/*
 120 * Take a union of paths in the index and the named tree (typically, "HEAD"),
 121 * and return the paths that match the given pattern in list.
 122 */
 123static int list_paths(struct path_list *list, const char *with_tree,
 124                      const char *prefix, const char **pattern)
 125{
 126        int i;
 127        char *m;
 128
 129        for (i = 0; pattern[i]; i++)
 130                ;
 131        m = xcalloc(1, i);
 132
 133        if (with_tree)
 134                overlay_tree_on_cache(with_tree, prefix);
 135
 136        for (i = 0; i < active_nr; i++) {
 137                struct cache_entry *ce = active_cache[i];
 138                if (ce->ce_flags & htons(CE_UPDATE))
 139                        continue;
 140                if (!pathspec_match(pattern, m, ce->name, 0))
 141                        continue;
 142                path_list_insert(ce->name, list);
 143        }
 144
 145        return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
 146}
 147
 148static void add_remove_files(struct path_list *list)
 149{
 150        int i;
 151        for (i = 0; i < list->nr; i++) {
 152                struct path_list_item *p = &(list->items[i]);
 153                if (file_exists(p->path))
 154                        add_file_to_cache(p->path, 0);
 155                else
 156                        remove_file_from_cache(p->path);
 157        }
 158}
 159
 160static char *prepare_index(const char **files, const char *prefix)
 161{
 162        int fd;
 163        struct tree *tree;
 164        struct path_list partial;
 165        const char **pathspec = NULL;
 166
 167        if (interactive) {
 168                interactive_add();
 169                commit_style = COMMIT_AS_IS;
 170                return get_index_file();
 171        }
 172
 173        if (read_cache() < 0)
 174                die("index file corrupt");
 175
 176        if (*files)
 177                pathspec = get_pathspec(prefix, files);
 178
 179        /*
 180         * Non partial, non as-is commit.
 181         *
 182         * (1) get the real index;
 183         * (2) update the_index as necessary;
 184         * (3) write the_index out to the real index (still locked);
 185         * (4) return the name of the locked index file.
 186         *
 187         * The caller should run hooks on the locked real index, and
 188         * (A) if all goes well, commit the real index;
 189         * (B) on failure, rollback the real index.
 190         */
 191        if (all || (also && pathspec && *pathspec)) {
 192                int fd = hold_locked_index(&index_lock, 1);
 193                add_files_to_cache(0, also ? prefix : NULL, pathspec);
 194                refresh_cache(REFRESH_QUIET);
 195                if (write_cache(fd, active_cache, active_nr) || close(fd))
 196                        die("unable to write new_index file");
 197                commit_style = COMMIT_NORMAL;
 198                return index_lock.filename;
 199        }
 200
 201        /*
 202         * As-is commit.
 203         *
 204         * (1) return the name of the real index file.
 205         *
 206         * The caller should run hooks on the real index, and run
 207         * hooks on the real index, and create commit from the_index.
 208         * We still need to refresh the index here.
 209         */
 210        if (!pathspec || !*pathspec) {
 211                fd = hold_locked_index(&index_lock, 1);
 212                refresh_cache(REFRESH_QUIET);
 213                if (write_cache(fd, active_cache, active_nr) ||
 214                    close(fd) || commit_locked_index(&index_lock))
 215                        die("unable to write new_index file");
 216                commit_style = COMMIT_AS_IS;
 217                return get_index_file();
 218        }
 219
 220        /*
 221         * A partial commit.
 222         *
 223         * (0) find the set of affected paths;
 224         * (1) get lock on the real index file;
 225         * (2) update the_index with the given paths;
 226         * (3) write the_index out to the real index (still locked);
 227         * (4) get lock on the false index file;
 228         * (5) reset the_index from HEAD;
 229         * (6) update the_index the same way as (2);
 230         * (7) write the_index out to the false index file;
 231         * (8) return the name of the false index file (still locked);
 232         *
 233         * The caller should run hooks on the locked false index, and
 234         * create commit from it.  Then
 235         * (A) if all goes well, commit the real index;
 236         * (B) on failure, rollback the real index;
 237         * In either case, rollback the false index.
 238         */
 239        commit_style = COMMIT_PARTIAL;
 240
 241        if (file_exists(git_path("MERGE_HEAD")))
 242                die("cannot do a partial commit during a merge.");
 243
 244        memset(&partial, 0, sizeof(partial));
 245        partial.strdup_paths = 1;
 246        if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
 247                exit(1);
 248
 249        discard_cache();
 250        if (read_cache() < 0)
 251                die("cannot read the index");
 252
 253        fd = hold_locked_index(&index_lock, 1);
 254        add_remove_files(&partial);
 255        refresh_cache(REFRESH_QUIET);
 256        if (write_cache(fd, active_cache, active_nr) || close(fd))
 257                die("unable to write new_index file");
 258
 259        fd = hold_lock_file_for_update(&false_lock,
 260                                       git_path("next-index-%d", getpid()), 1);
 261        discard_cache();
 262        if (!initial_commit) {
 263                tree = parse_tree_indirect(head_sha1);
 264                if (!tree)
 265                        die("failed to unpack HEAD tree object");
 266                if (read_tree(tree, 0, NULL))
 267                        die("failed to read HEAD tree object");
 268        }
 269        add_remove_files(&partial);
 270        refresh_cache(REFRESH_QUIET);
 271
 272        if (write_cache(fd, active_cache, active_nr) || close(fd))
 273                die("unable to write temporary index file");
 274        return false_lock.filename;
 275}
 276
 277static int run_status(FILE *fp, const char *index_file, const char *prefix)
 278{
 279        struct wt_status s;
 280
 281        wt_status_prepare(&s);
 282        s.prefix = prefix;
 283
 284        if (amend) {
 285                s.amend = 1;
 286                s.reference = "HEAD^1";
 287        }
 288        s.verbose = verbose;
 289        s.untracked = untracked_files;
 290        s.index_file = index_file;
 291        s.fp = fp;
 292
 293        wt_status_print(&s);
 294
 295        return s.commitable;
 296}
 297
 298static const char sign_off_header[] = "Signed-off-by: ";
 299
 300static int prepare_log_message(const char *index_file, const char *prefix)
 301{
 302        struct stat statbuf;
 303        int commitable, saved_color_setting;
 304        struct strbuf sb;
 305        char *buffer;
 306        FILE *fp;
 307
 308        strbuf_init(&sb, 0);
 309        if (message.len) {
 310                strbuf_addbuf(&sb, &message);
 311        } else if (logfile && !strcmp(logfile, "-")) {
 312                if (isatty(0))
 313                        fprintf(stderr, "(reading log message from standard input)\n");
 314                if (strbuf_read(&sb, 0, 0) < 0)
 315                        die("could not read log from standard input");
 316        } else if (logfile) {
 317                if (strbuf_read_file(&sb, logfile, 0) < 0)
 318                        die("could not read log file '%s': %s",
 319                            logfile, strerror(errno));
 320        } else if (use_message) {
 321                buffer = strstr(use_message_buffer, "\n\n");
 322                if (!buffer || buffer[2] == '\0')
 323                        die("commit has empty message");
 324                strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
 325        } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
 326                if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
 327                        die("could not read MERGE_MSG: %s", strerror(errno));
 328        } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
 329                if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
 330                        die("could not read SQUASH_MSG: %s", strerror(errno));
 331        } else if (template_file && !stat(template_file, &statbuf)) {
 332                if (strbuf_read_file(&sb, template_file, 0) < 0)
 333                        die("could not read %s: %s",
 334                            template_file, strerror(errno));
 335        }
 336
 337        fp = fopen(git_path(commit_editmsg), "w");
 338        if (fp == NULL)
 339                die("could not open %s\n", git_path(commit_editmsg));
 340
 341        stripspace(&sb, 0);
 342
 343        if (signoff) {
 344                struct strbuf sob;
 345                int i;
 346
 347                strbuf_init(&sob, 0);
 348                strbuf_addstr(&sob, sign_off_header);
 349                strbuf_addstr(&sob, fmt_ident(getenv("GIT_COMMITTER_NAME"),
 350                                              getenv("GIT_COMMITTER_EMAIL"),
 351                                              "", 1));
 352                strbuf_addch(&sob, '\n');
 353
 354                for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
 355                        ; /* do nothing */
 356                if (prefixcmp(sb.buf + i, sob.buf)) {
 357                        if (prefixcmp(sb.buf + i, sign_off_header))
 358                                strbuf_addch(&sb, '\n');
 359                        strbuf_addbuf(&sb, &sob);
 360                }
 361                strbuf_release(&sob);
 362        }
 363
 364        if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
 365                die("could not write commit template: %s\n",
 366                    strerror(errno));
 367
 368        strbuf_release(&sb);
 369
 370        if (no_edit) {
 371                struct rev_info rev;
 372                unsigned char sha1[40];
 373
 374                fclose(fp);
 375
 376                if (!active_nr && read_cache() < 0)
 377                        die("Cannot read index");
 378
 379                if (get_sha1("HEAD", sha1) != 0)
 380                        return !!active_nr;
 381
 382                init_revisions(&rev, "");
 383                rev.abbrev = 0;
 384                setup_revisions(0, NULL, &rev, "HEAD");
 385                DIFF_OPT_SET(&rev.diffopt, QUIET);
 386                DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
 387                run_diff_index(&rev, 1 /* cached */);
 388
 389                return !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
 390        }
 391
 392        if (in_merge && !no_edit)
 393                fprintf(fp,
 394                        "#\n"
 395                        "# It looks like you may be committing a MERGE.\n"
 396                        "# If this is not correct, please remove the file\n"
 397                        "#      %s\n"
 398                        "# and try again.\n"
 399                        "#\n",
 400                        git_path("MERGE_HEAD"));
 401
 402        fprintf(fp,
 403                "\n"
 404                "# Please enter the commit message for your changes.\n"
 405                "# (Comment lines starting with '#' will not be included)\n");
 406        if (only_include_assumed)
 407                fprintf(fp, "# %s\n", only_include_assumed);
 408
 409        saved_color_setting = wt_status_use_color;
 410        wt_status_use_color = 0;
 411        commitable = run_status(fp, index_file, prefix);
 412        wt_status_use_color = saved_color_setting;
 413
 414        fclose(fp);
 415
 416        return commitable;
 417}
 418
 419/*
 420 * Find out if the message starting at position 'start' in the strbuf
 421 * contains only whitespace and Signed-off-by lines.
 422 */
 423static int message_is_empty(struct strbuf *sb, int start)
 424{
 425        struct strbuf tmpl;
 426        const char *nl;
 427        int eol, i;
 428
 429        /* See if the template is just a prefix of the message. */
 430        strbuf_init(&tmpl, 0);
 431        if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
 432                stripspace(&tmpl, 1);
 433                if (start + tmpl.len <= sb->len &&
 434                    memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
 435                        start += tmpl.len;
 436        }
 437        strbuf_release(&tmpl);
 438
 439        /* Check if the rest is just whitespace and Signed-of-by's. */
 440        for (i = start; i < sb->len; i++) {
 441                nl = memchr(sb->buf + i, '\n', sb->len - i);
 442                if (nl)
 443                        eol = nl - sb->buf;
 444                else
 445                        eol = sb->len;
 446
 447                if (strlen(sign_off_header) <= eol - i &&
 448                    !prefixcmp(sb->buf + i, sign_off_header)) {
 449                        i = eol;
 450                        continue;
 451                }
 452                while (i < eol)
 453                        if (!isspace(sb->buf[i++]))
 454                                return 0;
 455        }
 456
 457        return 1;
 458}
 459
 460static void determine_author_info(struct strbuf *sb)
 461{
 462        char *name, *email, *date;
 463
 464        name = getenv("GIT_AUTHOR_NAME");
 465        email = getenv("GIT_AUTHOR_EMAIL");
 466        date = getenv("GIT_AUTHOR_DATE");
 467
 468        if (use_message) {
 469                const char *a, *lb, *rb, *eol;
 470
 471                a = strstr(use_message_buffer, "\nauthor ");
 472                if (!a)
 473                        die("invalid commit: %s\n", use_message);
 474
 475                lb = strstr(a + 8, " <");
 476                rb = strstr(a + 8, "> ");
 477                eol = strchr(a + 8, '\n');
 478                if (!lb || !rb || !eol)
 479                        die("invalid commit: %s\n", use_message);
 480
 481                name = xstrndup(a + 8, lb - (a + 8));
 482                email = xstrndup(lb + 2, rb - (lb + 2));
 483                date = xstrndup(rb + 2, eol - (rb + 2));
 484        }
 485
 486        if (force_author) {
 487                const char *lb = strstr(force_author, " <");
 488                const char *rb = strchr(force_author, '>');
 489
 490                if (!lb || !rb)
 491                        die("malformed --author parameter\n");
 492                name = xstrndup(force_author, lb - force_author);
 493                email = xstrndup(lb + 2, rb - (lb + 2));
 494        }
 495
 496        strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, 1));
 497}
 498
 499static int parse_and_validate_options(int argc, const char *argv[])
 500{
 501        int f = 0;
 502
 503        argc = parse_options(argc, argv, builtin_commit_options,
 504                             builtin_commit_usage, 0);
 505
 506        if (logfile || message.len || use_message)
 507                no_edit = 1;
 508        if (edit_flag)
 509                no_edit = 0;
 510
 511        if (get_sha1("HEAD", head_sha1))
 512                initial_commit = 1;
 513
 514        if (!get_sha1("MERGE_HEAD", merge_head_sha1))
 515                in_merge = 1;
 516
 517        /* Sanity check options */
 518        if (amend && initial_commit)
 519                die("You have nothing to amend.");
 520        if (amend && in_merge)
 521                die("You are in the middle of a merger -- cannot amend.");
 522
 523        if (use_message)
 524                f++;
 525        if (edit_message)
 526                f++;
 527        if (logfile)
 528                f++;
 529        if (f > 1)
 530                die("Only one of -c/-C/-F can be used.");
 531        if (message.len && f > 0)
 532                die("Option -m cannot be combined with -c/-C/-F.");
 533        if (edit_message)
 534                use_message = edit_message;
 535        if (amend)
 536                use_message = "HEAD";
 537        if (use_message) {
 538                unsigned char sha1[20];
 539                static char utf8[] = "UTF-8";
 540                const char *out_enc;
 541                char *enc, *end;
 542                struct commit *commit;
 543
 544                if (get_sha1(use_message, sha1))
 545                        die("could not lookup commit %s", use_message);
 546                commit = lookup_commit(sha1);
 547                if (!commit || parse_commit(commit))
 548                        die("could not parse commit %s", use_message);
 549
 550                enc = strstr(commit->buffer, "\nencoding");
 551                if (enc) {
 552                        end = strchr(enc + 10, '\n');
 553                        enc = xstrndup(enc + 10, end - (enc + 10));
 554                } else {
 555                        enc = utf8;
 556                }
 557                out_enc = git_commit_encoding ? git_commit_encoding : utf8;
 558
 559                if (strcmp(out_enc, enc))
 560                        use_message_buffer =
 561                                reencode_string(commit->buffer, out_enc, enc);
 562
 563                /*
 564                 * If we failed to reencode the buffer, just copy it
 565                 * byte for byte so the user can try to fix it up.
 566                 * This also handles the case where input and output
 567                 * encodings are identical.
 568                 */
 569                if (use_message_buffer == NULL)
 570                        use_message_buffer = xstrdup(commit->buffer);
 571                if (enc != utf8)
 572                        free(enc);
 573        }
 574
 575        if (!!also + !!only + !!all + !!interactive > 1)
 576                die("Only one of --include/--only/--all/--interactive can be used.");
 577        if (argc == 0 && (also || (only && !amend)))
 578                die("No paths with --include/--only does not make sense.");
 579        if (argc == 0 && only && amend)
 580                only_include_assumed = "Clever... amending the last one with dirty index.";
 581        if (argc > 0 && !also && !only) {
 582                only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
 583                also = 0;
 584        }
 585
 586        if (all && argc > 0)
 587                die("Paths with -a does not make sense.");
 588        else if (interactive && argc > 0)
 589                die("Paths with --interactive does not make sense.");
 590
 591        return argc;
 592}
 593
 594int cmd_status(int argc, const char **argv, const char *prefix)
 595{
 596        const char *index_file;
 597        int commitable;
 598
 599        git_config(git_status_config);
 600
 601        argc = parse_and_validate_options(argc, argv);
 602
 603        index_file = prepare_index(argv, prefix);
 604
 605        commitable = run_status(stdout, index_file, prefix);
 606
 607        rollback_index_files();
 608
 609        return commitable ? 0 : 1;
 610}
 611
 612static int run_hook(const char *index_file, const char *name, const char *arg)
 613{
 614        struct child_process hook;
 615        const char *argv[3], *env[2];
 616        char index[PATH_MAX];
 617
 618        argv[0] = git_path("hooks/%s", name);
 619        argv[1] = arg;
 620        argv[2] = NULL;
 621        snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 622        env[0] = index;
 623        env[1] = NULL;
 624
 625        if (access(argv[0], X_OK) < 0)
 626                return 0;
 627
 628        memset(&hook, 0, sizeof(hook));
 629        hook.argv = argv;
 630        hook.no_stdin = 1;
 631        hook.stdout_to_stderr = 1;
 632        hook.env = env;
 633
 634        return run_command(&hook);
 635}
 636
 637static void print_summary(const char *prefix, const unsigned char *sha1)
 638{
 639        struct rev_info rev;
 640        struct commit *commit;
 641
 642        commit = lookup_commit(sha1);
 643        if (!commit)
 644                die("couldn't look up newly created commit\n");
 645        if (!commit || parse_commit(commit))
 646                die("could not parse newly created commit");
 647
 648        init_revisions(&rev, prefix);
 649        setup_revisions(0, NULL, &rev, NULL);
 650
 651        rev.abbrev = 0;
 652        rev.diff = 1;
 653        rev.diffopt.output_format =
 654                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
 655
 656        rev.verbose_header = 1;
 657        rev.show_root_diff = 1;
 658        rev.commit_format = get_commit_format("format:%h: %s");
 659        rev.always_show_header = 1;
 660
 661        printf("Created %scommit ", initial_commit ? "initial " : "");
 662
 663        log_tree_commit(&rev, commit);
 664        printf("\n");
 665}
 666
 667int git_commit_config(const char *k, const char *v)
 668{
 669        if (!strcmp(k, "commit.template")) {
 670                template_file = xstrdup(v);
 671                return 0;
 672        }
 673
 674        return git_status_config(k, v);
 675}
 676
 677static const char commit_utf8_warn[] =
 678"Warning: commit message does not conform to UTF-8.\n"
 679"You may want to amend it after fixing the message, or set the config\n"
 680"variable i18n.commitencoding to the encoding your project uses.\n";
 681
 682int cmd_commit(int argc, const char **argv, const char *prefix)
 683{
 684        int header_len;
 685        struct strbuf sb;
 686        const char *index_file, *reflog_msg;
 687        char *nl, *p;
 688        unsigned char commit_sha1[20];
 689        struct ref_lock *ref_lock;
 690
 691        git_config(git_commit_config);
 692
 693        argc = parse_and_validate_options(argc, argv);
 694
 695        index_file = prepare_index(argv, prefix);
 696
 697        if (!no_verify && run_hook(index_file, "pre-commit", NULL)) {
 698                rollback_index_files();
 699                return 1;
 700        }
 701
 702        if (!prepare_log_message(index_file, prefix) && !in_merge) {
 703                run_status(stdout, index_file, prefix);
 704                rollback_index_files();
 705                unlink(commit_editmsg);
 706                return 1;
 707        }
 708
 709        /*
 710         * Re-read the index as pre-commit hook could have updated it,
 711         * and write it out as a tree.
 712         */
 713        discard_cache();
 714        read_cache_from(index_file);
 715        if (!active_cache_tree)
 716                active_cache_tree = cache_tree();
 717        if (cache_tree_update(active_cache_tree,
 718                              active_cache, active_nr, 0, 0) < 0) {
 719                rollback_index_files();
 720                die("Error building trees");
 721        }
 722
 723        /*
 724         * The commit object
 725         */
 726        strbuf_init(&sb, 0);
 727        strbuf_addf(&sb, "tree %s\n",
 728                    sha1_to_hex(active_cache_tree->sha1));
 729
 730        /* Determine parents */
 731        if (initial_commit) {
 732                reflog_msg = "commit (initial)";
 733        } else if (amend) {
 734                struct commit_list *c;
 735                struct commit *commit;
 736
 737                reflog_msg = "commit (amend)";
 738                commit = lookup_commit(head_sha1);
 739                if (!commit || parse_commit(commit))
 740                        die("could not parse HEAD commit");
 741
 742                for (c = commit->parents; c; c = c->next)
 743                        strbuf_addf(&sb, "parent %s\n",
 744                                      sha1_to_hex(c->item->object.sha1));
 745        } else if (in_merge) {
 746                struct strbuf m;
 747                FILE *fp;
 748
 749                reflog_msg = "commit (merge)";
 750                strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
 751                strbuf_init(&m, 0);
 752                fp = fopen(git_path("MERGE_HEAD"), "r");
 753                if (fp == NULL)
 754                        die("could not open %s for reading: %s",
 755                            git_path("MERGE_HEAD"), strerror(errno));
 756                while (strbuf_getline(&m, fp, '\n') != EOF)
 757                        strbuf_addf(&sb, "parent %s\n", m.buf);
 758                fclose(fp);
 759                strbuf_release(&m);
 760        } else {
 761                reflog_msg = "commit";
 762                strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
 763        }
 764
 765        determine_author_info(&sb);
 766        strbuf_addf(&sb, "committer %s\n", git_committer_info(1));
 767        if (!is_encoding_utf8(git_commit_encoding))
 768                strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
 769        strbuf_addch(&sb, '\n');
 770
 771        /* Get the commit message and validate it */
 772        header_len = sb.len;
 773        if (!no_edit) {
 774                char index[PATH_MAX];
 775                const char *env[2] = { index, NULL };
 776                snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 777                launch_editor(git_path(commit_editmsg), &sb, env);
 778        } else if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
 779                rollback_index_files();
 780                die("could not read commit message\n");
 781        }
 782        if (run_hook(index_file, "commit-msg", git_path(commit_editmsg))) {
 783                rollback_index_files();
 784                exit(1);
 785        }
 786
 787        /* Truncate the message just before the diff, if any. */
 788        p = strstr(sb.buf, "\ndiff --git a/");
 789        if (p != NULL)
 790                strbuf_setlen(&sb, p - sb.buf + 1);
 791
 792        stripspace(&sb, 1);
 793        if (sb.len < header_len || message_is_empty(&sb, header_len)) {
 794                rollback_index_files();
 795                die("* no commit message?  aborting commit.");
 796        }
 797        strbuf_addch(&sb, '\0');
 798        if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
 799                fprintf(stderr, commit_utf8_warn);
 800
 801        if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) {
 802                rollback_index_files();
 803                die("failed to write commit object");
 804        }
 805
 806        ref_lock = lock_any_ref_for_update("HEAD",
 807                                           initial_commit ? NULL : head_sha1,
 808                                           0);
 809
 810        nl = strchr(sb.buf + header_len, '\n');
 811        if (nl)
 812                strbuf_setlen(&sb, nl + 1 - sb.buf);
 813        else
 814                strbuf_addch(&sb, '\n');
 815        strbuf_remove(&sb, 0, header_len);
 816        strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
 817        strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
 818
 819        if (!ref_lock) {
 820                rollback_index_files();
 821                die("cannot lock HEAD ref");
 822        }
 823        if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
 824                rollback_index_files();
 825                die("cannot update HEAD ref");
 826        }
 827
 828        unlink(git_path("MERGE_HEAD"));
 829        unlink(git_path("MERGE_MSG"));
 830
 831        commit_index_files();
 832
 833        rerere();
 834        run_hook(get_index_file(), "post-commit", NULL);
 835        if (!quiet)
 836                print_summary(prefix, commit_sha1);
 837
 838        return 0;
 839}