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