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