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