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