builtin-commit.con commit unpack-trees: allow Porcelain to give different error messages (8ccba00)
   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 char *author_name, *author_email, *author_date;
  51static int all, edit_flag, also, interactive, only, amend, signoff;
  52static int quiet, verbose, untracked_files, no_verify, allow_empty;
  53/*
  54 * The default commit message cleanup mode will remove the lines
  55 * beginning with # (shell comments) and leading and trailing
  56 * whitespaces (empty lines or containing only whitespaces)
  57 * if editor is used, and only the whitespaces if the message
  58 * is specified explicitly.
  59 */
  60static enum {
  61        CLEANUP_SPACE,
  62        CLEANUP_NONE,
  63        CLEANUP_ALL,
  64} cleanup_mode;
  65static char *cleanup_arg;
  66
  67static int use_editor = 1, initial_commit, in_merge;
  68const char *only_include_assumed;
  69struct strbuf message;
  70
  71static int opt_parse_m(const struct option *opt, const char *arg, int unset)
  72{
  73        struct strbuf *buf = opt->value;
  74        if (unset)
  75                strbuf_setlen(buf, 0);
  76        else {
  77                strbuf_addstr(buf, arg);
  78                strbuf_addch(buf, '\n');
  79                strbuf_addch(buf, '\n');
  80        }
  81        return 0;
  82}
  83
  84static struct option builtin_commit_options[] = {
  85        OPT__QUIET(&quiet),
  86        OPT__VERBOSE(&verbose),
  87        OPT_GROUP("Commit message options"),
  88
  89        OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
  90        OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
  91        OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
  92        OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
  93        OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
  94        OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
  95        OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
  96        OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
  97
  98        OPT_GROUP("Commit contents options"),
  99        OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
 100        OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
 101        OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
 102        OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
 103        OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
 104        OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
 105        OPT_BOOLEAN('u', "untracked-files", &untracked_files, "show all untracked files"),
 106        OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
 107        OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
 108
 109        OPT_END()
 110};
 111
 112static void rollback_index_files(void)
 113{
 114        switch (commit_style) {
 115        case COMMIT_AS_IS:
 116                break; /* nothing to do */
 117        case COMMIT_NORMAL:
 118                rollback_lock_file(&index_lock);
 119                break;
 120        case COMMIT_PARTIAL:
 121                rollback_lock_file(&index_lock);
 122                rollback_lock_file(&false_lock);
 123                break;
 124        }
 125}
 126
 127static int commit_index_files(void)
 128{
 129        int err = 0;
 130
 131        switch (commit_style) {
 132        case COMMIT_AS_IS:
 133                break; /* nothing to do */
 134        case COMMIT_NORMAL:
 135                err = commit_lock_file(&index_lock);
 136                break;
 137        case COMMIT_PARTIAL:
 138                err = commit_lock_file(&index_lock);
 139                rollback_lock_file(&false_lock);
 140                break;
 141        }
 142
 143        return err;
 144}
 145
 146/*
 147 * Take a union of paths in the index and the named tree (typically, "HEAD"),
 148 * and return the paths that match the given pattern in list.
 149 */
 150static int list_paths(struct path_list *list, const char *with_tree,
 151                      const char *prefix, const char **pattern)
 152{
 153        int i;
 154        char *m;
 155
 156        for (i = 0; pattern[i]; i++)
 157                ;
 158        m = xcalloc(1, i);
 159
 160        if (with_tree)
 161                overlay_tree_on_cache(with_tree, prefix);
 162
 163        for (i = 0; i < active_nr; i++) {
 164                struct cache_entry *ce = active_cache[i];
 165                if (ce->ce_flags & CE_UPDATE)
 166                        continue;
 167                if (!pathspec_match(pattern, m, ce->name, 0))
 168                        continue;
 169                path_list_insert(ce->name, list);
 170        }
 171
 172        return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
 173}
 174
 175static void add_remove_files(struct path_list *list)
 176{
 177        int i;
 178        for (i = 0; i < list->nr; i++) {
 179                struct stat st;
 180                struct path_list_item *p = &(list->items[i]);
 181
 182                if (!lstat(p->path, &st))
 183                        add_to_cache(p->path, &st, 0);
 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(0, also ? prefix : NULL, pathspec);
 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 void determine_author_info(void)
 402{
 403        char *name, *email, *date;
 404
 405        name = getenv("GIT_AUTHOR_NAME");
 406        email = getenv("GIT_AUTHOR_EMAIL");
 407        date = getenv("GIT_AUTHOR_DATE");
 408
 409        if (use_message) {
 410                const char *a, *lb, *rb, *eol;
 411
 412                a = strstr(use_message_buffer, "\nauthor ");
 413                if (!a)
 414                        die("invalid commit: %s", use_message);
 415
 416                lb = strstr(a + 8, " <");
 417                rb = strstr(a + 8, "> ");
 418                eol = strchr(a + 8, '\n');
 419                if (!lb || !rb || !eol)
 420                        die("invalid commit: %s", use_message);
 421
 422                name = xstrndup(a + 8, lb - (a + 8));
 423                email = xstrndup(lb + 2, rb - (lb + 2));
 424                date = xstrndup(rb + 2, eol - (rb + 2));
 425        }
 426
 427        if (force_author) {
 428                const char *lb = strstr(force_author, " <");
 429                const char *rb = strchr(force_author, '>');
 430
 431                if (!lb || !rb)
 432                        die("malformed --author parameter");
 433                name = xstrndup(force_author, lb - force_author);
 434                email = xstrndup(lb + 2, rb - (lb + 2));
 435        }
 436
 437        author_name = name;
 438        author_email = email;
 439        author_date = date;
 440}
 441
 442static int prepare_to_commit(const char *index_file, const char *prefix)
 443{
 444        struct stat statbuf;
 445        int commitable, saved_color_setting;
 446        struct strbuf sb;
 447        char *buffer;
 448        FILE *fp;
 449        const char *hook_arg1 = NULL;
 450        const char *hook_arg2 = NULL;
 451        int ident_shown = 0;
 452
 453        if (!no_verify && run_hook(index_file, "pre-commit", NULL))
 454                return 0;
 455
 456        strbuf_init(&sb, 0);
 457        if (message.len) {
 458                strbuf_addbuf(&sb, &message);
 459                hook_arg1 = "message";
 460        } else if (logfile && !strcmp(logfile, "-")) {
 461                if (isatty(0))
 462                        fprintf(stderr, "(reading log message from standard input)\n");
 463                if (strbuf_read(&sb, 0, 0) < 0)
 464                        die("could not read log from standard input");
 465                hook_arg1 = "message";
 466        } else if (logfile) {
 467                if (strbuf_read_file(&sb, logfile, 0) < 0)
 468                        die("could not read log file '%s': %s",
 469                            logfile, strerror(errno));
 470                hook_arg1 = "message";
 471        } else if (use_message) {
 472                buffer = strstr(use_message_buffer, "\n\n");
 473                if (!buffer || buffer[2] == '\0')
 474                        die("commit has empty message");
 475                strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
 476                hook_arg1 = "commit";
 477                hook_arg2 = use_message;
 478        } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
 479                if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
 480                        die("could not read MERGE_MSG: %s", strerror(errno));
 481                hook_arg1 = "merge";
 482        } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
 483                if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
 484                        die("could not read SQUASH_MSG: %s", strerror(errno));
 485                hook_arg1 = "squash";
 486        } else if (template_file && !stat(template_file, &statbuf)) {
 487                if (strbuf_read_file(&sb, template_file, 0) < 0)
 488                        die("could not read %s: %s",
 489                            template_file, strerror(errno));
 490                hook_arg1 = "template";
 491        }
 492
 493        /*
 494         * This final case does not modify the template message,
 495         * it just sets the argument to the prepare-commit-msg hook.
 496         */
 497        else if (in_merge)
 498                hook_arg1 = "merge";
 499
 500        fp = fopen(git_path(commit_editmsg), "w");
 501        if (fp == NULL)
 502                die("could not open %s", git_path(commit_editmsg));
 503
 504        if (cleanup_mode != CLEANUP_NONE)
 505                stripspace(&sb, 0);
 506
 507        if (signoff) {
 508                struct strbuf sob;
 509                int i;
 510
 511                strbuf_init(&sob, 0);
 512                strbuf_addstr(&sob, sign_off_header);
 513                strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
 514                                             getenv("GIT_COMMITTER_EMAIL")));
 515                strbuf_addch(&sob, '\n');
 516                for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
 517                        ; /* do nothing */
 518                if (prefixcmp(sb.buf + i, sob.buf)) {
 519                        if (prefixcmp(sb.buf + i, sign_off_header))
 520                                strbuf_addch(&sb, '\n');
 521                        strbuf_addbuf(&sb, &sob);
 522                }
 523                strbuf_release(&sob);
 524        }
 525
 526        if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
 527                die("could not write commit template: %s", strerror(errno));
 528
 529        strbuf_release(&sb);
 530
 531        determine_author_info();
 532
 533        /* This checks if committer ident is explicitly given */
 534        git_committer_info(0);
 535        if (use_editor) {
 536                char *author_ident;
 537                const char *committer_ident;
 538
 539                if (in_merge)
 540                        fprintf(fp,
 541                                "#\n"
 542                                "# It looks like you may be committing a MERGE.\n"
 543                                "# If this is not correct, please remove the file\n"
 544                                "#      %s\n"
 545                                "# and try again.\n"
 546                                "#\n",
 547                                git_path("MERGE_HEAD"));
 548
 549                fprintf(fp,
 550                        "\n"
 551                        "# Please enter the commit message for your changes.\n"
 552                        "# (Comment lines starting with '#' will ");
 553                if (cleanup_mode == CLEANUP_ALL)
 554                        fprintf(fp, "not be included)\n");
 555                else /* CLEANUP_SPACE, that is. */
 556                        fprintf(fp, "be kept.\n"
 557                                "# You can remove them yourself if you want to)\n");
 558                if (only_include_assumed)
 559                        fprintf(fp, "# %s\n", only_include_assumed);
 560
 561                author_ident = xstrdup(fmt_name(author_name, author_email));
 562                committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
 563                                           getenv("GIT_COMMITTER_EMAIL"));
 564                if (strcmp(author_ident, committer_ident))
 565                        fprintf(fp,
 566                                "%s"
 567                                "# Author:    %s\n",
 568                                ident_shown++ ? "" : "#\n",
 569                                author_ident);
 570                free(author_ident);
 571
 572                if (!user_ident_explicitly_given)
 573                        fprintf(fp,
 574                                "%s"
 575                                "# Committer: %s\n",
 576                                ident_shown++ ? "" : "#\n",
 577                                committer_ident);
 578
 579                if (ident_shown)
 580                        fprintf(fp, "#\n");
 581
 582                saved_color_setting = wt_status_use_color;
 583                wt_status_use_color = 0;
 584                commitable = run_status(fp, index_file, prefix, 1);
 585                wt_status_use_color = saved_color_setting;
 586        } else {
 587                struct rev_info rev;
 588                unsigned char sha1[20];
 589                const char *parent = "HEAD";
 590
 591                if (!active_nr && read_cache() < 0)
 592                        die("Cannot read index");
 593
 594                if (amend)
 595                        parent = "HEAD^1";
 596
 597                if (get_sha1(parent, sha1))
 598                        commitable = !!active_nr;
 599                else {
 600                        init_revisions(&rev, "");
 601                        rev.abbrev = 0;
 602                        setup_revisions(0, NULL, &rev, parent);
 603                        DIFF_OPT_SET(&rev.diffopt, QUIET);
 604                        DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
 605                        run_diff_index(&rev, 1 /* cached */);
 606
 607                        commitable = !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
 608                }
 609        }
 610
 611        fclose(fp);
 612
 613        if (!commitable && !in_merge && !allow_empty &&
 614            !(amend && is_a_merge(head_sha1))) {
 615                run_status(stdout, index_file, prefix, 0);
 616                unlink(commit_editmsg);
 617                return 0;
 618        }
 619
 620        /*
 621         * Re-read the index as pre-commit hook could have updated it,
 622         * and write it out as a tree.  We must do this before we invoke
 623         * the editor and after we invoke run_status above.
 624         */
 625        discard_cache();
 626        read_cache_from(index_file);
 627        if (!active_cache_tree)
 628                active_cache_tree = cache_tree();
 629        if (cache_tree_update(active_cache_tree,
 630                              active_cache, active_nr, 0, 0) < 0) {
 631                error("Error building trees");
 632                return 0;
 633        }
 634
 635        if (run_hook(index_file, "prepare-commit-msg",
 636                     git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
 637                return 0;
 638
 639        if (use_editor) {
 640                char index[PATH_MAX];
 641                const char *env[2] = { index, NULL };
 642                snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 643                launch_editor(git_path(commit_editmsg), NULL, env);
 644        }
 645
 646        if (!no_verify &&
 647            run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
 648                return 0;
 649        }
 650
 651        return 1;
 652}
 653
 654/*
 655 * Find out if the message starting at position 'start' in the strbuf
 656 * contains only whitespace and Signed-off-by lines.
 657 */
 658static int message_is_empty(struct strbuf *sb, int start)
 659{
 660        struct strbuf tmpl;
 661        const char *nl;
 662        int eol, i;
 663
 664        if (cleanup_mode == CLEANUP_NONE && sb->len)
 665                return 0;
 666
 667        /* See if the template is just a prefix of the message. */
 668        strbuf_init(&tmpl, 0);
 669        if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
 670                stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
 671                if (start + tmpl.len <= sb->len &&
 672                    memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
 673                        start += tmpl.len;
 674        }
 675        strbuf_release(&tmpl);
 676
 677        /* Check if the rest is just whitespace and Signed-of-by's. */
 678        for (i = start; i < sb->len; i++) {
 679                nl = memchr(sb->buf + i, '\n', sb->len - i);
 680                if (nl)
 681                        eol = nl - sb->buf;
 682                else
 683                        eol = sb->len;
 684
 685                if (strlen(sign_off_header) <= eol - i &&
 686                    !prefixcmp(sb->buf + i, sign_off_header)) {
 687                        i = eol;
 688                        continue;
 689                }
 690                while (i < eol)
 691                        if (!isspace(sb->buf[i++]))
 692                                return 0;
 693        }
 694
 695        return 1;
 696}
 697
 698static int parse_and_validate_options(int argc, const char *argv[],
 699                                      const char * const usage[])
 700{
 701        int f = 0;
 702
 703        argc = parse_options(argc, argv, builtin_commit_options, usage, 0);
 704
 705        if (logfile || message.len || use_message)
 706                use_editor = 0;
 707        if (edit_flag)
 708                use_editor = 1;
 709        if (!use_editor)
 710                setenv("GIT_EDITOR", ":", 1);
 711
 712        if (get_sha1("HEAD", head_sha1))
 713                initial_commit = 1;
 714
 715        if (!get_sha1("MERGE_HEAD", merge_head_sha1))
 716                in_merge = 1;
 717
 718        /* Sanity check options */
 719        if (amend && initial_commit)
 720                die("You have nothing to amend.");
 721        if (amend && in_merge)
 722                die("You are in the middle of a merge -- cannot amend.");
 723
 724        if (use_message)
 725                f++;
 726        if (edit_message)
 727                f++;
 728        if (logfile)
 729                f++;
 730        if (f > 1)
 731                die("Only one of -c/-C/-F can be used.");
 732        if (message.len && f > 0)
 733                die("Option -m cannot be combined with -c/-C/-F.");
 734        if (edit_message)
 735                use_message = edit_message;
 736        if (amend && !use_message)
 737                use_message = "HEAD";
 738        if (use_message) {
 739                unsigned char sha1[20];
 740                static char utf8[] = "UTF-8";
 741                const char *out_enc;
 742                char *enc, *end;
 743                struct commit *commit;
 744
 745                if (get_sha1(use_message, sha1))
 746                        die("could not lookup commit %s", use_message);
 747                commit = lookup_commit_reference(sha1);
 748                if (!commit || parse_commit(commit))
 749                        die("could not parse commit %s", use_message);
 750
 751                enc = strstr(commit->buffer, "\nencoding");
 752                if (enc) {
 753                        end = strchr(enc + 10, '\n');
 754                        enc = xstrndup(enc + 10, end - (enc + 10));
 755                } else {
 756                        enc = utf8;
 757                }
 758                out_enc = git_commit_encoding ? git_commit_encoding : utf8;
 759
 760                if (strcmp(out_enc, enc))
 761                        use_message_buffer =
 762                                reencode_string(commit->buffer, out_enc, enc);
 763
 764                /*
 765                 * If we failed to reencode the buffer, just copy it
 766                 * byte for byte so the user can try to fix it up.
 767                 * This also handles the case where input and output
 768                 * encodings are identical.
 769                 */
 770                if (use_message_buffer == NULL)
 771                        use_message_buffer = xstrdup(commit->buffer);
 772                if (enc != utf8)
 773                        free(enc);
 774        }
 775
 776        if (!!also + !!only + !!all + !!interactive > 1)
 777                die("Only one of --include/--only/--all/--interactive can be used.");
 778        if (argc == 0 && (also || (only && !amend)))
 779                die("No paths with --include/--only does not make sense.");
 780        if (argc == 0 && only && amend)
 781                only_include_assumed = "Clever... amending the last one with dirty index.";
 782        if (argc > 0 && !also && !only)
 783                only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
 784        if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
 785                cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
 786        else if (!strcmp(cleanup_arg, "verbatim"))
 787                cleanup_mode = CLEANUP_NONE;
 788        else if (!strcmp(cleanup_arg, "whitespace"))
 789                cleanup_mode = CLEANUP_SPACE;
 790        else if (!strcmp(cleanup_arg, "strip"))
 791                cleanup_mode = CLEANUP_ALL;
 792        else
 793                die("Invalid cleanup mode %s", cleanup_arg);
 794
 795        if (all && argc > 0)
 796                die("Paths with -a does not make sense.");
 797        else if (interactive && argc > 0)
 798                die("Paths with --interactive does not make sense.");
 799
 800        return argc;
 801}
 802
 803int cmd_status(int argc, const char **argv, const char *prefix)
 804{
 805        const char *index_file;
 806        int commitable;
 807
 808        git_config(git_status_config);
 809
 810        if (wt_status_use_color == -1)
 811                wt_status_use_color = git_use_color_default;
 812
 813        argc = parse_and_validate_options(argc, argv, builtin_status_usage);
 814
 815        index_file = prepare_index(argc, argv, prefix);
 816
 817        commitable = run_status(stdout, index_file, prefix, 0);
 818
 819        rollback_index_files();
 820
 821        return commitable ? 0 : 1;
 822}
 823
 824static void print_summary(const char *prefix, const unsigned char *sha1)
 825{
 826        struct rev_info rev;
 827        struct commit *commit;
 828
 829        commit = lookup_commit(sha1);
 830        if (!commit)
 831                die("couldn't look up newly created commit");
 832        if (!commit || parse_commit(commit))
 833                die("could not parse newly created commit");
 834
 835        init_revisions(&rev, prefix);
 836        setup_revisions(0, NULL, &rev, NULL);
 837
 838        rev.abbrev = 0;
 839        rev.diff = 1;
 840        rev.diffopt.output_format =
 841                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
 842
 843        rev.verbose_header = 1;
 844        rev.show_root_diff = 1;
 845        get_commit_format("format:%h: %s", &rev);
 846        rev.always_show_header = 0;
 847        rev.diffopt.detect_rename = 1;
 848        rev.diffopt.rename_limit = 100;
 849        rev.diffopt.break_opt = 0;
 850        diff_setup_done(&rev.diffopt);
 851
 852        printf("Created %scommit ", initial_commit ? "initial " : "");
 853
 854        if (!log_tree_commit(&rev, commit)) {
 855                struct strbuf buf = STRBUF_INIT;
 856                format_commit_message(commit, "%h: %s", &buf);
 857                printf("%s\n", buf.buf);
 858                strbuf_release(&buf);
 859        }
 860}
 861
 862int git_commit_config(const char *k, const char *v)
 863{
 864        if (!strcmp(k, "commit.template")) {
 865                if (!v)
 866                        return config_error_nonbool(v);
 867                template_file = xstrdup(v);
 868                return 0;
 869        }
 870
 871        return git_status_config(k, v);
 872}
 873
 874static const char commit_utf8_warn[] =
 875"Warning: commit message does not conform to UTF-8.\n"
 876"You may want to amend it after fixing the message, or set the config\n"
 877"variable i18n.commitencoding to the encoding your project uses.\n";
 878
 879static void add_parent(struct strbuf *sb, const unsigned char *sha1)
 880{
 881        struct object *obj = parse_object(sha1);
 882        const char *parent = sha1_to_hex(sha1);
 883        if (!obj)
 884                die("Unable to find commit parent %s", parent);
 885        if (obj->type != OBJ_COMMIT)
 886                die("Parent %s isn't a proper commit", parent);
 887        strbuf_addf(sb, "parent %s\n", parent);
 888}
 889
 890int cmd_commit(int argc, const char **argv, const char *prefix)
 891{
 892        int header_len;
 893        struct strbuf sb;
 894        const char *index_file, *reflog_msg;
 895        char *nl, *p;
 896        unsigned char commit_sha1[20];
 897        struct ref_lock *ref_lock;
 898
 899        git_config(git_commit_config);
 900
 901        argc = parse_and_validate_options(argc, argv, builtin_commit_usage);
 902
 903        index_file = prepare_index(argc, argv, prefix);
 904
 905        /* Set up everything for writing the commit object.  This includes
 906           running hooks, writing the trees, and interacting with the user.  */
 907        if (!prepare_to_commit(index_file, prefix)) {
 908                rollback_index_files();
 909                return 1;
 910        }
 911
 912        /*
 913         * The commit object
 914         */
 915        strbuf_init(&sb, 0);
 916        strbuf_addf(&sb, "tree %s\n",
 917                    sha1_to_hex(active_cache_tree->sha1));
 918
 919        /* Determine parents */
 920        if (initial_commit) {
 921                reflog_msg = "commit (initial)";
 922        } else if (amend) {
 923                struct commit_list *c;
 924                struct commit *commit;
 925
 926                reflog_msg = "commit (amend)";
 927                commit = lookup_commit(head_sha1);
 928                if (!commit || parse_commit(commit))
 929                        die("could not parse HEAD commit");
 930
 931                for (c = commit->parents; c; c = c->next)
 932                        add_parent(&sb, c->item->object.sha1);
 933        } else if (in_merge) {
 934                struct strbuf m;
 935                FILE *fp;
 936
 937                reflog_msg = "commit (merge)";
 938                add_parent(&sb, head_sha1);
 939                strbuf_init(&m, 0);
 940                fp = fopen(git_path("MERGE_HEAD"), "r");
 941                if (fp == NULL)
 942                        die("could not open %s for reading: %s",
 943                            git_path("MERGE_HEAD"), strerror(errno));
 944                while (strbuf_getline(&m, fp, '\n') != EOF) {
 945                        unsigned char sha1[20];
 946                        if (get_sha1_hex(m.buf, sha1) < 0)
 947                                die("Corrupt MERGE_HEAD file (%s)", m.buf);
 948                        add_parent(&sb, sha1);
 949                }
 950                fclose(fp);
 951                strbuf_release(&m);
 952        } else {
 953                reflog_msg = "commit";
 954                strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
 955        }
 956
 957        strbuf_addf(&sb, "author %s\n",
 958                    fmt_ident(author_name, author_email, author_date, IDENT_ERROR_ON_NO_NAME));
 959        strbuf_addf(&sb, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME));
 960        if (!is_encoding_utf8(git_commit_encoding))
 961                strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
 962        strbuf_addch(&sb, '\n');
 963
 964        /* Finally, get the commit message */
 965        header_len = sb.len;
 966        if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
 967                rollback_index_files();
 968                die("could not read commit message");
 969        }
 970
 971        /* Truncate the message just before the diff, if any. */
 972        p = strstr(sb.buf, "\ndiff --git a/");
 973        if (p != NULL)
 974                strbuf_setlen(&sb, p - sb.buf + 1);
 975
 976        if (cleanup_mode != CLEANUP_NONE)
 977                stripspace(&sb, cleanup_mode == CLEANUP_ALL);
 978        if (sb.len < header_len || message_is_empty(&sb, header_len)) {
 979                rollback_index_files();
 980                die("no commit message?  aborting commit.");
 981        }
 982        strbuf_addch(&sb, '\0');
 983        if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
 984                fprintf(stderr, commit_utf8_warn);
 985
 986        if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) {
 987                rollback_index_files();
 988                die("failed to write commit object");
 989        }
 990
 991        ref_lock = lock_any_ref_for_update("HEAD",
 992                                           initial_commit ? NULL : head_sha1,
 993                                           0);
 994
 995        nl = strchr(sb.buf + header_len, '\n');
 996        if (nl)
 997                strbuf_setlen(&sb, nl + 1 - sb.buf);
 998        else
 999                strbuf_addch(&sb, '\n');
1000        strbuf_remove(&sb, 0, header_len);
1001        strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1002        strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1003
1004        if (!ref_lock) {
1005                rollback_index_files();
1006                die("cannot lock HEAD ref");
1007        }
1008        if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1009                rollback_index_files();
1010                die("cannot update HEAD ref");
1011        }
1012
1013        unlink(git_path("MERGE_HEAD"));
1014        unlink(git_path("MERGE_MSG"));
1015        unlink(git_path("SQUASH_MSG"));
1016
1017        if (commit_index_files())
1018                die ("Repository has been updated, but unable to write\n"
1019                     "new_index file. Check that disk is not full or quota is\n"
1020                     "not exceeded, and then \"git reset HEAD\" to recover.");
1021
1022        rerere();
1023        run_hook(get_index_file(), "post-commit", NULL);
1024        if (!quiet)
1025                print_summary(prefix, commit_sha1);
1026
1027        return 0;
1028}