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