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