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