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