builtin / commit.con commit Merge branch 'jk/commit-how-to-abort-cherry-pick' (af77c0b)
   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#include "submodule.h"
  29#include "gpg-interface.h"
  30#include "column.h"
  31#include "sequencer.h"
  32#include "notes-utils.h"
  33
  34static const char * const builtin_commit_usage[] = {
  35        N_("git commit [options] [--] <pathspec>..."),
  36        NULL
  37};
  38
  39static const char * const builtin_status_usage[] = {
  40        N_("git status [options] [--] <pathspec>..."),
  41        NULL
  42};
  43
  44static const char implicit_ident_advice[] =
  45N_("Your name and email address were configured automatically based\n"
  46"on your username and hostname. Please check that they are accurate.\n"
  47"You can suppress this message by setting them explicitly:\n"
  48"\n"
  49"    git config --global user.name \"Your Name\"\n"
  50"    git config --global user.email you@example.com\n"
  51"\n"
  52"After doing this, you may fix the identity used for this commit with:\n"
  53"\n"
  54"    git commit --amend --reset-author\n");
  55
  56static const char empty_amend_advice[] =
  57N_("You asked to amend the most recent commit, but doing so would make\n"
  58"it empty. You can repeat your command with --allow-empty, or you can\n"
  59"remove the commit entirely with \"git reset HEAD^\".\n");
  60
  61static const char empty_cherry_pick_advice[] =
  62N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
  63"If you wish to commit it anyway, use:\n"
  64"\n"
  65"    git commit --allow-empty\n"
  66"\n");
  67
  68static const char empty_cherry_pick_advice_single[] =
  69N_("Otherwise, please use 'git reset'\n");
  70
  71static const char empty_cherry_pick_advice_multi[] =
  72N_("If you wish to skip this commit, use:\n"
  73"\n"
  74"    git reset\n"
  75"\n"
  76"Then \"git cherry-pick --continue\" will resume cherry-picking\n"
  77"the remaining commits.\n");
  78
  79static const char *use_message_buffer;
  80static const char commit_editmsg[] = "COMMIT_EDITMSG";
  81static struct lock_file index_lock; /* real index */
  82static struct lock_file false_lock; /* used only for partial commits */
  83static enum {
  84        COMMIT_AS_IS = 1,
  85        COMMIT_NORMAL,
  86        COMMIT_PARTIAL
  87} commit_style;
  88
  89static const char *logfile, *force_author;
  90static const char *template_file;
  91/*
  92 * The _message variables are commit names from which to take
  93 * the commit message and/or authorship.
  94 */
  95static const char *author_message, *author_message_buffer;
  96static char *edit_message, *use_message;
  97static char *fixup_message, *squash_message;
  98static int all, also, interactive, patch_interactive, only, amend, signoff;
  99static int edit_flag = -1; /* unspecified */
 100static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
 101static int no_post_rewrite, allow_empty_message;
 102static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
 103static char *sign_commit;
 104
 105/*
 106 * The default commit message cleanup mode will remove the lines
 107 * beginning with # (shell comments) and leading and trailing
 108 * whitespaces (empty lines or containing only whitespaces)
 109 * if editor is used, and only the whitespaces if the message
 110 * is specified explicitly.
 111 */
 112static enum {
 113        CLEANUP_SPACE,
 114        CLEANUP_NONE,
 115        CLEANUP_ALL
 116} cleanup_mode;
 117static const char *cleanup_arg;
 118
 119static enum commit_whence whence;
 120static int sequencer_in_use;
 121static int use_editor = 1, include_status = 1;
 122static int show_ignored_in_status, have_option_m;
 123static const char *only_include_assumed;
 124static struct strbuf message = STRBUF_INIT;
 125
 126static enum status_format {
 127        STATUS_FORMAT_NONE = 0,
 128        STATUS_FORMAT_LONG,
 129        STATUS_FORMAT_SHORT,
 130        STATUS_FORMAT_PORCELAIN,
 131
 132        STATUS_FORMAT_UNSPECIFIED
 133} status_format = STATUS_FORMAT_UNSPECIFIED;
 134
 135static int opt_parse_m(const struct option *opt, const char *arg, int unset)
 136{
 137        struct strbuf *buf = opt->value;
 138        if (unset) {
 139                have_option_m = 0;
 140                strbuf_setlen(buf, 0);
 141        } else {
 142                have_option_m = 1;
 143                if (buf->len)
 144                        strbuf_addch(buf, '\n');
 145                strbuf_addstr(buf, arg);
 146                strbuf_complete_line(buf);
 147        }
 148        return 0;
 149}
 150
 151static void determine_whence(struct wt_status *s)
 152{
 153        if (file_exists(git_path("MERGE_HEAD")))
 154                whence = FROM_MERGE;
 155        else if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
 156                whence = FROM_CHERRY_PICK;
 157                if (file_exists(git_path("sequencer")))
 158                        sequencer_in_use = 1;
 159        }
 160        else
 161                whence = FROM_COMMIT;
 162        if (s)
 163                s->whence = whence;
 164}
 165
 166static void rollback_index_files(void)
 167{
 168        switch (commit_style) {
 169        case COMMIT_AS_IS:
 170                break; /* nothing to do */
 171        case COMMIT_NORMAL:
 172                rollback_lock_file(&index_lock);
 173                break;
 174        case COMMIT_PARTIAL:
 175                rollback_lock_file(&index_lock);
 176                rollback_lock_file(&false_lock);
 177                break;
 178        }
 179}
 180
 181static int commit_index_files(void)
 182{
 183        int err = 0;
 184
 185        switch (commit_style) {
 186        case COMMIT_AS_IS:
 187                break; /* nothing to do */
 188        case COMMIT_NORMAL:
 189                err = commit_lock_file(&index_lock);
 190                break;
 191        case COMMIT_PARTIAL:
 192                err = commit_lock_file(&index_lock);
 193                rollback_lock_file(&false_lock);
 194                break;
 195        }
 196
 197        return err;
 198}
 199
 200/*
 201 * Take a union of paths in the index and the named tree (typically, "HEAD"),
 202 * and return the paths that match the given pattern in list.
 203 */
 204static int list_paths(struct string_list *list, const char *with_tree,
 205                      const char *prefix, const char **pattern)
 206{
 207        int i;
 208        char *m;
 209
 210        if (!pattern)
 211                return 0;
 212
 213        for (i = 0; pattern[i]; i++)
 214                ;
 215        m = xcalloc(1, i);
 216
 217        if (with_tree) {
 218                char *max_prefix = common_prefix(pattern);
 219                overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
 220                free(max_prefix);
 221        }
 222
 223        for (i = 0; i < active_nr; i++) {
 224                const struct cache_entry *ce = active_cache[i];
 225                struct string_list_item *item;
 226
 227                if (ce->ce_flags & CE_UPDATE)
 228                        continue;
 229                if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
 230                        continue;
 231                item = string_list_insert(list, ce->name);
 232                if (ce_skip_worktree(ce))
 233                        item->util = item; /* better a valid pointer than a fake one */
 234        }
 235
 236        return report_path_error(m, pattern, prefix);
 237}
 238
 239static void add_remove_files(struct string_list *list)
 240{
 241        int i;
 242        for (i = 0; i < list->nr; i++) {
 243                struct stat st;
 244                struct string_list_item *p = &(list->items[i]);
 245
 246                /* p->util is skip-worktree */
 247                if (p->util)
 248                        continue;
 249
 250                if (!lstat(p->string, &st)) {
 251                        if (add_to_cache(p->string, &st, 0))
 252                                die(_("updating files failed"));
 253                } else
 254                        remove_file_from_cache(p->string);
 255        }
 256}
 257
 258static void create_base_index(const struct commit *current_head)
 259{
 260        struct tree *tree;
 261        struct unpack_trees_options opts;
 262        struct tree_desc t;
 263
 264        if (!current_head) {
 265                discard_cache();
 266                return;
 267        }
 268
 269        memset(&opts, 0, sizeof(opts));
 270        opts.head_idx = 1;
 271        opts.index_only = 1;
 272        opts.merge = 1;
 273        opts.src_index = &the_index;
 274        opts.dst_index = &the_index;
 275
 276        opts.fn = oneway_merge;
 277        tree = parse_tree_indirect(current_head->object.sha1);
 278        if (!tree)
 279                die(_("failed to unpack HEAD tree object"));
 280        parse_tree(tree);
 281        init_tree_desc(&t, tree->buffer, tree->size);
 282        if (unpack_trees(1, &t, &opts))
 283                exit(128); /* We've already reported the error, finish dying */
 284}
 285
 286static void refresh_cache_or_die(int refresh_flags)
 287{
 288        /*
 289         * refresh_flags contains REFRESH_QUIET, so the only errors
 290         * are for unmerged entries.
 291         */
 292        if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
 293                die_resolve_conflict("commit");
 294}
 295
 296static char *prepare_index(int argc, const char **argv, const char *prefix,
 297                           const struct commit *current_head, int is_status)
 298{
 299        int fd;
 300        struct string_list partial;
 301        const char **pathspec = NULL;
 302        char *old_index_env = NULL;
 303        int refresh_flags = REFRESH_QUIET;
 304
 305        if (is_status)
 306                refresh_flags |= REFRESH_UNMERGED;
 307
 308        if (*argv)
 309                pathspec = get_pathspec(prefix, argv);
 310
 311        if (read_cache_preload(pathspec) < 0)
 312                die(_("index file corrupt"));
 313
 314        if (interactive) {
 315                fd = hold_locked_index(&index_lock, 1);
 316
 317                refresh_cache_or_die(refresh_flags);
 318
 319                if (write_cache(fd, active_cache, active_nr) ||
 320                    close_lock_file(&index_lock))
 321                        die(_("unable to create temporary index"));
 322
 323                old_index_env = getenv(INDEX_ENVIRONMENT);
 324                setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
 325
 326                if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
 327                        die(_("interactive add failed"));
 328
 329                if (old_index_env && *old_index_env)
 330                        setenv(INDEX_ENVIRONMENT, old_index_env, 1);
 331                else
 332                        unsetenv(INDEX_ENVIRONMENT);
 333
 334                discard_cache();
 335                read_cache_from(index_lock.filename);
 336
 337                commit_style = COMMIT_NORMAL;
 338                return index_lock.filename;
 339        }
 340
 341        /*
 342         * Non partial, non as-is commit.
 343         *
 344         * (1) get the real index;
 345         * (2) update the_index as necessary;
 346         * (3) write the_index out to the real index (still locked);
 347         * (4) return the name of the locked index file.
 348         *
 349         * The caller should run hooks on the locked real index, and
 350         * (A) if all goes well, commit the real index;
 351         * (B) on failure, rollback the real index.
 352         */
 353        if (all || (also && pathspec && *pathspec)) {
 354                fd = hold_locked_index(&index_lock, 1);
 355                add_files_to_cache(also ? prefix : NULL, pathspec, 0);
 356                refresh_cache_or_die(refresh_flags);
 357                update_main_cache_tree(WRITE_TREE_SILENT);
 358                if (write_cache(fd, active_cache, active_nr) ||
 359                    close_lock_file(&index_lock))
 360                        die(_("unable to write new_index file"));
 361                commit_style = COMMIT_NORMAL;
 362                return index_lock.filename;
 363        }
 364
 365        /*
 366         * As-is commit.
 367         *
 368         * (1) return the name of the real index file.
 369         *
 370         * The caller should run hooks on the real index,
 371         * and create commit from the_index.
 372         * We still need to refresh the index here.
 373         */
 374        if (!only && (!pathspec || !*pathspec)) {
 375                fd = hold_locked_index(&index_lock, 1);
 376                refresh_cache_or_die(refresh_flags);
 377                if (active_cache_changed) {
 378                        update_main_cache_tree(WRITE_TREE_SILENT);
 379                        if (write_cache(fd, active_cache, active_nr) ||
 380                            commit_locked_index(&index_lock))
 381                                die(_("unable to write new_index file"));
 382                } else {
 383                        rollback_lock_file(&index_lock);
 384                }
 385                commit_style = COMMIT_AS_IS;
 386                return get_index_file();
 387        }
 388
 389        /*
 390         * A partial commit.
 391         *
 392         * (0) find the set of affected paths;
 393         * (1) get lock on the real index file;
 394         * (2) update the_index with the given paths;
 395         * (3) write the_index out to the real index (still locked);
 396         * (4) get lock on the false index file;
 397         * (5) reset the_index from HEAD;
 398         * (6) update the_index the same way as (2);
 399         * (7) write the_index out to the false index file;
 400         * (8) return the name of the false index file (still locked);
 401         *
 402         * The caller should run hooks on the locked false index, and
 403         * create commit from it.  Then
 404         * (A) if all goes well, commit the real index;
 405         * (B) on failure, rollback the real index;
 406         * In either case, rollback the false index.
 407         */
 408        commit_style = COMMIT_PARTIAL;
 409
 410        if (whence != FROM_COMMIT) {
 411                if (whence == FROM_MERGE)
 412                        die(_("cannot do a partial commit during a merge."));
 413                else if (whence == FROM_CHERRY_PICK)
 414                        die(_("cannot do a partial commit during a cherry-pick."));
 415        }
 416
 417        memset(&partial, 0, sizeof(partial));
 418        partial.strdup_strings = 1;
 419        if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, pathspec))
 420                exit(1);
 421
 422        discard_cache();
 423        if (read_cache() < 0)
 424                die(_("cannot read the index"));
 425
 426        fd = hold_locked_index(&index_lock, 1);
 427        add_remove_files(&partial);
 428        refresh_cache(REFRESH_QUIET);
 429        if (write_cache(fd, active_cache, active_nr) ||
 430            close_lock_file(&index_lock))
 431                die(_("unable to write new_index file"));
 432
 433        fd = hold_lock_file_for_update(&false_lock,
 434                                       git_path("next-index-%"PRIuMAX,
 435                                                (uintmax_t) getpid()),
 436                                       LOCK_DIE_ON_ERROR);
 437
 438        create_base_index(current_head);
 439        add_remove_files(&partial);
 440        refresh_cache(REFRESH_QUIET);
 441
 442        if (write_cache(fd, active_cache, active_nr) ||
 443            close_lock_file(&false_lock))
 444                die(_("unable to write temporary index file"));
 445
 446        discard_cache();
 447        read_cache_from(false_lock.filename);
 448
 449        return false_lock.filename;
 450}
 451
 452static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
 453                      struct wt_status *s)
 454{
 455        unsigned char sha1[20];
 456
 457        if (s->relative_paths)
 458                s->prefix = prefix;
 459
 460        if (amend) {
 461                s->amend = 1;
 462                s->reference = "HEAD^1";
 463        }
 464        s->verbose = verbose;
 465        s->index_file = index_file;
 466        s->fp = fp;
 467        s->nowarn = nowarn;
 468        s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
 469
 470        wt_status_collect(s);
 471
 472        switch (status_format) {
 473        case STATUS_FORMAT_SHORT:
 474                wt_shortstatus_print(s);
 475                break;
 476        case STATUS_FORMAT_PORCELAIN:
 477                wt_porcelain_print(s);
 478                break;
 479        case STATUS_FORMAT_UNSPECIFIED:
 480                die("BUG: finalize_deferred_config() should have been called");
 481                break;
 482        case STATUS_FORMAT_NONE:
 483        case STATUS_FORMAT_LONG:
 484                wt_status_print(s);
 485                break;
 486        }
 487
 488        return s->commitable;
 489}
 490
 491static int is_a_merge(const struct commit *current_head)
 492{
 493        return !!(current_head->parents && current_head->parents->next);
 494}
 495
 496static void export_one(const char *var, const char *s, const char *e, int hack)
 497{
 498        struct strbuf buf = STRBUF_INIT;
 499        if (hack)
 500                strbuf_addch(&buf, hack);
 501        strbuf_addf(&buf, "%.*s", (int)(e - s), s);
 502        setenv(var, buf.buf, 1);
 503        strbuf_release(&buf);
 504}
 505
 506static int sane_ident_split(struct ident_split *person)
 507{
 508        if (!person->name_begin || !person->name_end ||
 509            person->name_begin == person->name_end)
 510                return 0; /* no human readable name */
 511        if (!person->mail_begin || !person->mail_end ||
 512            person->mail_begin == person->mail_end)
 513                return 0; /* no usable mail */
 514        if (!person->date_begin || !person->date_end ||
 515            !person->tz_begin || !person->tz_end)
 516                return 0;
 517        return 1;
 518}
 519
 520static void determine_author_info(struct strbuf *author_ident)
 521{
 522        char *name, *email, *date;
 523        struct ident_split author;
 524
 525        name = getenv("GIT_AUTHOR_NAME");
 526        email = getenv("GIT_AUTHOR_EMAIL");
 527        date = getenv("GIT_AUTHOR_DATE");
 528
 529        if (author_message) {
 530                const char *a, *lb, *rb, *eol;
 531                size_t len;
 532
 533                a = strstr(author_message_buffer, "\nauthor ");
 534                if (!a)
 535                        die(_("invalid commit: %s"), author_message);
 536
 537                lb = strchrnul(a + strlen("\nauthor "), '<');
 538                rb = strchrnul(lb, '>');
 539                eol = strchrnul(rb, '\n');
 540                if (!*lb || !*rb || !*eol)
 541                        die(_("invalid commit: %s"), author_message);
 542
 543                if (lb == a + strlen("\nauthor "))
 544                        /* \nauthor <foo@example.com> */
 545                        name = xcalloc(1, 1);
 546                else
 547                        name = xmemdupz(a + strlen("\nauthor "),
 548                                        (lb - strlen(" ") -
 549                                         (a + strlen("\nauthor "))));
 550                email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
 551                len = eol - (rb + strlen("> "));
 552                date = xmalloc(len + 2);
 553                *date = '@';
 554                memcpy(date + 1, rb + strlen("> "), len);
 555                date[len + 1] = '\0';
 556        }
 557
 558        if (force_author) {
 559                const char *lb = strstr(force_author, " <");
 560                const char *rb = strchr(force_author, '>');
 561
 562                if (!lb || !rb)
 563                        die(_("malformed --author parameter"));
 564                name = xstrndup(force_author, lb - force_author);
 565                email = xstrndup(lb + 2, rb - (lb + 2));
 566        }
 567
 568        if (force_date)
 569                date = force_date;
 570        strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
 571        if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
 572            sane_ident_split(&author)) {
 573                export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
 574                export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
 575                export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
 576        }
 577}
 578
 579static char *cut_ident_timestamp_part(char *string)
 580{
 581        char *ket = strrchr(string, '>');
 582        if (!ket || ket[1] != ' ')
 583                die(_("Malformed ident string: '%s'"), string);
 584        *++ket = '\0';
 585        return ket;
 586}
 587
 588static int prepare_to_commit(const char *index_file, const char *prefix,
 589                             struct commit *current_head,
 590                             struct wt_status *s,
 591                             struct strbuf *author_ident)
 592{
 593        struct stat statbuf;
 594        struct strbuf committer_ident = STRBUF_INIT;
 595        int commitable, saved_color_setting;
 596        struct strbuf sb = STRBUF_INIT;
 597        char *buffer;
 598        const char *hook_arg1 = NULL;
 599        const char *hook_arg2 = NULL;
 600        int ident_shown = 0;
 601        int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
 602
 603        /* This checks and barfs if author is badly specified */
 604        determine_author_info(author_ident);
 605
 606        if (!no_verify && run_hook(index_file, "pre-commit", NULL))
 607                return 0;
 608
 609        if (squash_message) {
 610                /*
 611                 * Insert the proper subject line before other commit
 612                 * message options add their content.
 613                 */
 614                if (use_message && !strcmp(use_message, squash_message))
 615                        strbuf_addstr(&sb, "squash! ");
 616                else {
 617                        struct pretty_print_context ctx = {0};
 618                        struct commit *c;
 619                        c = lookup_commit_reference_by_name(squash_message);
 620                        if (!c)
 621                                die(_("could not lookup commit %s"), squash_message);
 622                        ctx.output_encoding = get_commit_output_encoding();
 623                        format_commit_message(c, "squash! %s\n\n", &sb,
 624                                              &ctx);
 625                }
 626        }
 627
 628        if (message.len) {
 629                strbuf_addbuf(&sb, &message);
 630                hook_arg1 = "message";
 631        } else if (logfile && !strcmp(logfile, "-")) {
 632                if (isatty(0))
 633                        fprintf(stderr, _("(reading log message from standard input)\n"));
 634                if (strbuf_read(&sb, 0, 0) < 0)
 635                        die_errno(_("could not read log from standard input"));
 636                hook_arg1 = "message";
 637        } else if (logfile) {
 638                if (strbuf_read_file(&sb, logfile, 0) < 0)
 639                        die_errno(_("could not read log file '%s'"),
 640                                  logfile);
 641                hook_arg1 = "message";
 642        } else if (use_message) {
 643                buffer = strstr(use_message_buffer, "\n\n");
 644                if (!use_editor && (!buffer || buffer[2] == '\0'))
 645                        die(_("commit has empty message"));
 646                strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
 647                hook_arg1 = "commit";
 648                hook_arg2 = use_message;
 649        } else if (fixup_message) {
 650                struct pretty_print_context ctx = {0};
 651                struct commit *commit;
 652                commit = lookup_commit_reference_by_name(fixup_message);
 653                if (!commit)
 654                        die(_("could not lookup commit %s"), fixup_message);
 655                ctx.output_encoding = get_commit_output_encoding();
 656                format_commit_message(commit, "fixup! %s\n\n",
 657                                      &sb, &ctx);
 658                hook_arg1 = "message";
 659        } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
 660                if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
 661                        die_errno(_("could not read MERGE_MSG"));
 662                hook_arg1 = "merge";
 663        } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
 664                if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
 665                        die_errno(_("could not read SQUASH_MSG"));
 666                hook_arg1 = "squash";
 667        } else if (template_file) {
 668                if (strbuf_read_file(&sb, template_file, 0) < 0)
 669                        die_errno(_("could not read '%s'"), template_file);
 670                hook_arg1 = "template";
 671                clean_message_contents = 0;
 672        }
 673
 674        /*
 675         * The remaining cases don't modify the template message, but
 676         * just set the argument(s) to the prepare-commit-msg hook.
 677         */
 678        else if (whence == FROM_MERGE)
 679                hook_arg1 = "merge";
 680        else if (whence == FROM_CHERRY_PICK) {
 681                hook_arg1 = "commit";
 682                hook_arg2 = "CHERRY_PICK_HEAD";
 683        }
 684
 685        if (squash_message) {
 686                /*
 687                 * If squash_commit was used for the commit subject,
 688                 * then we're possibly hijacking other commit log options.
 689                 * Reset the hook args to tell the real story.
 690                 */
 691                hook_arg1 = "message";
 692                hook_arg2 = "";
 693        }
 694
 695        s->fp = fopen(git_path(commit_editmsg), "w");
 696        if (s->fp == NULL)
 697                die_errno(_("could not open '%s'"), git_path(commit_editmsg));
 698
 699        if (clean_message_contents)
 700                stripspace(&sb, 0);
 701
 702        if (signoff) {
 703                /*
 704                 * See if we have a Conflicts: block at the end. If yes, count
 705                 * its size, so we can ignore it.
 706                 */
 707                int ignore_footer = 0;
 708                int i, eol, previous = 0;
 709                const char *nl;
 710
 711                for (i = 0; i < sb.len; i++) {
 712                        nl = memchr(sb.buf + i, '\n', sb.len - i);
 713                        if (nl)
 714                                eol = nl - sb.buf;
 715                        else
 716                                eol = sb.len;
 717                        if (!prefixcmp(sb.buf + previous, "\nConflicts:\n")) {
 718                                ignore_footer = sb.len - previous;
 719                                break;
 720                        }
 721                        while (i < eol)
 722                                i++;
 723                        previous = eol;
 724                }
 725
 726                append_signoff(&sb, ignore_footer, 0);
 727        }
 728
 729        if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
 730                die_errno(_("could not write commit template"));
 731
 732        strbuf_release(&sb);
 733
 734        /* This checks if committer ident is explicitly given */
 735        strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
 736        if (use_editor && include_status) {
 737                char *ai_tmp, *ci_tmp;
 738                if (whence != FROM_COMMIT)
 739                        status_printf_ln(s, GIT_COLOR_NORMAL,
 740                            whence == FROM_MERGE
 741                                ? _("\n"
 742                                        "It looks like you may be committing a merge.\n"
 743                                        "If this is not correct, please remove the file\n"
 744                                        "       %s\n"
 745                                        "and try again.\n")
 746                                : _("\n"
 747                                        "It looks like you may be committing a cherry-pick.\n"
 748                                        "If this is not correct, please remove the file\n"
 749                                        "       %s\n"
 750                                        "and try again.\n"),
 751                                git_path(whence == FROM_MERGE
 752                                         ? "MERGE_HEAD"
 753                                         : "CHERRY_PICK_HEAD"));
 754
 755                fprintf(s->fp, "\n");
 756                if (cleanup_mode == CLEANUP_ALL)
 757                        status_printf(s, GIT_COLOR_NORMAL,
 758                                _("Please enter the commit message for your changes."
 759                                  " Lines starting\nwith '%c' will be ignored, and an empty"
 760                                  " message aborts the commit.\n"), comment_line_char);
 761                else /* CLEANUP_SPACE, that is. */
 762                        status_printf(s, GIT_COLOR_NORMAL,
 763                                _("Please enter the commit message for your changes."
 764                                  " Lines starting\n"
 765                                  "with '%c' will be kept; you may remove them"
 766                                  " yourself if you want to.\n"
 767                                  "An empty message aborts the commit.\n"), comment_line_char);
 768                if (only_include_assumed)
 769                        status_printf_ln(s, GIT_COLOR_NORMAL,
 770                                        "%s", only_include_assumed);
 771
 772                ai_tmp = cut_ident_timestamp_part(author_ident->buf);
 773                ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
 774                if (strcmp(author_ident->buf, committer_ident.buf))
 775                        status_printf_ln(s, GIT_COLOR_NORMAL,
 776                                _("%s"
 777                                "Author:    %s"),
 778                                ident_shown++ ? "" : "\n",
 779                                author_ident->buf);
 780
 781                if (!committer_ident_sufficiently_given())
 782                        status_printf_ln(s, GIT_COLOR_NORMAL,
 783                                _("%s"
 784                                "Committer: %s"),
 785                                ident_shown++ ? "" : "\n",
 786                                committer_ident.buf);
 787
 788                if (ident_shown)
 789                        status_printf_ln(s, GIT_COLOR_NORMAL, "");
 790
 791                saved_color_setting = s->use_color;
 792                s->use_color = 0;
 793                commitable = run_status(s->fp, index_file, prefix, 1, s);
 794                s->use_color = saved_color_setting;
 795
 796                *ai_tmp = ' ';
 797                *ci_tmp = ' ';
 798        } else {
 799                unsigned char sha1[20];
 800                const char *parent = "HEAD";
 801
 802                if (!active_nr && read_cache() < 0)
 803                        die(_("Cannot read index"));
 804
 805                if (amend)
 806                        parent = "HEAD^1";
 807
 808                if (get_sha1(parent, sha1))
 809                        commitable = !!active_nr;
 810                else
 811                        commitable = index_differs_from(parent, 0);
 812        }
 813        strbuf_release(&committer_ident);
 814
 815        fclose(s->fp);
 816
 817        /*
 818         * Reject an attempt to record a non-merge empty commit without
 819         * explicit --allow-empty. In the cherry-pick case, it may be
 820         * empty due to conflict resolution, which the user should okay.
 821         */
 822        if (!commitable && whence != FROM_MERGE && !allow_empty &&
 823            !(amend && is_a_merge(current_head))) {
 824                run_status(stdout, index_file, prefix, 0, s);
 825                if (amend)
 826                        fputs(_(empty_amend_advice), stderr);
 827                else if (whence == FROM_CHERRY_PICK) {
 828                        fputs(_(empty_cherry_pick_advice), stderr);
 829                        if (!sequencer_in_use)
 830                                fputs(_(empty_cherry_pick_advice_single), stderr);
 831                        else
 832                                fputs(_(empty_cherry_pick_advice_multi), stderr);
 833                }
 834                return 0;
 835        }
 836
 837        /*
 838         * Re-read the index as pre-commit hook could have updated it,
 839         * and write it out as a tree.  We must do this before we invoke
 840         * the editor and after we invoke run_status above.
 841         */
 842        discard_cache();
 843        read_cache_from(index_file);
 844        if (update_main_cache_tree(0)) {
 845                error(_("Error building trees"));
 846                return 0;
 847        }
 848
 849        if (run_hook(index_file, "prepare-commit-msg",
 850                     git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
 851                return 0;
 852
 853        if (use_editor) {
 854                char index[PATH_MAX];
 855                const char *env[2] = { NULL };
 856                env[0] =  index;
 857                snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 858                if (launch_editor(git_path(commit_editmsg), NULL, env)) {
 859                        fprintf(stderr,
 860                        _("Please supply the message using either -m or -F option.\n"));
 861                        exit(1);
 862                }
 863        }
 864
 865        if (!no_verify &&
 866            run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
 867                return 0;
 868        }
 869
 870        return 1;
 871}
 872
 873static int rest_is_empty(struct strbuf *sb, int start)
 874{
 875        int i, eol;
 876        const char *nl;
 877
 878        /* Check if the rest is just whitespace and Signed-of-by's. */
 879        for (i = start; i < sb->len; i++) {
 880                nl = memchr(sb->buf + i, '\n', sb->len - i);
 881                if (nl)
 882                        eol = nl - sb->buf;
 883                else
 884                        eol = sb->len;
 885
 886                if (strlen(sign_off_header) <= eol - i &&
 887                    !prefixcmp(sb->buf + i, sign_off_header)) {
 888                        i = eol;
 889                        continue;
 890                }
 891                while (i < eol)
 892                        if (!isspace(sb->buf[i++]))
 893                                return 0;
 894        }
 895
 896        return 1;
 897}
 898
 899/*
 900 * Find out if the message in the strbuf contains only whitespace and
 901 * Signed-off-by lines.
 902 */
 903static int message_is_empty(struct strbuf *sb)
 904{
 905        if (cleanup_mode == CLEANUP_NONE && sb->len)
 906                return 0;
 907        return rest_is_empty(sb, 0);
 908}
 909
 910/*
 911 * See if the user edited the message in the editor or left what
 912 * was in the template intact
 913 */
 914static int template_untouched(struct strbuf *sb)
 915{
 916        struct strbuf tmpl = STRBUF_INIT;
 917        char *start;
 918
 919        if (cleanup_mode == CLEANUP_NONE && sb->len)
 920                return 0;
 921
 922        if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
 923                return 0;
 924
 925        stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
 926        start = (char *)skip_prefix(sb->buf, tmpl.buf);
 927        if (!start)
 928                start = sb->buf;
 929        strbuf_release(&tmpl);
 930        return rest_is_empty(sb, start - sb->buf);
 931}
 932
 933static const char *find_author_by_nickname(const char *name)
 934{
 935        struct rev_info revs;
 936        struct commit *commit;
 937        struct strbuf buf = STRBUF_INIT;
 938        const char *av[20];
 939        int ac = 0;
 940
 941        init_revisions(&revs, NULL);
 942        strbuf_addf(&buf, "--author=%s", name);
 943        av[++ac] = "--all";
 944        av[++ac] = "-i";
 945        av[++ac] = buf.buf;
 946        av[++ac] = NULL;
 947        setup_revisions(ac, av, &revs, NULL);
 948        prepare_revision_walk(&revs);
 949        commit = get_revision(&revs);
 950        if (commit) {
 951                struct pretty_print_context ctx = {0};
 952                ctx.date_mode = DATE_NORMAL;
 953                strbuf_release(&buf);
 954                format_commit_message(commit, "%an <%ae>", &buf, &ctx);
 955                return strbuf_detach(&buf, NULL);
 956        }
 957        die(_("No existing author found with '%s'"), name);
 958}
 959
 960
 961static void handle_untracked_files_arg(struct wt_status *s)
 962{
 963        if (!untracked_files_arg)
 964                ; /* default already initialized */
 965        else if (!strcmp(untracked_files_arg, "no"))
 966                s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
 967        else if (!strcmp(untracked_files_arg, "normal"))
 968                s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
 969        else if (!strcmp(untracked_files_arg, "all"))
 970                s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
 971        else
 972                die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
 973}
 974
 975static const char *read_commit_message(const char *name)
 976{
 977        const char *out_enc;
 978        struct commit *commit;
 979
 980        commit = lookup_commit_reference_by_name(name);
 981        if (!commit)
 982                die(_("could not lookup commit %s"), name);
 983        out_enc = get_commit_output_encoding();
 984        return logmsg_reencode(commit, NULL, out_enc);
 985}
 986
 987/*
 988 * Enumerate what needs to be propagated when --porcelain
 989 * is not in effect here.
 990 */
 991static struct status_deferred_config {
 992        enum status_format status_format;
 993        int show_branch;
 994} status_deferred_config = {
 995        STATUS_FORMAT_UNSPECIFIED,
 996        -1 /* unspecified */
 997};
 998
 999static void finalize_deferred_config(struct wt_status *s)
1000{
1001        int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1002                                   !s->null_termination);
1003
1004        if (s->null_termination) {
1005                if (status_format == STATUS_FORMAT_NONE ||
1006                    status_format == STATUS_FORMAT_UNSPECIFIED)
1007                        status_format = STATUS_FORMAT_PORCELAIN;
1008                else if (status_format == STATUS_FORMAT_LONG)
1009                        die(_("--long and -z are incompatible"));
1010        }
1011
1012        if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1013                status_format = status_deferred_config.status_format;
1014        if (status_format == STATUS_FORMAT_UNSPECIFIED)
1015                status_format = STATUS_FORMAT_NONE;
1016
1017        if (use_deferred_config && s->show_branch < 0)
1018                s->show_branch = status_deferred_config.show_branch;
1019        if (s->show_branch < 0)
1020                s->show_branch = 0;
1021}
1022
1023static int parse_and_validate_options(int argc, const char *argv[],
1024                                      const struct option *options,
1025                                      const char * const usage[],
1026                                      const char *prefix,
1027                                      struct commit *current_head,
1028                                      struct wt_status *s)
1029{
1030        int f = 0;
1031
1032        argc = parse_options(argc, argv, prefix, options, usage, 0);
1033        finalize_deferred_config(s);
1034
1035        if (force_author && !strchr(force_author, '>'))
1036                force_author = find_author_by_nickname(force_author);
1037
1038        if (force_author && renew_authorship)
1039                die(_("Using both --reset-author and --author does not make sense"));
1040
1041        if (logfile || have_option_m || use_message || fixup_message)
1042                use_editor = 0;
1043        if (0 <= edit_flag)
1044                use_editor = edit_flag;
1045        if (!use_editor)
1046                setenv("GIT_EDITOR", ":", 1);
1047
1048        /* Sanity check options */
1049        if (amend && !current_head)
1050                die(_("You have nothing to amend."));
1051        if (amend && whence != FROM_COMMIT) {
1052                if (whence == FROM_MERGE)
1053                        die(_("You are in the middle of a merge -- cannot amend."));
1054                else if (whence == FROM_CHERRY_PICK)
1055                        die(_("You are in the middle of a cherry-pick -- cannot amend."));
1056        }
1057        if (fixup_message && squash_message)
1058                die(_("Options --squash and --fixup cannot be used together"));
1059        if (use_message)
1060                f++;
1061        if (edit_message)
1062                f++;
1063        if (fixup_message)
1064                f++;
1065        if (logfile)
1066                f++;
1067        if (f > 1)
1068                die(_("Only one of -c/-C/-F/--fixup can be used."));
1069        if (message.len && f > 0)
1070                die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1071        if (f || message.len)
1072                template_file = NULL;
1073        if (edit_message)
1074                use_message = edit_message;
1075        if (amend && !use_message && !fixup_message)
1076                use_message = "HEAD";
1077        if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1078                die(_("--reset-author can be used only with -C, -c or --amend."));
1079        if (use_message) {
1080                use_message_buffer = read_commit_message(use_message);
1081                if (!renew_authorship) {
1082                        author_message = use_message;
1083                        author_message_buffer = use_message_buffer;
1084                }
1085        }
1086        if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1087                author_message = "CHERRY_PICK_HEAD";
1088                author_message_buffer = read_commit_message(author_message);
1089        }
1090
1091        if (patch_interactive)
1092                interactive = 1;
1093
1094        if (!!also + !!only + !!all + !!interactive > 1)
1095                die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1096        if (argc == 0 && (also || (only && !amend)))
1097                die(_("No paths with --include/--only does not make sense."));
1098        if (argc == 0 && only && amend)
1099                only_include_assumed = _("Clever... amending the last one with dirty index.");
1100        if (argc > 0 && !also && !only)
1101                only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1102        if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1103                cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1104        else if (!strcmp(cleanup_arg, "verbatim"))
1105                cleanup_mode = CLEANUP_NONE;
1106        else if (!strcmp(cleanup_arg, "whitespace"))
1107                cleanup_mode = CLEANUP_SPACE;
1108        else if (!strcmp(cleanup_arg, "strip"))
1109                cleanup_mode = CLEANUP_ALL;
1110        else
1111                die(_("Invalid cleanup mode %s"), cleanup_arg);
1112
1113        handle_untracked_files_arg(s);
1114
1115        if (all && argc > 0)
1116                die(_("Paths with -a does not make sense."));
1117
1118        if (status_format != STATUS_FORMAT_NONE)
1119                dry_run = 1;
1120
1121        return argc;
1122}
1123
1124static int dry_run_commit(int argc, const char **argv, const char *prefix,
1125                          const struct commit *current_head, struct wt_status *s)
1126{
1127        int commitable;
1128        const char *index_file;
1129
1130        index_file = prepare_index(argc, argv, prefix, current_head, 1);
1131        commitable = run_status(stdout, index_file, prefix, 0, s);
1132        rollback_index_files();
1133
1134        return commitable ? 0 : 1;
1135}
1136
1137static int parse_status_slot(const char *var, int offset)
1138{
1139        if (!strcasecmp(var+offset, "header"))
1140                return WT_STATUS_HEADER;
1141        if (!strcasecmp(var+offset, "branch"))
1142                return WT_STATUS_ONBRANCH;
1143        if (!strcasecmp(var+offset, "updated")
1144                || !strcasecmp(var+offset, "added"))
1145                return WT_STATUS_UPDATED;
1146        if (!strcasecmp(var+offset, "changed"))
1147                return WT_STATUS_CHANGED;
1148        if (!strcasecmp(var+offset, "untracked"))
1149                return WT_STATUS_UNTRACKED;
1150        if (!strcasecmp(var+offset, "nobranch"))
1151                return WT_STATUS_NOBRANCH;
1152        if (!strcasecmp(var+offset, "unmerged"))
1153                return WT_STATUS_UNMERGED;
1154        return -1;
1155}
1156
1157static int git_status_config(const char *k, const char *v, void *cb)
1158{
1159        struct wt_status *s = cb;
1160
1161        if (!prefixcmp(k, "column."))
1162                return git_column_config(k, v, "status", &s->colopts);
1163        if (!strcmp(k, "status.submodulesummary")) {
1164                int is_bool;
1165                s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1166                if (is_bool && s->submodule_summary)
1167                        s->submodule_summary = -1;
1168                return 0;
1169        }
1170        if (!strcmp(k, "status.short")) {
1171                if (git_config_bool(k, v))
1172                        status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1173                else
1174                        status_deferred_config.status_format = STATUS_FORMAT_NONE;
1175                return 0;
1176        }
1177        if (!strcmp(k, "status.branch")) {
1178                status_deferred_config.show_branch = git_config_bool(k, v);
1179                return 0;
1180        }
1181        if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1182                s->use_color = git_config_colorbool(k, v);
1183                return 0;
1184        }
1185        if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1186                int slot = parse_status_slot(k, 13);
1187                if (slot < 0)
1188                        return 0;
1189                if (!v)
1190                        return config_error_nonbool(k);
1191                color_parse(v, k, s->color_palette[slot]);
1192                return 0;
1193        }
1194        if (!strcmp(k, "status.relativepaths")) {
1195                s->relative_paths = git_config_bool(k, v);
1196                return 0;
1197        }
1198        if (!strcmp(k, "status.showuntrackedfiles")) {
1199                if (!v)
1200                        return config_error_nonbool(k);
1201                else if (!strcmp(v, "no"))
1202                        s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1203                else if (!strcmp(v, "normal"))
1204                        s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1205                else if (!strcmp(v, "all"))
1206                        s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1207                else
1208                        return error(_("Invalid untracked files mode '%s'"), v);
1209                return 0;
1210        }
1211        return git_diff_ui_config(k, v, NULL);
1212}
1213
1214int cmd_status(int argc, const char **argv, const char *prefix)
1215{
1216        static struct wt_status s;
1217        int fd;
1218        unsigned char sha1[20];
1219        static struct option builtin_status_options[] = {
1220                OPT__VERBOSE(&verbose, N_("be verbose")),
1221                OPT_SET_INT('s', "short", &status_format,
1222                            N_("show status concisely"), STATUS_FORMAT_SHORT),
1223                OPT_BOOL('b', "branch", &s.show_branch,
1224                         N_("show branch information")),
1225                OPT_SET_INT(0, "porcelain", &status_format,
1226                            N_("machine-readable output"),
1227                            STATUS_FORMAT_PORCELAIN),
1228                OPT_SET_INT(0, "long", &status_format,
1229                            N_("show status in long format (default)"),
1230                            STATUS_FORMAT_LONG),
1231                OPT_BOOLEAN('z', "null", &s.null_termination,
1232                            N_("terminate entries with NUL")),
1233                { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1234                  N_("mode"),
1235                  N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1236                  PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1237                OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1238                            N_("show ignored files")),
1239                { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1240                  N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1241                  PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1242                OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1243                OPT_END(),
1244        };
1245
1246        if (argc == 2 && !strcmp(argv[1], "-h"))
1247                usage_with_options(builtin_status_usage, builtin_status_options);
1248
1249        wt_status_prepare(&s);
1250        gitmodules_config();
1251        git_config(git_status_config, &s);
1252        determine_whence(&s);
1253        argc = parse_options(argc, argv, prefix,
1254                             builtin_status_options,
1255                             builtin_status_usage, 0);
1256        finalize_colopts(&s.colopts, -1);
1257        finalize_deferred_config(&s);
1258
1259        handle_untracked_files_arg(&s);
1260        if (show_ignored_in_status)
1261                s.show_ignored_files = 1;
1262        if (*argv)
1263                s.pathspec = get_pathspec(prefix, argv);
1264
1265        read_cache_preload(s.pathspec);
1266        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1267
1268        fd = hold_locked_index(&index_lock, 0);
1269        if (0 <= fd)
1270                update_index_if_able(&the_index, &index_lock);
1271
1272        s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1273        s.ignore_submodule_arg = ignore_submodule_arg;
1274        wt_status_collect(&s);
1275
1276        if (s.relative_paths)
1277                s.prefix = prefix;
1278
1279        switch (status_format) {
1280        case STATUS_FORMAT_SHORT:
1281                wt_shortstatus_print(&s);
1282                break;
1283        case STATUS_FORMAT_PORCELAIN:
1284                wt_porcelain_print(&s);
1285                break;
1286        case STATUS_FORMAT_UNSPECIFIED:
1287                die("BUG: finalize_deferred_config() should have been called");
1288                break;
1289        case STATUS_FORMAT_NONE:
1290        case STATUS_FORMAT_LONG:
1291                s.verbose = verbose;
1292                s.ignore_submodule_arg = ignore_submodule_arg;
1293                wt_status_print(&s);
1294                break;
1295        }
1296        return 0;
1297}
1298
1299static void print_summary(const char *prefix, const unsigned char *sha1,
1300                          int initial_commit)
1301{
1302        struct rev_info rev;
1303        struct commit *commit;
1304        struct strbuf format = STRBUF_INIT;
1305        unsigned char junk_sha1[20];
1306        const char *head;
1307        struct pretty_print_context pctx = {0};
1308        struct strbuf author_ident = STRBUF_INIT;
1309        struct strbuf committer_ident = STRBUF_INIT;
1310
1311        commit = lookup_commit(sha1);
1312        if (!commit)
1313                die(_("couldn't look up newly created commit"));
1314        if (!commit || parse_commit(commit))
1315                die(_("could not parse newly created commit"));
1316
1317        strbuf_addstr(&format, "format:%h] %s");
1318
1319        format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1320        format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1321        if (strbuf_cmp(&author_ident, &committer_ident)) {
1322                strbuf_addstr(&format, "\n Author: ");
1323                strbuf_addbuf_percentquote(&format, &author_ident);
1324        }
1325        if (!committer_ident_sufficiently_given()) {
1326                strbuf_addstr(&format, "\n Committer: ");
1327                strbuf_addbuf_percentquote(&format, &committer_ident);
1328                if (advice_implicit_identity) {
1329                        strbuf_addch(&format, '\n');
1330                        strbuf_addstr(&format, _(implicit_ident_advice));
1331                }
1332        }
1333        strbuf_release(&author_ident);
1334        strbuf_release(&committer_ident);
1335
1336        init_revisions(&rev, prefix);
1337        setup_revisions(0, NULL, &rev, NULL);
1338
1339        rev.diff = 1;
1340        rev.diffopt.output_format =
1341                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1342
1343        rev.verbose_header = 1;
1344        rev.show_root_diff = 1;
1345        get_commit_format(format.buf, &rev);
1346        rev.always_show_header = 0;
1347        rev.diffopt.detect_rename = 1;
1348        rev.diffopt.break_opt = 0;
1349        diff_setup_done(&rev.diffopt);
1350
1351        head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1352        printf("[%s%s ",
1353                !prefixcmp(head, "refs/heads/") ?
1354                        head + 11 :
1355                        !strcmp(head, "HEAD") ?
1356                                _("detached HEAD") :
1357                                head,
1358                initial_commit ? _(" (root-commit)") : "");
1359
1360        if (!log_tree_commit(&rev, commit)) {
1361                rev.always_show_header = 1;
1362                rev.use_terminator = 1;
1363                log_tree_commit(&rev, commit);
1364        }
1365
1366        strbuf_release(&format);
1367}
1368
1369static int git_commit_config(const char *k, const char *v, void *cb)
1370{
1371        struct wt_status *s = cb;
1372        int status;
1373
1374        if (!strcmp(k, "commit.template"))
1375                return git_config_pathname(&template_file, k, v);
1376        if (!strcmp(k, "commit.status")) {
1377                include_status = git_config_bool(k, v);
1378                return 0;
1379        }
1380        if (!strcmp(k, "commit.cleanup"))
1381                return git_config_string(&cleanup_arg, k, v);
1382
1383        status = git_gpg_config(k, v, NULL);
1384        if (status)
1385                return status;
1386        return git_status_config(k, v, s);
1387}
1388
1389static int run_rewrite_hook(const unsigned char *oldsha1,
1390                            const unsigned char *newsha1)
1391{
1392        /* oldsha1 SP newsha1 LF NUL */
1393        static char buf[2*40 + 3];
1394        struct child_process proc;
1395        const char *argv[3];
1396        int code;
1397        size_t n;
1398
1399        argv[0] = find_hook("post-rewrite");
1400        if (!argv[0])
1401                return 0;
1402
1403        argv[1] = "amend";
1404        argv[2] = NULL;
1405
1406        memset(&proc, 0, sizeof(proc));
1407        proc.argv = argv;
1408        proc.in = -1;
1409        proc.stdout_to_stderr = 1;
1410
1411        code = start_command(&proc);
1412        if (code)
1413                return code;
1414        n = snprintf(buf, sizeof(buf), "%s %s\n",
1415                     sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1416        write_in_full(proc.in, buf, n);
1417        close(proc.in);
1418        return finish_command(&proc);
1419}
1420
1421int cmd_commit(int argc, const char **argv, const char *prefix)
1422{
1423        static struct wt_status s;
1424        static struct option builtin_commit_options[] = {
1425                OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1426                OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1427
1428                OPT_GROUP(N_("Commit message options")),
1429                OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1430                OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1431                OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1432                OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1433                OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1434                OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1435                OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1436                OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1437                OPT_BOOLEAN(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1438                OPT_BOOLEAN('s', "signoff", &signoff, N_("add Signed-off-by:")),
1439                OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1440                OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1441                OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1442                OPT_BOOLEAN(0, "status", &include_status, N_("include status in commit message template")),
1443                { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key id"),
1444                  N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1445                /* end commit message options */
1446
1447                OPT_GROUP(N_("Commit contents options")),
1448                OPT_BOOLEAN('a', "all", &all, N_("commit all changed files")),
1449                OPT_BOOLEAN('i', "include", &also, N_("add specified files to index for commit")),
1450                OPT_BOOLEAN(0, "interactive", &interactive, N_("interactively add files")),
1451                OPT_BOOLEAN('p', "patch", &patch_interactive, N_("interactively add changes")),
1452                OPT_BOOLEAN('o', "only", &only, N_("commit only specified files")),
1453                OPT_BOOLEAN('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1454                OPT_BOOLEAN(0, "dry-run", &dry_run, N_("show what would be committed")),
1455                OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1456                            STATUS_FORMAT_SHORT),
1457                OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1458                OPT_SET_INT(0, "porcelain", &status_format,
1459                            N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1460                OPT_SET_INT(0, "long", &status_format,
1461                            N_("show status in long format (default)"),
1462                            STATUS_FORMAT_LONG),
1463                OPT_BOOLEAN('z', "null", &s.null_termination,
1464                            N_("terminate entries with NUL")),
1465                OPT_BOOLEAN(0, "amend", &amend, N_("amend previous commit")),
1466                OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1467                { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, N_("mode"), N_("show untracked files, optional modes: all, normal, no. (Default: all)"), PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1468                /* end commit contents options */
1469
1470                { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
1471                  N_("ok to record an empty change"),
1472                  PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1473                { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
1474                  N_("ok to record a change with an empty message"),
1475                  PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1476
1477                OPT_END()
1478        };
1479
1480        struct strbuf sb = STRBUF_INIT;
1481        struct strbuf author_ident = STRBUF_INIT;
1482        const char *index_file, *reflog_msg;
1483        char *nl, *p;
1484        unsigned char sha1[20];
1485        struct ref_lock *ref_lock;
1486        struct commit_list *parents = NULL, **pptr = &parents;
1487        struct stat statbuf;
1488        int allow_fast_forward = 1;
1489        struct commit *current_head = NULL;
1490        struct commit_extra_header *extra = NULL;
1491
1492        if (argc == 2 && !strcmp(argv[1], "-h"))
1493                usage_with_options(builtin_commit_usage, builtin_commit_options);
1494
1495        wt_status_prepare(&s);
1496        gitmodules_config();
1497        git_config(git_commit_config, &s);
1498        status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1499        determine_whence(&s);
1500        s.colopts = 0;
1501
1502        if (get_sha1("HEAD", sha1))
1503                current_head = NULL;
1504        else {
1505                current_head = lookup_commit_or_die(sha1, "HEAD");
1506                if (!current_head || parse_commit(current_head))
1507                        die(_("could not parse HEAD commit"));
1508        }
1509        argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1510                                          builtin_commit_usage,
1511                                          prefix, current_head, &s);
1512        if (dry_run)
1513                return dry_run_commit(argc, argv, prefix, current_head, &s);
1514        index_file = prepare_index(argc, argv, prefix, current_head, 0);
1515
1516        /* Set up everything for writing the commit object.  This includes
1517           running hooks, writing the trees, and interacting with the user.  */
1518        if (!prepare_to_commit(index_file, prefix,
1519                               current_head, &s, &author_ident)) {
1520                rollback_index_files();
1521                return 1;
1522        }
1523
1524        /* Determine parents */
1525        reflog_msg = getenv("GIT_REFLOG_ACTION");
1526        if (!current_head) {
1527                if (!reflog_msg)
1528                        reflog_msg = "commit (initial)";
1529        } else if (amend) {
1530                struct commit_list *c;
1531
1532                if (!reflog_msg)
1533                        reflog_msg = "commit (amend)";
1534                for (c = current_head->parents; c; c = c->next)
1535                        pptr = &commit_list_insert(c->item, pptr)->next;
1536        } else if (whence == FROM_MERGE) {
1537                struct strbuf m = STRBUF_INIT;
1538                FILE *fp;
1539
1540                if (!reflog_msg)
1541                        reflog_msg = "commit (merge)";
1542                pptr = &commit_list_insert(current_head, pptr)->next;
1543                fp = fopen(git_path("MERGE_HEAD"), "r");
1544                if (fp == NULL)
1545                        die_errno(_("could not open '%s' for reading"),
1546                                  git_path("MERGE_HEAD"));
1547                while (strbuf_getline(&m, fp, '\n') != EOF) {
1548                        struct commit *parent;
1549
1550                        parent = get_merge_parent(m.buf);
1551                        if (!parent)
1552                                die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1553                        pptr = &commit_list_insert(parent, pptr)->next;
1554                }
1555                fclose(fp);
1556                strbuf_release(&m);
1557                if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1558                        if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1559                                die_errno(_("could not read MERGE_MODE"));
1560                        if (!strcmp(sb.buf, "no-ff"))
1561                                allow_fast_forward = 0;
1562                }
1563                if (allow_fast_forward)
1564                        parents = reduce_heads(parents);
1565        } else {
1566                if (!reflog_msg)
1567                        reflog_msg = (whence == FROM_CHERRY_PICK)
1568                                        ? "commit (cherry-pick)"
1569                                        : "commit";
1570                pptr = &commit_list_insert(current_head, pptr)->next;
1571        }
1572
1573        /* Finally, get the commit message */
1574        strbuf_reset(&sb);
1575        if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1576                int saved_errno = errno;
1577                rollback_index_files();
1578                die(_("could not read commit message: %s"), strerror(saved_errno));
1579        }
1580
1581        /* Truncate the message just before the diff, if any. */
1582        if (verbose) {
1583                p = strstr(sb.buf, "\ndiff --git ");
1584                if (p != NULL)
1585                        strbuf_setlen(&sb, p - sb.buf + 1);
1586        }
1587
1588        if (cleanup_mode != CLEANUP_NONE)
1589                stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1590        if (template_untouched(&sb) && !allow_empty_message) {
1591                rollback_index_files();
1592                fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1593                exit(1);
1594        }
1595        if (message_is_empty(&sb) && !allow_empty_message) {
1596                rollback_index_files();
1597                fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1598                exit(1);
1599        }
1600
1601        if (amend) {
1602                const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1603                extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1604        } else {
1605                struct commit_extra_header **tail = &extra;
1606                append_merge_tag_headers(parents, &tail);
1607        }
1608
1609        if (commit_tree_extended(&sb, active_cache_tree->sha1, parents, sha1,
1610                                 author_ident.buf, sign_commit, extra)) {
1611                rollback_index_files();
1612                die(_("failed to write commit object"));
1613        }
1614        strbuf_release(&author_ident);
1615        free_commit_extra_headers(extra);
1616
1617        ref_lock = lock_any_ref_for_update("HEAD",
1618                                           !current_head
1619                                           ? NULL
1620                                           : current_head->object.sha1,
1621                                           0);
1622
1623        nl = strchr(sb.buf, '\n');
1624        if (nl)
1625                strbuf_setlen(&sb, nl + 1 - sb.buf);
1626        else
1627                strbuf_addch(&sb, '\n');
1628        strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1629        strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1630
1631        if (!ref_lock) {
1632                rollback_index_files();
1633                die(_("cannot lock HEAD ref"));
1634        }
1635        if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1636                rollback_index_files();
1637                die(_("cannot update HEAD ref"));
1638        }
1639
1640        unlink(git_path("CHERRY_PICK_HEAD"));
1641        unlink(git_path("REVERT_HEAD"));
1642        unlink(git_path("MERGE_HEAD"));
1643        unlink(git_path("MERGE_MSG"));
1644        unlink(git_path("MERGE_MODE"));
1645        unlink(git_path("SQUASH_MSG"));
1646
1647        if (commit_index_files())
1648                die (_("Repository has been updated, but unable to write\n"
1649                     "new_index file. Check that disk is not full or quota is\n"
1650                     "not exceeded, and then \"git reset HEAD\" to recover."));
1651
1652        rerere(0);
1653        run_hook(get_index_file(), "post-commit", NULL);
1654        if (amend && !no_post_rewrite) {
1655                struct notes_rewrite_cfg *cfg;
1656                cfg = init_copy_notes_for_rewrite("amend");
1657                if (cfg) {
1658                        /* we are amending, so current_head is not NULL */
1659                        copy_note_for_rewrite(cfg, current_head->object.sha1, sha1);
1660                        finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1661                }
1662                run_rewrite_hook(current_head->object.sha1, sha1);
1663        }
1664        if (!quiet)
1665                print_summary(prefix, sha1, !current_head);
1666
1667        return 0;
1668}