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