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