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