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