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