builtin-commit.con commit Merge branch 'maint' (9e7ad09)
   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 "string-list.h"
  25#include "rerere.h"
  26#include "unpack-trees.h"
  27#include "quote.h"
  28
  29static const char * const builtin_commit_usage[] = {
  30        "git commit [options] [--] <filepattern>...",
  31        NULL
  32};
  33
  34static const char * const builtin_status_usage[] = {
  35        "git status [options] [--] <filepattern>...",
  36        NULL
  37};
  38
  39static unsigned char head_sha1[20];
  40static char *use_message_buffer;
  41static const char commit_editmsg[] = "COMMIT_EDITMSG";
  42static struct lock_file index_lock; /* real index */
  43static struct lock_file false_lock; /* used only for partial commits */
  44static enum {
  45        COMMIT_AS_IS = 1,
  46        COMMIT_NORMAL,
  47        COMMIT_PARTIAL,
  48} commit_style;
  49
  50static const char *logfile, *force_author;
  51static const char *template_file;
  52static char *edit_message, *use_message;
  53static char *author_name, *author_email, *author_date;
  54static int all, edit_flag, also, interactive, only, amend, signoff;
  55static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
  56static char *untracked_files_arg;
  57/*
  58 * The default commit message cleanup mode will remove the lines
  59 * beginning with # (shell comments) and leading and trailing
  60 * whitespaces (empty lines or containing only whitespaces)
  61 * if editor is used, and only the whitespaces if the message
  62 * is specified explicitly.
  63 */
  64static enum {
  65        CLEANUP_SPACE,
  66        CLEANUP_NONE,
  67        CLEANUP_ALL,
  68} cleanup_mode;
  69static char *cleanup_arg;
  70
  71static int use_editor = 1, initial_commit, in_merge;
  72static const char *only_include_assumed;
  73static struct strbuf message;
  74
  75static int null_termination;
  76static enum {
  77        STATUS_FORMAT_LONG,
  78        STATUS_FORMAT_SHORT,
  79        STATUS_FORMAT_PORCELAIN,
  80} status_format = STATUS_FORMAT_LONG;
  81
  82static int opt_parse_m(const struct option *opt, const char *arg, int unset)
  83{
  84        struct strbuf *buf = opt->value;
  85        if (unset)
  86                strbuf_setlen(buf, 0);
  87        else {
  88                strbuf_addstr(buf, arg);
  89                strbuf_addstr(buf, "\n\n");
  90        }
  91        return 0;
  92}
  93
  94static struct option builtin_commit_options[] = {
  95        OPT__QUIET(&quiet),
  96        OPT__VERBOSE(&verbose),
  97
  98        OPT_GROUP("Commit message options"),
  99        OPT_FILENAME('F', "file", &logfile, "read log from file"),
 100        OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
 101        OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
 102        OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
 103        OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
 104        OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
 105        OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
 106        OPT_FILENAME('t', "template", &template_file, "use specified template file"),
 107        OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
 108        OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
 109        /* end commit message options */
 110
 111        OPT_GROUP("Commit contents options"),
 112        OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
 113        OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
 114        OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
 115        OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
 116        OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
 117        OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
 118        OPT_SET_INT(0, "short", &status_format, "show status concisely",
 119                    STATUS_FORMAT_SHORT),
 120        OPT_SET_INT(0, "porcelain", &status_format,
 121                    "show porcelain output format", STATUS_FORMAT_PORCELAIN),
 122        OPT_BOOLEAN('z', "null", &null_termination,
 123                    "terminate entries with NUL"),
 124        OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
 125        { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, "mode", "show untracked files, optional modes: all, normal, no. (Default: all)", PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
 126        OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
 127        /* end commit contents options */
 128
 129        OPT_END()
 130};
 131
 132static void rollback_index_files(void)
 133{
 134        switch (commit_style) {
 135        case COMMIT_AS_IS:
 136                break; /* nothing to do */
 137        case COMMIT_NORMAL:
 138                rollback_lock_file(&index_lock);
 139                break;
 140        case COMMIT_PARTIAL:
 141                rollback_lock_file(&index_lock);
 142                rollback_lock_file(&false_lock);
 143                break;
 144        }
 145}
 146
 147static int commit_index_files(void)
 148{
 149        int err = 0;
 150
 151        switch (commit_style) {
 152        case COMMIT_AS_IS:
 153                break; /* nothing to do */
 154        case COMMIT_NORMAL:
 155                err = commit_lock_file(&index_lock);
 156                break;
 157        case COMMIT_PARTIAL:
 158                err = commit_lock_file(&index_lock);
 159                rollback_lock_file(&false_lock);
 160                break;
 161        }
 162
 163        return err;
 164}
 165
 166/*
 167 * Take a union of paths in the index and the named tree (typically, "HEAD"),
 168 * and return the paths that match the given pattern in list.
 169 */
 170static int list_paths(struct string_list *list, const char *with_tree,
 171                      const char *prefix, const char **pattern)
 172{
 173        int i;
 174        char *m;
 175
 176        for (i = 0; pattern[i]; i++)
 177                ;
 178        m = xcalloc(1, i);
 179
 180        if (with_tree)
 181                overlay_tree_on_cache(with_tree, prefix);
 182
 183        for (i = 0; i < active_nr; i++) {
 184                struct cache_entry *ce = active_cache[i];
 185                if (ce->ce_flags & CE_UPDATE)
 186                        continue;
 187                if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
 188                        continue;
 189                string_list_insert(ce->name, list);
 190        }
 191
 192        return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
 193}
 194
 195static void add_remove_files(struct string_list *list)
 196{
 197        int i;
 198        for (i = 0; i < list->nr; i++) {
 199                struct stat st;
 200                struct string_list_item *p = &(list->items[i]);
 201
 202                if (!lstat(p->string, &st)) {
 203                        if (add_to_cache(p->string, &st, 0))
 204                                die("updating files failed");
 205                } else
 206                        remove_file_from_cache(p->string);
 207        }
 208}
 209
 210static void create_base_index(void)
 211{
 212        struct tree *tree;
 213        struct unpack_trees_options opts;
 214        struct tree_desc t;
 215
 216        if (initial_commit) {
 217                discard_cache();
 218                return;
 219        }
 220
 221        memset(&opts, 0, sizeof(opts));
 222        opts.head_idx = 1;
 223        opts.index_only = 1;
 224        opts.merge = 1;
 225        opts.src_index = &the_index;
 226        opts.dst_index = &the_index;
 227
 228        opts.fn = oneway_merge;
 229        tree = parse_tree_indirect(head_sha1);
 230        if (!tree)
 231                die("failed to unpack HEAD tree object");
 232        parse_tree(tree);
 233        init_tree_desc(&t, tree->buffer, tree->size);
 234        if (unpack_trees(1, &t, &opts))
 235                exit(128); /* We've already reported the error, finish dying */
 236}
 237
 238static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
 239{
 240        int fd;
 241        struct string_list partial;
 242        const char **pathspec = NULL;
 243        int refresh_flags = REFRESH_QUIET;
 244
 245        if (is_status)
 246                refresh_flags |= REFRESH_UNMERGED;
 247        if (interactive) {
 248                if (interactive_add(argc, argv, prefix) != 0)
 249                        die("interactive add failed");
 250                if (read_cache_preload(NULL) < 0)
 251                        die("index file corrupt");
 252                commit_style = COMMIT_AS_IS;
 253                return get_index_file();
 254        }
 255
 256        if (*argv)
 257                pathspec = get_pathspec(prefix, argv);
 258
 259        if (read_cache_preload(pathspec) < 0)
 260                die("index file corrupt");
 261
 262        /*
 263         * Non partial, non as-is commit.
 264         *
 265         * (1) get the real index;
 266         * (2) update the_index as necessary;
 267         * (3) write the_index out to the real index (still locked);
 268         * (4) return the name of the locked index file.
 269         *
 270         * The caller should run hooks on the locked real index, and
 271         * (A) if all goes well, commit the real index;
 272         * (B) on failure, rollback the real index.
 273         */
 274        if (all || (also && pathspec && *pathspec)) {
 275                int fd = hold_locked_index(&index_lock, 1);
 276                add_files_to_cache(also ? prefix : NULL, pathspec, 0);
 277                refresh_cache(refresh_flags);
 278                if (write_cache(fd, active_cache, active_nr) ||
 279                    close_lock_file(&index_lock))
 280                        die("unable to write new_index file");
 281                commit_style = COMMIT_NORMAL;
 282                return index_lock.filename;
 283        }
 284
 285        /*
 286         * As-is commit.
 287         *
 288         * (1) return the name of the real index file.
 289         *
 290         * The caller should run hooks on the real index, and run
 291         * hooks on the real index, and create commit from the_index.
 292         * We still need to refresh the index here.
 293         */
 294        if (!pathspec || !*pathspec) {
 295                fd = hold_locked_index(&index_lock, 1);
 296                refresh_cache(refresh_flags);
 297                if (write_cache(fd, active_cache, active_nr) ||
 298                    commit_locked_index(&index_lock))
 299                        die("unable to write new_index file");
 300                commit_style = COMMIT_AS_IS;
 301                return get_index_file();
 302        }
 303
 304        /*
 305         * A partial commit.
 306         *
 307         * (0) find the set of affected paths;
 308         * (1) get lock on the real index file;
 309         * (2) update the_index with the given paths;
 310         * (3) write the_index out to the real index (still locked);
 311         * (4) get lock on the false index file;
 312         * (5) reset the_index from HEAD;
 313         * (6) update the_index the same way as (2);
 314         * (7) write the_index out to the false index file;
 315         * (8) return the name of the false index file (still locked);
 316         *
 317         * The caller should run hooks on the locked false index, and
 318         * create commit from it.  Then
 319         * (A) if all goes well, commit the real index;
 320         * (B) on failure, rollback the real index;
 321         * In either case, rollback the false index.
 322         */
 323        commit_style = COMMIT_PARTIAL;
 324
 325        if (in_merge)
 326                die("cannot do a partial commit during a merge.");
 327
 328        memset(&partial, 0, sizeof(partial));
 329        partial.strdup_strings = 1;
 330        if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
 331                exit(1);
 332
 333        discard_cache();
 334        if (read_cache() < 0)
 335                die("cannot read the index");
 336
 337        fd = hold_locked_index(&index_lock, 1);
 338        add_remove_files(&partial);
 339        refresh_cache(REFRESH_QUIET);
 340        if (write_cache(fd, active_cache, active_nr) ||
 341            close_lock_file(&index_lock))
 342                die("unable to write new_index file");
 343
 344        fd = hold_lock_file_for_update(&false_lock,
 345                                       git_path("next-index-%"PRIuMAX,
 346                                                (uintmax_t) getpid()),
 347                                       LOCK_DIE_ON_ERROR);
 348
 349        create_base_index();
 350        add_remove_files(&partial);
 351        refresh_cache(REFRESH_QUIET);
 352
 353        if (write_cache(fd, active_cache, active_nr) ||
 354            close_lock_file(&false_lock))
 355                die("unable to write temporary index file");
 356
 357        discard_cache();
 358        read_cache_from(false_lock.filename);
 359
 360        return false_lock.filename;
 361}
 362
 363static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
 364                      struct wt_status *s)
 365{
 366        unsigned char sha1[20];
 367
 368        if (s->relative_paths)
 369                s->prefix = prefix;
 370
 371        if (amend) {
 372                s->amend = 1;
 373                s->reference = "HEAD^1";
 374        }
 375        s->verbose = verbose;
 376        s->index_file = index_file;
 377        s->fp = fp;
 378        s->nowarn = nowarn;
 379        s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
 380
 381        wt_status_collect(s);
 382
 383        switch (status_format) {
 384        case STATUS_FORMAT_SHORT:
 385                wt_shortstatus_print(s, null_termination);
 386                break;
 387        case STATUS_FORMAT_PORCELAIN:
 388                wt_porcelain_print(s, null_termination);
 389                break;
 390        case STATUS_FORMAT_LONG:
 391                wt_status_print(s);
 392                break;
 393        }
 394
 395        return s->commitable;
 396}
 397
 398static int is_a_merge(const unsigned char *sha1)
 399{
 400        struct commit *commit = lookup_commit(sha1);
 401        if (!commit || parse_commit(commit))
 402                die("could not parse HEAD commit");
 403        return !!(commit->parents && commit->parents->next);
 404}
 405
 406static const char sign_off_header[] = "Signed-off-by: ";
 407
 408static void determine_author_info(void)
 409{
 410        char *name, *email, *date;
 411
 412        name = getenv("GIT_AUTHOR_NAME");
 413        email = getenv("GIT_AUTHOR_EMAIL");
 414        date = getenv("GIT_AUTHOR_DATE");
 415
 416        if (use_message && !renew_authorship) {
 417                const char *a, *lb, *rb, *eol;
 418
 419                a = strstr(use_message_buffer, "\nauthor ");
 420                if (!a)
 421                        die("invalid commit: %s", use_message);
 422
 423                lb = strstr(a + 8, " <");
 424                rb = strstr(a + 8, "> ");
 425                eol = strchr(a + 8, '\n');
 426                if (!lb || !rb || !eol)
 427                        die("invalid commit: %s", use_message);
 428
 429                name = xstrndup(a + 8, lb - (a + 8));
 430                email = xstrndup(lb + 2, rb - (lb + 2));
 431                date = xstrndup(rb + 2, eol - (rb + 2));
 432        }
 433
 434        if (force_author) {
 435                const char *lb = strstr(force_author, " <");
 436                const char *rb = strchr(force_author, '>');
 437
 438                if (!lb || !rb)
 439                        die("malformed --author parameter");
 440                name = xstrndup(force_author, lb - force_author);
 441                email = xstrndup(lb + 2, rb - (lb + 2));
 442        }
 443
 444        author_name = name;
 445        author_email = email;
 446        author_date = date;
 447}
 448
 449static int ends_rfc2822_footer(struct strbuf *sb)
 450{
 451        int ch;
 452        int hit = 0;
 453        int i, j, k;
 454        int len = sb->len;
 455        int first = 1;
 456        const char *buf = sb->buf;
 457
 458        for (i = len - 1; i > 0; i--) {
 459                if (hit && buf[i] == '\n')
 460                        break;
 461                hit = (buf[i] == '\n');
 462        }
 463
 464        while (i < len - 1 && buf[i] == '\n')
 465                i++;
 466
 467        for (; i < len; i = k) {
 468                for (k = i; k < len && buf[k] != '\n'; k++)
 469                        ; /* do nothing */
 470                k++;
 471
 472                if ((buf[k] == ' ' || buf[k] == '\t') && !first)
 473                        continue;
 474
 475                first = 0;
 476
 477                for (j = 0; i + j < len; j++) {
 478                        ch = buf[i + j];
 479                        if (ch == ':')
 480                                break;
 481                        if (isalnum(ch) ||
 482                            (ch == '-'))
 483                                continue;
 484                        return 0;
 485                }
 486        }
 487        return 1;
 488}
 489
 490static int prepare_to_commit(const char *index_file, const char *prefix,
 491                             struct wt_status *s)
 492{
 493        struct stat statbuf;
 494        int commitable, saved_color_setting;
 495        struct strbuf sb = STRBUF_INIT;
 496        char *buffer;
 497        FILE *fp;
 498        const char *hook_arg1 = NULL;
 499        const char *hook_arg2 = NULL;
 500        int ident_shown = 0;
 501
 502        if (!no_verify && run_hook(index_file, "pre-commit", NULL))
 503                return 0;
 504
 505        if (message.len) {
 506                strbuf_addbuf(&sb, &message);
 507                hook_arg1 = "message";
 508        } else if (logfile && !strcmp(logfile, "-")) {
 509                if (isatty(0))
 510                        fprintf(stderr, "(reading log message from standard input)\n");
 511                if (strbuf_read(&sb, 0, 0) < 0)
 512                        die_errno("could not read log from standard input");
 513                hook_arg1 = "message";
 514        } else if (logfile) {
 515                if (strbuf_read_file(&sb, logfile, 0) < 0)
 516                        die_errno("could not read log file '%s'",
 517                                  logfile);
 518                hook_arg1 = "message";
 519        } else if (use_message) {
 520                buffer = strstr(use_message_buffer, "\n\n");
 521                if (!buffer || buffer[2] == '\0')
 522                        die("commit has empty message");
 523                strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
 524                hook_arg1 = "commit";
 525                hook_arg2 = use_message;
 526        } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
 527                if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
 528                        die_errno("could not read MERGE_MSG");
 529                hook_arg1 = "merge";
 530        } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
 531                if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
 532                        die_errno("could not read SQUASH_MSG");
 533                hook_arg1 = "squash";
 534        } else if (template_file && !stat(template_file, &statbuf)) {
 535                if (strbuf_read_file(&sb, template_file, 0) < 0)
 536                        die_errno("could not read '%s'", template_file);
 537                hook_arg1 = "template";
 538        }
 539
 540        /*
 541         * This final case does not modify the template message,
 542         * it just sets the argument to the prepare-commit-msg hook.
 543         */
 544        else if (in_merge)
 545                hook_arg1 = "merge";
 546
 547        fp = fopen(git_path(commit_editmsg), "w");
 548        if (fp == NULL)
 549                die_errno("could not open '%s'", git_path(commit_editmsg));
 550
 551        if (cleanup_mode != CLEANUP_NONE)
 552                stripspace(&sb, 0);
 553
 554        if (signoff) {
 555                struct strbuf sob = STRBUF_INIT;
 556                int i;
 557
 558                strbuf_addstr(&sob, sign_off_header);
 559                strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
 560                                             getenv("GIT_COMMITTER_EMAIL")));
 561                strbuf_addch(&sob, '\n');
 562                for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
 563                        ; /* do nothing */
 564                if (prefixcmp(sb.buf + i, sob.buf)) {
 565                        if (!i || !ends_rfc2822_footer(&sb))
 566                                strbuf_addch(&sb, '\n');
 567                        strbuf_addbuf(&sb, &sob);
 568                }
 569                strbuf_release(&sob);
 570        }
 571
 572        if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
 573                die_errno("could not write commit template");
 574
 575        strbuf_release(&sb);
 576
 577        determine_author_info();
 578
 579        /* This checks if committer ident is explicitly given */
 580        git_committer_info(0);
 581        if (use_editor) {
 582                char *author_ident;
 583                const char *committer_ident;
 584
 585                if (in_merge)
 586                        fprintf(fp,
 587                                "#\n"
 588                                "# It looks like you may be committing a MERGE.\n"
 589                                "# If this is not correct, please remove the file\n"
 590                                "#      %s\n"
 591                                "# and try again.\n"
 592                                "#\n",
 593                                git_path("MERGE_HEAD"));
 594
 595                fprintf(fp,
 596                        "\n"
 597                        "# Please enter the commit message for your changes.");
 598                if (cleanup_mode == CLEANUP_ALL)
 599                        fprintf(fp,
 600                                " Lines starting\n"
 601                                "# with '#' will be ignored, and an empty"
 602                                " message aborts the commit.\n");
 603                else /* CLEANUP_SPACE, that is. */
 604                        fprintf(fp,
 605                                " Lines starting\n"
 606                                "# with '#' will be kept; you may remove them"
 607                                " yourself if you want to.\n"
 608                                "# An empty message aborts the commit.\n");
 609                if (only_include_assumed)
 610                        fprintf(fp, "# %s\n", only_include_assumed);
 611
 612                author_ident = xstrdup(fmt_name(author_name, author_email));
 613                committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
 614                                           getenv("GIT_COMMITTER_EMAIL"));
 615                if (strcmp(author_ident, committer_ident))
 616                        fprintf(fp,
 617                                "%s"
 618                                "# Author:    %s\n",
 619                                ident_shown++ ? "" : "#\n",
 620                                author_ident);
 621                free(author_ident);
 622
 623                if (!user_ident_explicitly_given)
 624                        fprintf(fp,
 625                                "%s"
 626                                "# Committer: %s\n",
 627                                ident_shown++ ? "" : "#\n",
 628                                committer_ident);
 629
 630                if (ident_shown)
 631                        fprintf(fp, "#\n");
 632
 633                saved_color_setting = s->use_color;
 634                s->use_color = 0;
 635                commitable = run_status(fp, index_file, prefix, 1, s);
 636                s->use_color = saved_color_setting;
 637        } else {
 638                unsigned char sha1[20];
 639                const char *parent = "HEAD";
 640
 641                if (!active_nr && read_cache() < 0)
 642                        die("Cannot read index");
 643
 644                if (amend)
 645                        parent = "HEAD^1";
 646
 647                if (get_sha1(parent, sha1))
 648                        commitable = !!active_nr;
 649                else
 650                        commitable = index_differs_from(parent, 0);
 651        }
 652
 653        fclose(fp);
 654
 655        if (!commitable && !in_merge && !allow_empty &&
 656            !(amend && is_a_merge(head_sha1))) {
 657                run_status(stdout, index_file, prefix, 0, s);
 658                return 0;
 659        }
 660
 661        /*
 662         * Re-read the index as pre-commit hook could have updated it,
 663         * and write it out as a tree.  We must do this before we invoke
 664         * the editor and after we invoke run_status above.
 665         */
 666        discard_cache();
 667        read_cache_from(index_file);
 668        if (!active_cache_tree)
 669                active_cache_tree = cache_tree();
 670        if (cache_tree_update(active_cache_tree,
 671                              active_cache, active_nr, 0, 0) < 0) {
 672                error("Error building trees");
 673                return 0;
 674        }
 675
 676        if (run_hook(index_file, "prepare-commit-msg",
 677                     git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
 678                return 0;
 679
 680        if (use_editor) {
 681                char index[PATH_MAX];
 682                const char *env[2] = { index, NULL };
 683                snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 684                if (launch_editor(git_path(commit_editmsg), NULL, env)) {
 685                        fprintf(stderr,
 686                        "Please supply the message using either -m or -F option.\n");
 687                        exit(1);
 688                }
 689        }
 690
 691        if (!no_verify &&
 692            run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
 693                return 0;
 694        }
 695
 696        return 1;
 697}
 698
 699/*
 700 * Find out if the message in the strbuf contains only whitespace and
 701 * Signed-off-by lines.
 702 */
 703static int message_is_empty(struct strbuf *sb)
 704{
 705        struct strbuf tmpl = STRBUF_INIT;
 706        const char *nl;
 707        int eol, i, start = 0;
 708
 709        if (cleanup_mode == CLEANUP_NONE && sb->len)
 710                return 0;
 711
 712        /* See if the template is just a prefix of the message. */
 713        if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
 714                stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
 715                if (start + tmpl.len <= sb->len &&
 716                    memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
 717                        start += tmpl.len;
 718        }
 719        strbuf_release(&tmpl);
 720
 721        /* Check if the rest is just whitespace and Signed-of-by's. */
 722        for (i = start; i < sb->len; i++) {
 723                nl = memchr(sb->buf + i, '\n', sb->len - i);
 724                if (nl)
 725                        eol = nl - sb->buf;
 726                else
 727                        eol = sb->len;
 728
 729                if (strlen(sign_off_header) <= eol - i &&
 730                    !prefixcmp(sb->buf + i, sign_off_header)) {
 731                        i = eol;
 732                        continue;
 733                }
 734                while (i < eol)
 735                        if (!isspace(sb->buf[i++]))
 736                                return 0;
 737        }
 738
 739        return 1;
 740}
 741
 742static const char *find_author_by_nickname(const char *name)
 743{
 744        struct rev_info revs;
 745        struct commit *commit;
 746        struct strbuf buf = STRBUF_INIT;
 747        const char *av[20];
 748        int ac = 0;
 749
 750        init_revisions(&revs, NULL);
 751        strbuf_addf(&buf, "--author=%s", name);
 752        av[++ac] = "--all";
 753        av[++ac] = "-i";
 754        av[++ac] = buf.buf;
 755        av[++ac] = NULL;
 756        setup_revisions(ac, av, &revs, NULL);
 757        prepare_revision_walk(&revs);
 758        commit = get_revision(&revs);
 759        if (commit) {
 760                struct pretty_print_context ctx = {0};
 761                ctx.date_mode = DATE_NORMAL;
 762                strbuf_release(&buf);
 763                format_commit_message(commit, "%an <%ae>", &buf, &ctx);
 764                return strbuf_detach(&buf, NULL);
 765        }
 766        die("No existing author found with '%s'", name);
 767}
 768
 769
 770static void handle_untracked_files_arg(struct wt_status *s)
 771{
 772        if (!untracked_files_arg)
 773                ; /* default already initialized */
 774        else if (!strcmp(untracked_files_arg, "no"))
 775                s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
 776        else if (!strcmp(untracked_files_arg, "normal"))
 777                s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
 778        else if (!strcmp(untracked_files_arg, "all"))
 779                s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
 780        else
 781                die("Invalid untracked files mode '%s'", untracked_files_arg);
 782}
 783
 784static int parse_and_validate_options(int argc, const char *argv[],
 785                                      const char * const usage[],
 786                                      const char *prefix,
 787                                      struct wt_status *s)
 788{
 789        int f = 0;
 790
 791        argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
 792                             0);
 793
 794        if (force_author && !strchr(force_author, '>'))
 795                force_author = find_author_by_nickname(force_author);
 796
 797        if (force_author && renew_authorship)
 798                die("Using both --reset-author and --author does not make sense");
 799
 800        if (logfile || message.len || use_message)
 801                use_editor = 0;
 802        if (edit_flag)
 803                use_editor = 1;
 804        if (!use_editor)
 805                setenv("GIT_EDITOR", ":", 1);
 806
 807        if (get_sha1("HEAD", head_sha1))
 808                initial_commit = 1;
 809
 810        /* Sanity check options */
 811        if (amend && initial_commit)
 812                die("You have nothing to amend.");
 813        if (amend && in_merge)
 814                die("You are in the middle of a merge -- cannot amend.");
 815
 816        if (use_message)
 817                f++;
 818        if (edit_message)
 819                f++;
 820        if (logfile)
 821                f++;
 822        if (f > 1)
 823                die("Only one of -c/-C/-F can be used.");
 824        if (message.len && f > 0)
 825                die("Option -m cannot be combined with -c/-C/-F.");
 826        if (edit_message)
 827                use_message = edit_message;
 828        if (amend && !use_message)
 829                use_message = "HEAD";
 830        if (!use_message && renew_authorship)
 831                die("--reset-author can be used only with -C, -c or --amend.");
 832        if (use_message) {
 833                unsigned char sha1[20];
 834                static char utf8[] = "UTF-8";
 835                const char *out_enc;
 836                char *enc, *end;
 837                struct commit *commit;
 838
 839                if (get_sha1(use_message, sha1))
 840                        die("could not lookup commit %s", use_message);
 841                commit = lookup_commit_reference(sha1);
 842                if (!commit || parse_commit(commit))
 843                        die("could not parse commit %s", use_message);
 844
 845                enc = strstr(commit->buffer, "\nencoding");
 846                if (enc) {
 847                        end = strchr(enc + 10, '\n');
 848                        enc = xstrndup(enc + 10, end - (enc + 10));
 849                } else {
 850                        enc = utf8;
 851                }
 852                out_enc = git_commit_encoding ? git_commit_encoding : utf8;
 853
 854                if (strcmp(out_enc, enc))
 855                        use_message_buffer =
 856                                reencode_string(commit->buffer, out_enc, enc);
 857
 858                /*
 859                 * If we failed to reencode the buffer, just copy it
 860                 * byte for byte so the user can try to fix it up.
 861                 * This also handles the case where input and output
 862                 * encodings are identical.
 863                 */
 864                if (use_message_buffer == NULL)
 865                        use_message_buffer = xstrdup(commit->buffer);
 866                if (enc != utf8)
 867                        free(enc);
 868        }
 869
 870        if (!!also + !!only + !!all + !!interactive > 1)
 871                die("Only one of --include/--only/--all/--interactive can be used.");
 872        if (argc == 0 && (also || (only && !amend)))
 873                die("No paths with --include/--only does not make sense.");
 874        if (argc == 0 && only && amend)
 875                only_include_assumed = "Clever... amending the last one with dirty index.";
 876        if (argc > 0 && !also && !only)
 877                only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
 878        if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
 879                cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
 880        else if (!strcmp(cleanup_arg, "verbatim"))
 881                cleanup_mode = CLEANUP_NONE;
 882        else if (!strcmp(cleanup_arg, "whitespace"))
 883                cleanup_mode = CLEANUP_SPACE;
 884        else if (!strcmp(cleanup_arg, "strip"))
 885                cleanup_mode = CLEANUP_ALL;
 886        else
 887                die("Invalid cleanup mode %s", cleanup_arg);
 888
 889        handle_untracked_files_arg(s);
 890
 891        if (all && argc > 0)
 892                die("Paths with -a does not make sense.");
 893        else if (interactive && argc > 0)
 894                die("Paths with --interactive does not make sense.");
 895
 896        if (null_termination && status_format == STATUS_FORMAT_LONG)
 897                status_format = STATUS_FORMAT_PORCELAIN;
 898        if (status_format != STATUS_FORMAT_LONG)
 899                dry_run = 1;
 900
 901        return argc;
 902}
 903
 904static int dry_run_commit(int argc, const char **argv, const char *prefix,
 905                          struct wt_status *s)
 906{
 907        int commitable;
 908        const char *index_file;
 909
 910        index_file = prepare_index(argc, argv, prefix, 1);
 911        commitable = run_status(stdout, index_file, prefix, 0, s);
 912        rollback_index_files();
 913
 914        return commitable ? 0 : 1;
 915}
 916
 917static int parse_status_slot(const char *var, int offset)
 918{
 919        if (!strcasecmp(var+offset, "header"))
 920                return WT_STATUS_HEADER;
 921        if (!strcasecmp(var+offset, "updated")
 922                || !strcasecmp(var+offset, "added"))
 923                return WT_STATUS_UPDATED;
 924        if (!strcasecmp(var+offset, "changed"))
 925                return WT_STATUS_CHANGED;
 926        if (!strcasecmp(var+offset, "untracked"))
 927                return WT_STATUS_UNTRACKED;
 928        if (!strcasecmp(var+offset, "nobranch"))
 929                return WT_STATUS_NOBRANCH;
 930        if (!strcasecmp(var+offset, "unmerged"))
 931                return WT_STATUS_UNMERGED;
 932        return -1;
 933}
 934
 935static int git_status_config(const char *k, const char *v, void *cb)
 936{
 937        struct wt_status *s = cb;
 938
 939        if (!strcmp(k, "status.submodulesummary")) {
 940                int is_bool;
 941                s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
 942                if (is_bool && s->submodule_summary)
 943                        s->submodule_summary = -1;
 944                return 0;
 945        }
 946        if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
 947                s->use_color = git_config_colorbool(k, v, -1);
 948                return 0;
 949        }
 950        if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
 951                int slot = parse_status_slot(k, 13);
 952                if (slot < 0)
 953                        return 0;
 954                if (!v)
 955                        return config_error_nonbool(k);
 956                color_parse(v, k, s->color_palette[slot]);
 957                return 0;
 958        }
 959        if (!strcmp(k, "status.relativepaths")) {
 960                s->relative_paths = git_config_bool(k, v);
 961                return 0;
 962        }
 963        if (!strcmp(k, "status.showuntrackedfiles")) {
 964                if (!v)
 965                        return config_error_nonbool(k);
 966                else if (!strcmp(v, "no"))
 967                        s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
 968                else if (!strcmp(v, "normal"))
 969                        s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
 970                else if (!strcmp(v, "all"))
 971                        s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
 972                else
 973                        return error("Invalid untracked files mode '%s'", v);
 974                return 0;
 975        }
 976        return git_diff_ui_config(k, v, NULL);
 977}
 978
 979int cmd_status(int argc, const char **argv, const char *prefix)
 980{
 981        struct wt_status s;
 982        unsigned char sha1[20];
 983        static struct option builtin_status_options[] = {
 984                OPT__VERBOSE(&verbose),
 985                OPT_SET_INT('s', "short", &status_format,
 986                            "show status concisely", STATUS_FORMAT_SHORT),
 987                OPT_SET_INT(0, "porcelain", &status_format,
 988                            "show porcelain output format",
 989                            STATUS_FORMAT_PORCELAIN),
 990                OPT_BOOLEAN('z', "null", &null_termination,
 991                            "terminate entries with NUL"),
 992                { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
 993                  "mode",
 994                  "show untracked files, optional modes: all, normal, no. (Default: all)",
 995                  PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
 996                OPT_END(),
 997        };
 998
 999        if (null_termination && status_format == STATUS_FORMAT_LONG)
1000                status_format = STATUS_FORMAT_PORCELAIN;
1001
1002        wt_status_prepare(&s);
1003        git_config(git_status_config, &s);
1004        in_merge = file_exists(git_path("MERGE_HEAD"));
1005        argc = parse_options(argc, argv, prefix,
1006                             builtin_status_options,
1007                             builtin_status_usage, 0);
1008        handle_untracked_files_arg(&s);
1009
1010        if (*argv)
1011                s.pathspec = get_pathspec(prefix, argv);
1012
1013        read_cache();
1014        refresh_cache(REFRESH_QUIET|REFRESH_UNMERGED);
1015        s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1016        s.in_merge = in_merge;
1017        wt_status_collect(&s);
1018
1019        if (s.relative_paths)
1020                s.prefix = prefix;
1021        if (s.use_color == -1)
1022                s.use_color = git_use_color_default;
1023        if (diff_use_color_default == -1)
1024                diff_use_color_default = git_use_color_default;
1025
1026        switch (status_format) {
1027        case STATUS_FORMAT_SHORT:
1028                wt_shortstatus_print(&s, null_termination);
1029                break;
1030        case STATUS_FORMAT_PORCELAIN:
1031                wt_porcelain_print(&s, null_termination);
1032                break;
1033        case STATUS_FORMAT_LONG:
1034                s.verbose = verbose;
1035                wt_status_print(&s);
1036                break;
1037        }
1038        return 0;
1039}
1040
1041static void print_summary(const char *prefix, const unsigned char *sha1)
1042{
1043        struct rev_info rev;
1044        struct commit *commit;
1045        static const char *format = "format:%h] %s";
1046        unsigned char junk_sha1[20];
1047        const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1048
1049        commit = lookup_commit(sha1);
1050        if (!commit)
1051                die("couldn't look up newly created commit");
1052        if (!commit || parse_commit(commit))
1053                die("could not parse newly created commit");
1054
1055        init_revisions(&rev, prefix);
1056        setup_revisions(0, NULL, &rev, NULL);
1057
1058        rev.abbrev = 0;
1059        rev.diff = 1;
1060        rev.diffopt.output_format =
1061                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1062
1063        rev.verbose_header = 1;
1064        rev.show_root_diff = 1;
1065        get_commit_format(format, &rev);
1066        rev.always_show_header = 0;
1067        rev.diffopt.detect_rename = 1;
1068        rev.diffopt.rename_limit = 100;
1069        rev.diffopt.break_opt = 0;
1070        diff_setup_done(&rev.diffopt);
1071
1072        printf("[%s%s ",
1073                !prefixcmp(head, "refs/heads/") ?
1074                        head + 11 :
1075                        !strcmp(head, "HEAD") ?
1076                                "detached HEAD" :
1077                                head,
1078                initial_commit ? " (root-commit)" : "");
1079
1080        if (!log_tree_commit(&rev, commit)) {
1081                struct pretty_print_context ctx = {0};
1082                struct strbuf buf = STRBUF_INIT;
1083                ctx.date_mode = DATE_NORMAL;
1084                format_commit_message(commit, format + 7, &buf, &ctx);
1085                printf("%s\n", buf.buf);
1086                strbuf_release(&buf);
1087        }
1088}
1089
1090static int git_commit_config(const char *k, const char *v, void *cb)
1091{
1092        struct wt_status *s = cb;
1093
1094        if (!strcmp(k, "commit.template"))
1095                return git_config_pathname(&template_file, k, v);
1096
1097        return git_status_config(k, v, s);
1098}
1099
1100int cmd_commit(int argc, const char **argv, const char *prefix)
1101{
1102        struct strbuf sb = STRBUF_INIT;
1103        const char *index_file, *reflog_msg;
1104        char *nl, *p;
1105        unsigned char commit_sha1[20];
1106        struct ref_lock *ref_lock;
1107        struct commit_list *parents = NULL, **pptr = &parents;
1108        struct stat statbuf;
1109        int allow_fast_forward = 1;
1110        struct wt_status s;
1111
1112        wt_status_prepare(&s);
1113        git_config(git_commit_config, &s);
1114        in_merge = file_exists(git_path("MERGE_HEAD"));
1115        s.in_merge = in_merge;
1116
1117        if (s.use_color == -1)
1118                s.use_color = git_use_color_default;
1119        argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1120                                          prefix, &s);
1121        if (dry_run) {
1122                if (diff_use_color_default == -1)
1123                        diff_use_color_default = git_use_color_default;
1124                return dry_run_commit(argc, argv, prefix, &s);
1125        }
1126        index_file = prepare_index(argc, argv, prefix, 0);
1127
1128        /* Set up everything for writing the commit object.  This includes
1129           running hooks, writing the trees, and interacting with the user.  */
1130        if (!prepare_to_commit(index_file, prefix, &s)) {
1131                rollback_index_files();
1132                return 1;
1133        }
1134
1135        /* Determine parents */
1136        if (initial_commit) {
1137                reflog_msg = "commit (initial)";
1138        } else if (amend) {
1139                struct commit_list *c;
1140                struct commit *commit;
1141
1142                reflog_msg = "commit (amend)";
1143                commit = lookup_commit(head_sha1);
1144                if (!commit || parse_commit(commit))
1145                        die("could not parse HEAD commit");
1146
1147                for (c = commit->parents; c; c = c->next)
1148                        pptr = &commit_list_insert(c->item, pptr)->next;
1149        } else if (in_merge) {
1150                struct strbuf m = STRBUF_INIT;
1151                FILE *fp;
1152
1153                reflog_msg = "commit (merge)";
1154                pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1155                fp = fopen(git_path("MERGE_HEAD"), "r");
1156                if (fp == NULL)
1157                        die_errno("could not open '%s' for reading",
1158                                  git_path("MERGE_HEAD"));
1159                while (strbuf_getline(&m, fp, '\n') != EOF) {
1160                        unsigned char sha1[20];
1161                        if (get_sha1_hex(m.buf, sha1) < 0)
1162                                die("Corrupt MERGE_HEAD file (%s)", m.buf);
1163                        pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1164                }
1165                fclose(fp);
1166                strbuf_release(&m);
1167                if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1168                        if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1169                                die_errno("could not read MERGE_MODE");
1170                        if (!strcmp(sb.buf, "no-ff"))
1171                                allow_fast_forward = 0;
1172                }
1173                if (allow_fast_forward)
1174                        parents = reduce_heads(parents);
1175        } else {
1176                reflog_msg = "commit";
1177                pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1178        }
1179
1180        /* Finally, get the commit message */
1181        strbuf_reset(&sb);
1182        if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1183                int saved_errno = errno;
1184                rollback_index_files();
1185                die("could not read commit message: %s", strerror(saved_errno));
1186        }
1187
1188        /* Truncate the message just before the diff, if any. */
1189        if (verbose) {
1190                p = strstr(sb.buf, "\ndiff --git ");
1191                if (p != NULL)
1192                        strbuf_setlen(&sb, p - sb.buf + 1);
1193        }
1194
1195        if (cleanup_mode != CLEANUP_NONE)
1196                stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1197        if (message_is_empty(&sb)) {
1198                rollback_index_files();
1199                fprintf(stderr, "Aborting commit due to empty commit message.\n");
1200                exit(1);
1201        }
1202
1203        if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1204                        fmt_ident(author_name, author_email, author_date,
1205                                IDENT_ERROR_ON_NO_NAME))) {
1206                rollback_index_files();
1207                die("failed to write commit object");
1208        }
1209
1210        ref_lock = lock_any_ref_for_update("HEAD",
1211                                           initial_commit ? NULL : head_sha1,
1212                                           0);
1213
1214        nl = strchr(sb.buf, '\n');
1215        if (nl)
1216                strbuf_setlen(&sb, nl + 1 - sb.buf);
1217        else
1218                strbuf_addch(&sb, '\n');
1219        strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1220        strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1221
1222        if (!ref_lock) {
1223                rollback_index_files();
1224                die("cannot lock HEAD ref");
1225        }
1226        if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1227                rollback_index_files();
1228                die("cannot update HEAD ref");
1229        }
1230
1231        unlink(git_path("MERGE_HEAD"));
1232        unlink(git_path("MERGE_MSG"));
1233        unlink(git_path("MERGE_MODE"));
1234        unlink(git_path("SQUASH_MSG"));
1235
1236        if (commit_index_files())
1237                die ("Repository has been updated, but unable to write\n"
1238                     "new_index file. Check that disk is not full or quota is\n"
1239                     "not exceeded, and then \"git reset HEAD\" to recover.");
1240
1241        rerere();
1242        run_hook(get_index_file(), "post-commit", NULL);
1243        if (!quiet)
1244                print_summary(prefix, commit_sha1);
1245
1246        return 0;
1247}