builtin-commit.con commit status: show worktree status of conflicted paths separately (4d4d572)
   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
  28static const char * const builtin_commit_usage[] = {
  29        "git commit [options] [--] <filepattern>...",
  30        NULL
  31};
  32
  33static const char * const builtin_status_usage[] = {
  34        "git status [options] [--] <filepattern>...",
  35        NULL
  36};
  37
  38static unsigned char head_sha1[20], merge_head_sha1[20];
  39static char *use_message_buffer;
  40static const char commit_editmsg[] = "COMMIT_EDITMSG";
  41static struct lock_file index_lock; /* real index */
  42static struct lock_file false_lock; /* used only for partial commits */
  43static enum {
  44        COMMIT_AS_IS = 1,
  45        COMMIT_NORMAL,
  46        COMMIT_PARTIAL,
  47} commit_style;
  48
  49static const char *logfile, *force_author;
  50static const char *template_file;
  51static char *edit_message, *use_message;
  52static char *author_name, *author_email, *author_date;
  53static int all, edit_flag, also, interactive, only, amend, signoff;
  54static int quiet, verbose, no_verify, allow_empty;
  55static char *untracked_files_arg;
  56/*
  57 * The default commit message cleanup mode will remove the lines
  58 * beginning with # (shell comments) and leading and trailing
  59 * whitespaces (empty lines or containing only whitespaces)
  60 * if editor is used, and only the whitespaces if the message
  61 * is specified explicitly.
  62 */
  63static enum {
  64        CLEANUP_SPACE,
  65        CLEANUP_NONE,
  66        CLEANUP_ALL,
  67} cleanup_mode;
  68static char *cleanup_arg;
  69
  70static int use_editor = 1, initial_commit, in_merge;
  71static const char *only_include_assumed;
  72static struct strbuf message;
  73
  74static int opt_parse_m(const struct option *opt, const char *arg, int unset)
  75{
  76        struct strbuf *buf = opt->value;
  77        if (unset)
  78                strbuf_setlen(buf, 0);
  79        else {
  80                strbuf_addstr(buf, arg);
  81                strbuf_addstr(buf, "\n\n");
  82        }
  83        return 0;
  84}
  85
  86static struct option builtin_commit_options[] = {
  87        OPT__QUIET(&quiet),
  88        OPT__VERBOSE(&verbose),
  89        OPT_GROUP("Commit message options"),
  90
  91        OPT_FILENAME('F', "file", &logfile, "read log from file"),
  92        OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
  93        OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
  94        OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
  95        OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
  96        OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
  97        OPT_FILENAME('t', "template", &template_file, "use specified template file"),
  98        OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
  99
 100        OPT_GROUP("Commit contents options"),
 101        OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
 102        OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
 103        OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
 104        OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
 105        OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
 106        OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
 107        { 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" },
 108        OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
 109        OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
 110
 111        OPT_END()
 112};
 113
 114static void rollback_index_files(void)
 115{
 116        switch (commit_style) {
 117        case COMMIT_AS_IS:
 118                break; /* nothing to do */
 119        case COMMIT_NORMAL:
 120                rollback_lock_file(&index_lock);
 121                break;
 122        case COMMIT_PARTIAL:
 123                rollback_lock_file(&index_lock);
 124                rollback_lock_file(&false_lock);
 125                break;
 126        }
 127}
 128
 129static int commit_index_files(void)
 130{
 131        int err = 0;
 132
 133        switch (commit_style) {
 134        case COMMIT_AS_IS:
 135                break; /* nothing to do */
 136        case COMMIT_NORMAL:
 137                err = commit_lock_file(&index_lock);
 138                break;
 139        case COMMIT_PARTIAL:
 140                err = commit_lock_file(&index_lock);
 141                rollback_lock_file(&false_lock);
 142                break;
 143        }
 144
 145        return err;
 146}
 147
 148/*
 149 * Take a union of paths in the index and the named tree (typically, "HEAD"),
 150 * and return the paths that match the given pattern in list.
 151 */
 152static int list_paths(struct string_list *list, const char *with_tree,
 153                      const char *prefix, const char **pattern)
 154{
 155        int i;
 156        char *m;
 157
 158        for (i = 0; pattern[i]; i++)
 159                ;
 160        m = xcalloc(1, i);
 161
 162        if (with_tree)
 163                overlay_tree_on_cache(with_tree, prefix);
 164
 165        for (i = 0; i < active_nr; i++) {
 166                struct cache_entry *ce = active_cache[i];
 167                if (ce->ce_flags & CE_UPDATE)
 168                        continue;
 169                if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
 170                        continue;
 171                string_list_insert(ce->name, list);
 172        }
 173
 174        return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
 175}
 176
 177static void add_remove_files(struct string_list *list)
 178{
 179        int i;
 180        for (i = 0; i < list->nr; i++) {
 181                struct stat st;
 182                struct string_list_item *p = &(list->items[i]);
 183
 184                if (!lstat(p->string, &st)) {
 185                        if (add_to_cache(p->string, &st, 0))
 186                                die("updating files failed");
 187                } else
 188                        remove_file_from_cache(p->string);
 189        }
 190}
 191
 192static void create_base_index(void)
 193{
 194        struct tree *tree;
 195        struct unpack_trees_options opts;
 196        struct tree_desc t;
 197
 198        if (initial_commit) {
 199                discard_cache();
 200                return;
 201        }
 202
 203        memset(&opts, 0, sizeof(opts));
 204        opts.head_idx = 1;
 205        opts.index_only = 1;
 206        opts.merge = 1;
 207        opts.src_index = &the_index;
 208        opts.dst_index = &the_index;
 209
 210        opts.fn = oneway_merge;
 211        tree = parse_tree_indirect(head_sha1);
 212        if (!tree)
 213                die("failed to unpack HEAD tree object");
 214        parse_tree(tree);
 215        init_tree_desc(&t, tree->buffer, tree->size);
 216        if (unpack_trees(1, &t, &opts))
 217                exit(128); /* We've already reported the error, finish dying */
 218}
 219
 220static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
 221{
 222        int fd;
 223        struct string_list partial;
 224        const char **pathspec = NULL;
 225        int refresh_flags = REFRESH_QUIET;
 226
 227        if (is_status)
 228                refresh_flags |= REFRESH_UNMERGED;
 229        if (interactive) {
 230                if (interactive_add(argc, argv, prefix) != 0)
 231                        die("interactive add failed");
 232                if (read_cache_preload(NULL) < 0)
 233                        die("index file corrupt");
 234                commit_style = COMMIT_AS_IS;
 235                return get_index_file();
 236        }
 237
 238        if (*argv)
 239                pathspec = get_pathspec(prefix, argv);
 240
 241        if (read_cache_preload(pathspec) < 0)
 242                die("index file corrupt");
 243
 244        /*
 245         * Non partial, non as-is commit.
 246         *
 247         * (1) get the real index;
 248         * (2) update the_index as necessary;
 249         * (3) write the_index out to the real index (still locked);
 250         * (4) return the name of the locked index file.
 251         *
 252         * The caller should run hooks on the locked real index, and
 253         * (A) if all goes well, commit the real index;
 254         * (B) on failure, rollback the real index.
 255         */
 256        if (all || (also && pathspec && *pathspec)) {
 257                int fd = hold_locked_index(&index_lock, 1);
 258                add_files_to_cache(also ? prefix : NULL, pathspec, 0);
 259                refresh_cache(refresh_flags);
 260                if (write_cache(fd, active_cache, active_nr) ||
 261                    close_lock_file(&index_lock))
 262                        die("unable to write new_index file");
 263                commit_style = COMMIT_NORMAL;
 264                return index_lock.filename;
 265        }
 266
 267        /*
 268         * As-is commit.
 269         *
 270         * (1) return the name of the real index file.
 271         *
 272         * The caller should run hooks on the real index, and run
 273         * hooks on the real index, and create commit from the_index.
 274         * We still need to refresh the index here.
 275         */
 276        if (!pathspec || !*pathspec) {
 277                fd = hold_locked_index(&index_lock, 1);
 278                refresh_cache(refresh_flags);
 279                if (write_cache(fd, active_cache, active_nr) ||
 280                    commit_locked_index(&index_lock))
 281                        die("unable to write new_index file");
 282                commit_style = COMMIT_AS_IS;
 283                return get_index_file();
 284        }
 285
 286        /*
 287         * A partial commit.
 288         *
 289         * (0) find the set of affected paths;
 290         * (1) get lock on the real index file;
 291         * (2) update the_index with the given paths;
 292         * (3) write the_index out to the real index (still locked);
 293         * (4) get lock on the false index file;
 294         * (5) reset the_index from HEAD;
 295         * (6) update the_index the same way as (2);
 296         * (7) write the_index out to the false index file;
 297         * (8) return the name of the false index file (still locked);
 298         *
 299         * The caller should run hooks on the locked false index, and
 300         * create commit from it.  Then
 301         * (A) if all goes well, commit the real index;
 302         * (B) on failure, rollback the real index;
 303         * In either case, rollback the false index.
 304         */
 305        commit_style = COMMIT_PARTIAL;
 306
 307        if (file_exists(git_path("MERGE_HEAD")))
 308                die("cannot do a partial commit during a merge.");
 309
 310        memset(&partial, 0, sizeof(partial));
 311        partial.strdup_strings = 1;
 312        if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
 313                exit(1);
 314
 315        discard_cache();
 316        if (read_cache() < 0)
 317                die("cannot read the index");
 318
 319        fd = hold_locked_index(&index_lock, 1);
 320        add_remove_files(&partial);
 321        refresh_cache(REFRESH_QUIET);
 322        if (write_cache(fd, active_cache, active_nr) ||
 323            close_lock_file(&index_lock))
 324                die("unable to write new_index file");
 325
 326        fd = hold_lock_file_for_update(&false_lock,
 327                                       git_path("next-index-%"PRIuMAX,
 328                                                (uintmax_t) getpid()),
 329                                       LOCK_DIE_ON_ERROR);
 330
 331        create_base_index();
 332        add_remove_files(&partial);
 333        refresh_cache(REFRESH_QUIET);
 334
 335        if (write_cache(fd, active_cache, active_nr) ||
 336            close_lock_file(&false_lock))
 337                die("unable to write temporary index file");
 338
 339        discard_cache();
 340        read_cache_from(false_lock.filename);
 341
 342        return false_lock.filename;
 343}
 344
 345static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn)
 346{
 347        struct wt_status s;
 348
 349        wt_status_prepare(&s);
 350        if (wt_status_relative_paths)
 351                s.prefix = prefix;
 352
 353        if (amend) {
 354                s.amend = 1;
 355                s.reference = "HEAD^1";
 356        }
 357        s.verbose = verbose;
 358        s.untracked = (show_untracked_files == SHOW_ALL_UNTRACKED_FILES);
 359        s.index_file = index_file;
 360        s.fp = fp;
 361        s.nowarn = nowarn;
 362
 363        wt_status_print(&s);
 364
 365        return s.commitable;
 366}
 367
 368static int is_a_merge(const unsigned char *sha1)
 369{
 370        struct commit *commit = lookup_commit(sha1);
 371        if (!commit || parse_commit(commit))
 372                die("could not parse HEAD commit");
 373        return !!(commit->parents && commit->parents->next);
 374}
 375
 376static const char sign_off_header[] = "Signed-off-by: ";
 377
 378static void determine_author_info(void)
 379{
 380        char *name, *email, *date;
 381
 382        name = getenv("GIT_AUTHOR_NAME");
 383        email = getenv("GIT_AUTHOR_EMAIL");
 384        date = getenv("GIT_AUTHOR_DATE");
 385
 386        if (use_message) {
 387                const char *a, *lb, *rb, *eol;
 388
 389                a = strstr(use_message_buffer, "\nauthor ");
 390                if (!a)
 391                        die("invalid commit: %s", use_message);
 392
 393                lb = strstr(a + 8, " <");
 394                rb = strstr(a + 8, "> ");
 395                eol = strchr(a + 8, '\n');
 396                if (!lb || !rb || !eol)
 397                        die("invalid commit: %s", use_message);
 398
 399                name = xstrndup(a + 8, lb - (a + 8));
 400                email = xstrndup(lb + 2, rb - (lb + 2));
 401                date = xstrndup(rb + 2, eol - (rb + 2));
 402        }
 403
 404        if (force_author) {
 405                const char *lb = strstr(force_author, " <");
 406                const char *rb = strchr(force_author, '>');
 407
 408                if (!lb || !rb)
 409                        die("malformed --author parameter");
 410                name = xstrndup(force_author, lb - force_author);
 411                email = xstrndup(lb + 2, rb - (lb + 2));
 412        }
 413
 414        author_name = name;
 415        author_email = email;
 416        author_date = date;
 417}
 418
 419static int prepare_to_commit(const char *index_file, const char *prefix)
 420{
 421        struct stat statbuf;
 422        int commitable, saved_color_setting;
 423        struct strbuf sb = STRBUF_INIT;
 424        char *buffer;
 425        FILE *fp;
 426        const char *hook_arg1 = NULL;
 427        const char *hook_arg2 = NULL;
 428        int ident_shown = 0;
 429
 430        if (!no_verify && run_hook(index_file, "pre-commit", NULL))
 431                return 0;
 432
 433        if (message.len) {
 434                strbuf_addbuf(&sb, &message);
 435                hook_arg1 = "message";
 436        } else if (logfile && !strcmp(logfile, "-")) {
 437                if (isatty(0))
 438                        fprintf(stderr, "(reading log message from standard input)\n");
 439                if (strbuf_read(&sb, 0, 0) < 0)
 440                        die_errno("could not read log from standard input");
 441                hook_arg1 = "message";
 442        } else if (logfile) {
 443                if (strbuf_read_file(&sb, logfile, 0) < 0)
 444                        die_errno("could not read log file '%s'",
 445                                  logfile);
 446                hook_arg1 = "message";
 447        } else if (use_message) {
 448                buffer = strstr(use_message_buffer, "\n\n");
 449                if (!buffer || buffer[2] == '\0')
 450                        die("commit has empty message");
 451                strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
 452                hook_arg1 = "commit";
 453                hook_arg2 = use_message;
 454        } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
 455                if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
 456                        die_errno("could not read MERGE_MSG");
 457                hook_arg1 = "merge";
 458        } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
 459                if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
 460                        die_errno("could not read SQUASH_MSG");
 461                hook_arg1 = "squash";
 462        } else if (template_file && !stat(template_file, &statbuf)) {
 463                if (strbuf_read_file(&sb, template_file, 0) < 0)
 464                        die_errno("could not read '%s'", template_file);
 465                hook_arg1 = "template";
 466        }
 467
 468        /*
 469         * This final case does not modify the template message,
 470         * it just sets the argument to the prepare-commit-msg hook.
 471         */
 472        else if (in_merge)
 473                hook_arg1 = "merge";
 474
 475        fp = fopen(git_path(commit_editmsg), "w");
 476        if (fp == NULL)
 477                die_errno("could not open '%s'", git_path(commit_editmsg));
 478
 479        if (cleanup_mode != CLEANUP_NONE)
 480                stripspace(&sb, 0);
 481
 482        if (signoff) {
 483                struct strbuf sob = STRBUF_INIT;
 484                int i;
 485
 486                strbuf_addstr(&sob, sign_off_header);
 487                strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
 488                                             getenv("GIT_COMMITTER_EMAIL")));
 489                strbuf_addch(&sob, '\n');
 490                for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
 491                        ; /* do nothing */
 492                if (prefixcmp(sb.buf + i, sob.buf)) {
 493                        if (prefixcmp(sb.buf + i, sign_off_header))
 494                                strbuf_addch(&sb, '\n');
 495                        strbuf_addbuf(&sb, &sob);
 496                }
 497                strbuf_release(&sob);
 498        }
 499
 500        if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
 501                die_errno("could not write commit template");
 502
 503        strbuf_release(&sb);
 504
 505        determine_author_info();
 506
 507        /* This checks if committer ident is explicitly given */
 508        git_committer_info(0);
 509        if (use_editor) {
 510                char *author_ident;
 511                const char *committer_ident;
 512
 513                if (in_merge)
 514                        fprintf(fp,
 515                                "#\n"
 516                                "# It looks like you may be committing a MERGE.\n"
 517                                "# If this is not correct, please remove the file\n"
 518                                "#      %s\n"
 519                                "# and try again.\n"
 520                                "#\n",
 521                                git_path("MERGE_HEAD"));
 522
 523                fprintf(fp,
 524                        "\n"
 525                        "# Please enter the commit message for your changes.");
 526                if (cleanup_mode == CLEANUP_ALL)
 527                        fprintf(fp,
 528                                " Lines starting\n"
 529                                "# with '#' will be ignored, and an empty"
 530                                " message aborts the commit.\n");
 531                else /* CLEANUP_SPACE, that is. */
 532                        fprintf(fp,
 533                                " Lines starting\n"
 534                                "# with '#' will be kept; you may remove them"
 535                                " yourself if you want to.\n"
 536                                "# An empty message aborts the commit.\n");
 537                if (only_include_assumed)
 538                        fprintf(fp, "# %s\n", only_include_assumed);
 539
 540                author_ident = xstrdup(fmt_name(author_name, author_email));
 541                committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
 542                                           getenv("GIT_COMMITTER_EMAIL"));
 543                if (strcmp(author_ident, committer_ident))
 544                        fprintf(fp,
 545                                "%s"
 546                                "# Author:    %s\n",
 547                                ident_shown++ ? "" : "#\n",
 548                                author_ident);
 549                free(author_ident);
 550
 551                if (!user_ident_explicitly_given)
 552                        fprintf(fp,
 553                                "%s"
 554                                "# Committer: %s\n",
 555                                ident_shown++ ? "" : "#\n",
 556                                committer_ident);
 557
 558                if (ident_shown)
 559                        fprintf(fp, "#\n");
 560
 561                saved_color_setting = wt_status_use_color;
 562                wt_status_use_color = 0;
 563                commitable = run_status(fp, index_file, prefix, 1);
 564                wt_status_use_color = saved_color_setting;
 565        } else {
 566                unsigned char sha1[20];
 567                const char *parent = "HEAD";
 568
 569                if (!active_nr && read_cache() < 0)
 570                        die("Cannot read index");
 571
 572                if (amend)
 573                        parent = "HEAD^1";
 574
 575                if (get_sha1(parent, sha1))
 576                        commitable = !!active_nr;
 577                else
 578                        commitable = index_differs_from(parent, 0);
 579        }
 580
 581        fclose(fp);
 582
 583        if (!commitable && !in_merge && !allow_empty &&
 584            !(amend && is_a_merge(head_sha1))) {
 585                run_status(stdout, index_file, prefix, 0);
 586                return 0;
 587        }
 588
 589        /*
 590         * Re-read the index as pre-commit hook could have updated it,
 591         * and write it out as a tree.  We must do this before we invoke
 592         * the editor and after we invoke run_status above.
 593         */
 594        discard_cache();
 595        read_cache_from(index_file);
 596        if (!active_cache_tree)
 597                active_cache_tree = cache_tree();
 598        if (cache_tree_update(active_cache_tree,
 599                              active_cache, active_nr, 0, 0) < 0) {
 600                error("Error building trees");
 601                return 0;
 602        }
 603
 604        if (run_hook(index_file, "prepare-commit-msg",
 605                     git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
 606                return 0;
 607
 608        if (use_editor) {
 609                char index[PATH_MAX];
 610                const char *env[2] = { index, NULL };
 611                snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 612                if (launch_editor(git_path(commit_editmsg), NULL, env)) {
 613                        fprintf(stderr,
 614                        "Please supply the message using either -m or -F option.\n");
 615                        exit(1);
 616                }
 617        }
 618
 619        if (!no_verify &&
 620            run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
 621                return 0;
 622        }
 623
 624        return 1;
 625}
 626
 627/*
 628 * Find out if the message in the strbuf contains only whitespace and
 629 * Signed-off-by lines.
 630 */
 631static int message_is_empty(struct strbuf *sb)
 632{
 633        struct strbuf tmpl = STRBUF_INIT;
 634        const char *nl;
 635        int eol, i, start = 0;
 636
 637        if (cleanup_mode == CLEANUP_NONE && sb->len)
 638                return 0;
 639
 640        /* See if the template is just a prefix of the message. */
 641        if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
 642                stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
 643                if (start + tmpl.len <= sb->len &&
 644                    memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
 645                        start += tmpl.len;
 646        }
 647        strbuf_release(&tmpl);
 648
 649        /* Check if the rest is just whitespace and Signed-of-by's. */
 650        for (i = start; i < sb->len; i++) {
 651                nl = memchr(sb->buf + i, '\n', sb->len - i);
 652                if (nl)
 653                        eol = nl - sb->buf;
 654                else
 655                        eol = sb->len;
 656
 657                if (strlen(sign_off_header) <= eol - i &&
 658                    !prefixcmp(sb->buf + i, sign_off_header)) {
 659                        i = eol;
 660                        continue;
 661                }
 662                while (i < eol)
 663                        if (!isspace(sb->buf[i++]))
 664                                return 0;
 665        }
 666
 667        return 1;
 668}
 669
 670static const char *find_author_by_nickname(const char *name)
 671{
 672        struct rev_info revs;
 673        struct commit *commit;
 674        struct strbuf buf = STRBUF_INIT;
 675        const char *av[20];
 676        int ac = 0;
 677
 678        init_revisions(&revs, NULL);
 679        strbuf_addf(&buf, "--author=%s", name);
 680        av[++ac] = "--all";
 681        av[++ac] = "-i";
 682        av[++ac] = buf.buf;
 683        av[++ac] = NULL;
 684        setup_revisions(ac, av, &revs, NULL);
 685        prepare_revision_walk(&revs);
 686        commit = get_revision(&revs);
 687        if (commit) {
 688                strbuf_release(&buf);
 689                format_commit_message(commit, "%an <%ae>", &buf, DATE_NORMAL);
 690                return strbuf_detach(&buf, NULL);
 691        }
 692        die("No existing author found with '%s'", name);
 693}
 694
 695static int parse_and_validate_options(int argc, const char *argv[],
 696                                      const char * const usage[],
 697                                      const char *prefix)
 698{
 699        int f = 0;
 700
 701        argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
 702                             0);
 703
 704        if (force_author && !strchr(force_author, '>'))
 705                force_author = find_author_by_nickname(force_author);
 706
 707        if (logfile || message.len || use_message)
 708                use_editor = 0;
 709        if (edit_flag)
 710                use_editor = 1;
 711        if (!use_editor)
 712                setenv("GIT_EDITOR", ":", 1);
 713
 714        if (get_sha1("HEAD", head_sha1))
 715                initial_commit = 1;
 716
 717        if (!get_sha1("MERGE_HEAD", merge_head_sha1))
 718                in_merge = 1;
 719
 720        /* Sanity check options */
 721        if (amend && initial_commit)
 722                die("You have nothing to amend.");
 723        if (amend && in_merge)
 724                die("You are in the middle of a merge -- cannot amend.");
 725
 726        if (use_message)
 727                f++;
 728        if (edit_message)
 729                f++;
 730        if (logfile)
 731                f++;
 732        if (f > 1)
 733                die("Only one of -c/-C/-F can be used.");
 734        if (message.len && f > 0)
 735                die("Option -m cannot be combined with -c/-C/-F.");
 736        if (edit_message)
 737                use_message = edit_message;
 738        if (amend && !use_message)
 739                use_message = "HEAD";
 740        if (use_message) {
 741                unsigned char sha1[20];
 742                static char utf8[] = "UTF-8";
 743                const char *out_enc;
 744                char *enc, *end;
 745                struct commit *commit;
 746
 747                if (get_sha1(use_message, sha1))
 748                        die("could not lookup commit %s", use_message);
 749                commit = lookup_commit_reference(sha1);
 750                if (!commit || parse_commit(commit))
 751                        die("could not parse commit %s", use_message);
 752
 753                enc = strstr(commit->buffer, "\nencoding");
 754                if (enc) {
 755                        end = strchr(enc + 10, '\n');
 756                        enc = xstrndup(enc + 10, end - (enc + 10));
 757                } else {
 758                        enc = utf8;
 759                }
 760                out_enc = git_commit_encoding ? git_commit_encoding : utf8;
 761
 762                if (strcmp(out_enc, enc))
 763                        use_message_buffer =
 764                                reencode_string(commit->buffer, out_enc, enc);
 765
 766                /*
 767                 * If we failed to reencode the buffer, just copy it
 768                 * byte for byte so the user can try to fix it up.
 769                 * This also handles the case where input and output
 770                 * encodings are identical.
 771                 */
 772                if (use_message_buffer == NULL)
 773                        use_message_buffer = xstrdup(commit->buffer);
 774                if (enc != utf8)
 775                        free(enc);
 776        }
 777
 778        if (!!also + !!only + !!all + !!interactive > 1)
 779                die("Only one of --include/--only/--all/--interactive can be used.");
 780        if (argc == 0 && (also || (only && !amend)))
 781                die("No paths with --include/--only does not make sense.");
 782        if (argc == 0 && only && amend)
 783                only_include_assumed = "Clever... amending the last one with dirty index.";
 784        if (argc > 0 && !also && !only)
 785                only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
 786        if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
 787                cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
 788        else if (!strcmp(cleanup_arg, "verbatim"))
 789                cleanup_mode = CLEANUP_NONE;
 790        else if (!strcmp(cleanup_arg, "whitespace"))
 791                cleanup_mode = CLEANUP_SPACE;
 792        else if (!strcmp(cleanup_arg, "strip"))
 793                cleanup_mode = CLEANUP_ALL;
 794        else
 795                die("Invalid cleanup mode %s", cleanup_arg);
 796
 797        if (!untracked_files_arg)
 798                ; /* default already initialized */
 799        else if (!strcmp(untracked_files_arg, "no"))
 800                show_untracked_files = SHOW_NO_UNTRACKED_FILES;
 801        else if (!strcmp(untracked_files_arg, "normal"))
 802                show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
 803        else if (!strcmp(untracked_files_arg, "all"))
 804                show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
 805        else
 806                die("Invalid untracked files mode '%s'", untracked_files_arg);
 807
 808        if (all && argc > 0)
 809                die("Paths with -a does not make sense.");
 810        else if (interactive && argc > 0)
 811                die("Paths with --interactive does not make sense.");
 812
 813        return argc;
 814}
 815
 816int cmd_status(int argc, const char **argv, const char *prefix)
 817{
 818        const char *index_file;
 819        int commitable;
 820
 821        git_config(git_status_config, NULL);
 822
 823        if (wt_status_use_color == -1)
 824                wt_status_use_color = git_use_color_default;
 825
 826        if (diff_use_color_default == -1)
 827                diff_use_color_default = git_use_color_default;
 828
 829        argc = parse_and_validate_options(argc, argv, builtin_status_usage, prefix);
 830
 831        index_file = prepare_index(argc, argv, prefix, 1);
 832
 833        commitable = run_status(stdout, index_file, prefix, 0);
 834
 835        rollback_index_files();
 836
 837        return commitable ? 0 : 1;
 838}
 839
 840static void print_summary(const char *prefix, const unsigned char *sha1)
 841{
 842        struct rev_info rev;
 843        struct commit *commit;
 844        static const char *format = "format:%h] %s";
 845        unsigned char junk_sha1[20];
 846        const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
 847
 848        commit = lookup_commit(sha1);
 849        if (!commit)
 850                die("couldn't look up newly created commit");
 851        if (!commit || parse_commit(commit))
 852                die("could not parse newly created commit");
 853
 854        init_revisions(&rev, prefix);
 855        setup_revisions(0, NULL, &rev, NULL);
 856
 857        rev.abbrev = 0;
 858        rev.diff = 1;
 859        rev.diffopt.output_format =
 860                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
 861
 862        rev.verbose_header = 1;
 863        rev.show_root_diff = 1;
 864        get_commit_format(format, &rev);
 865        rev.always_show_header = 0;
 866        rev.diffopt.detect_rename = 1;
 867        rev.diffopt.rename_limit = 100;
 868        rev.diffopt.break_opt = 0;
 869        diff_setup_done(&rev.diffopt);
 870
 871        printf("[%s%s ",
 872                !prefixcmp(head, "refs/heads/") ?
 873                        head + 11 :
 874                        !strcmp(head, "HEAD") ?
 875                                "detached HEAD" :
 876                                head,
 877                initial_commit ? " (root-commit)" : "");
 878
 879        if (!log_tree_commit(&rev, commit)) {
 880                struct strbuf buf = STRBUF_INIT;
 881                format_commit_message(commit, format + 7, &buf, DATE_NORMAL);
 882                printf("%s\n", buf.buf);
 883                strbuf_release(&buf);
 884        }
 885}
 886
 887static int git_commit_config(const char *k, const char *v, void *cb)
 888{
 889        if (!strcmp(k, "commit.template"))
 890                return git_config_string(&template_file, k, v);
 891
 892        return git_status_config(k, v, cb);
 893}
 894
 895int cmd_commit(int argc, const char **argv, const char *prefix)
 896{
 897        struct strbuf sb = STRBUF_INIT;
 898        const char *index_file, *reflog_msg;
 899        char *nl, *p;
 900        unsigned char commit_sha1[20];
 901        struct ref_lock *ref_lock;
 902        struct commit_list *parents = NULL, **pptr = &parents;
 903        struct stat statbuf;
 904        int allow_fast_forward = 1;
 905
 906        git_config(git_commit_config, NULL);
 907
 908        if (wt_status_use_color == -1)
 909                wt_status_use_color = git_use_color_default;
 910
 911        argc = parse_and_validate_options(argc, argv, builtin_commit_usage, prefix);
 912
 913        index_file = prepare_index(argc, argv, prefix, 0);
 914
 915        /* Set up everything for writing the commit object.  This includes
 916           running hooks, writing the trees, and interacting with the user.  */
 917        if (!prepare_to_commit(index_file, prefix)) {
 918                rollback_index_files();
 919                return 1;
 920        }
 921
 922        /* Determine parents */
 923        if (initial_commit) {
 924                reflog_msg = "commit (initial)";
 925        } else if (amend) {
 926                struct commit_list *c;
 927                struct commit *commit;
 928
 929                reflog_msg = "commit (amend)";
 930                commit = lookup_commit(head_sha1);
 931                if (!commit || parse_commit(commit))
 932                        die("could not parse HEAD commit");
 933
 934                for (c = commit->parents; c; c = c->next)
 935                        pptr = &commit_list_insert(c->item, pptr)->next;
 936        } else if (in_merge) {
 937                struct strbuf m = STRBUF_INIT;
 938                FILE *fp;
 939
 940                reflog_msg = "commit (merge)";
 941                pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
 942                fp = fopen(git_path("MERGE_HEAD"), "r");
 943                if (fp == NULL)
 944                        die_errno("could not open '%s' for reading",
 945                                  git_path("MERGE_HEAD"));
 946                while (strbuf_getline(&m, fp, '\n') != EOF) {
 947                        unsigned char sha1[20];
 948                        if (get_sha1_hex(m.buf, sha1) < 0)
 949                                die("Corrupt MERGE_HEAD file (%s)", m.buf);
 950                        pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
 951                }
 952                fclose(fp);
 953                strbuf_release(&m);
 954                if (!stat(git_path("MERGE_MODE"), &statbuf)) {
 955                        if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
 956                                die_errno("could not read MERGE_MODE");
 957                        if (!strcmp(sb.buf, "no-ff"))
 958                                allow_fast_forward = 0;
 959                }
 960                if (allow_fast_forward)
 961                        parents = reduce_heads(parents);
 962        } else {
 963                reflog_msg = "commit";
 964                pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
 965        }
 966
 967        /* Finally, get the commit message */
 968        strbuf_reset(&sb);
 969        if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
 970                int saved_errno = errno;
 971                rollback_index_files();
 972                die("could not read commit message: %s", strerror(saved_errno));
 973        }
 974
 975        /* Truncate the message just before the diff, if any. */
 976        if (verbose) {
 977                p = strstr(sb.buf, "\ndiff --git ");
 978                if (p != NULL)
 979                        strbuf_setlen(&sb, p - sb.buf + 1);
 980        }
 981
 982        if (cleanup_mode != CLEANUP_NONE)
 983                stripspace(&sb, cleanup_mode == CLEANUP_ALL);
 984        if (message_is_empty(&sb)) {
 985                rollback_index_files();
 986                fprintf(stderr, "Aborting commit due to empty commit message.\n");
 987                exit(1);
 988        }
 989
 990        if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
 991                        fmt_ident(author_name, author_email, author_date,
 992                                IDENT_ERROR_ON_NO_NAME))) {
 993                rollback_index_files();
 994                die("failed to write commit object");
 995        }
 996
 997        ref_lock = lock_any_ref_for_update("HEAD",
 998                                           initial_commit ? NULL : head_sha1,
 999                                           0);
1000
1001        nl = strchr(sb.buf, '\n');
1002        if (nl)
1003                strbuf_setlen(&sb, nl + 1 - sb.buf);
1004        else
1005                strbuf_addch(&sb, '\n');
1006        strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1007        strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1008
1009        if (!ref_lock) {
1010                rollback_index_files();
1011                die("cannot lock HEAD ref");
1012        }
1013        if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1014                rollback_index_files();
1015                die("cannot update HEAD ref");
1016        }
1017
1018        unlink(git_path("MERGE_HEAD"));
1019        unlink(git_path("MERGE_MSG"));
1020        unlink(git_path("MERGE_MODE"));
1021        unlink(git_path("SQUASH_MSG"));
1022
1023        if (commit_index_files())
1024                die ("Repository has been updated, but unable to write\n"
1025                     "new_index file. Check that disk is not full or quota is\n"
1026                     "not exceeded, and then \"git reset HEAD\" to recover.");
1027
1028        rerere();
1029        run_hook(get_index_file(), "post-commit", NULL);
1030        if (!quiet)
1031                print_summary(prefix, commit_sha1);
1032
1033        return 0;
1034}