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