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