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