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