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