builtin / update-index.con commit index-pack: work around thread-unsafe pread() (3953949)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6#include "cache.h"
   7#include "quote.h"
   8#include "cache-tree.h"
   9#include "tree-walk.h"
  10#include "builtin.h"
  11#include "refs.h"
  12#include "resolve-undo.h"
  13#include "parse-options.h"
  14#include "pathspec.h"
  15
  16/*
  17 * Default to not allowing changes to the list of files. The
  18 * tool doesn't actually care, but this makes it harder to add
  19 * files to the revision control by mistake by doing something
  20 * like "git update-index *" and suddenly having all the object
  21 * files be revision controlled.
  22 */
  23static int allow_add;
  24static int allow_remove;
  25static int allow_replace;
  26static int info_only;
  27static int force_remove;
  28static int verbose;
  29static int mark_valid_only;
  30static int mark_skip_worktree_only;
  31#define MARK_FLAG 1
  32#define UNMARK_FLAG 2
  33
  34__attribute__((format (printf, 1, 2)))
  35static void report(const char *fmt, ...)
  36{
  37        va_list vp;
  38
  39        if (!verbose)
  40                return;
  41
  42        va_start(vp, fmt);
  43        vprintf(fmt, vp);
  44        putchar('\n');
  45        va_end(vp);
  46}
  47
  48static int mark_ce_flags(const char *path, int flag, int mark)
  49{
  50        int namelen = strlen(path);
  51        int pos = cache_name_pos(path, namelen);
  52        if (0 <= pos) {
  53                if (mark)
  54                        active_cache[pos]->ce_flags |= flag;
  55                else
  56                        active_cache[pos]->ce_flags &= ~flag;
  57                cache_tree_invalidate_path(active_cache_tree, path);
  58                active_cache_changed = 1;
  59                return 0;
  60        }
  61        return -1;
  62}
  63
  64static int remove_one_path(const char *path)
  65{
  66        if (!allow_remove)
  67                return error("%s: does not exist and --remove not passed", path);
  68        if (remove_file_from_cache(path))
  69                return error("%s: cannot remove from the index", path);
  70        return 0;
  71}
  72
  73/*
  74 * Handle a path that couldn't be lstat'ed. It's either:
  75 *  - missing file (ENOENT or ENOTDIR). That's ok if we're
  76 *    supposed to be removing it and the removal actually
  77 *    succeeds.
  78 *  - permission error. That's never ok.
  79 */
  80static int process_lstat_error(const char *path, int err)
  81{
  82        if (err == ENOENT || err == ENOTDIR)
  83                return remove_one_path(path);
  84        return error("lstat(\"%s\"): %s", path, strerror(errno));
  85}
  86
  87static int add_one_path(const struct cache_entry *old, const char *path, int len, struct stat *st)
  88{
  89        int option, size;
  90        struct cache_entry *ce;
  91
  92        /* Was the old index entry already up-to-date? */
  93        if (old && !ce_stage(old) && !ce_match_stat(old, st, 0))
  94                return 0;
  95
  96        size = cache_entry_size(len);
  97        ce = xcalloc(1, size);
  98        memcpy(ce->name, path, len);
  99        ce->ce_flags = create_ce_flags(0);
 100        ce->ce_namelen = len;
 101        fill_stat_cache_info(ce, st);
 102        ce->ce_mode = ce_mode_from_stat(old, st->st_mode);
 103
 104        if (index_path(ce->sha1, path, st,
 105                       info_only ? 0 : HASH_WRITE_OBJECT)) {
 106                free(ce);
 107                return -1;
 108        }
 109        option = allow_add ? ADD_CACHE_OK_TO_ADD : 0;
 110        option |= allow_replace ? ADD_CACHE_OK_TO_REPLACE : 0;
 111        if (add_cache_entry(ce, option))
 112                return error("%s: cannot add to the index - missing --add option?", path);
 113        return 0;
 114}
 115
 116/*
 117 * Handle a path that was a directory. Four cases:
 118 *
 119 *  - it's already a gitlink in the index, and we keep it that
 120 *    way, and update it if we can (if we cannot find the HEAD,
 121 *    we're going to keep it unchanged in the index!)
 122 *
 123 *  - it's a *file* in the index, in which case it should be
 124 *    removed as a file if removal is allowed, since it doesn't
 125 *    exist as such any more. If removal isn't allowed, it's
 126 *    an error.
 127 *
 128 *    (NOTE! This is old and arguably fairly strange behaviour.
 129 *    We might want to make this an error unconditionally, and
 130 *    use "--force-remove" if you actually want to force removal).
 131 *
 132 *  - it used to exist as a subdirectory (ie multiple files with
 133 *    this particular prefix) in the index, in which case it's wrong
 134 *    to try to update it as a directory.
 135 *
 136 *  - it doesn't exist at all in the index, but it is a valid
 137 *    git directory, and it should be *added* as a gitlink.
 138 */
 139static int process_directory(const char *path, int len, struct stat *st)
 140{
 141        unsigned char sha1[20];
 142        int pos = cache_name_pos(path, len);
 143
 144        /* Exact match: file or existing gitlink */
 145        if (pos >= 0) {
 146                const struct cache_entry *ce = active_cache[pos];
 147                if (S_ISGITLINK(ce->ce_mode)) {
 148
 149                        /* Do nothing to the index if there is no HEAD! */
 150                        if (resolve_gitlink_ref(path, "HEAD", sha1) < 0)
 151                                return 0;
 152
 153                        return add_one_path(ce, path, len, st);
 154                }
 155                /* Should this be an unconditional error? */
 156                return remove_one_path(path);
 157        }
 158
 159        /* Inexact match: is there perhaps a subdirectory match? */
 160        pos = -pos-1;
 161        while (pos < active_nr) {
 162                const struct cache_entry *ce = active_cache[pos++];
 163
 164                if (strncmp(ce->name, path, len))
 165                        break;
 166                if (ce->name[len] > '/')
 167                        break;
 168                if (ce->name[len] < '/')
 169                        continue;
 170
 171                /* Subdirectory match - error out */
 172                return error("%s: is a directory - add individual files instead", path);
 173        }
 174
 175        /* No match - should we add it as a gitlink? */
 176        if (!resolve_gitlink_ref(path, "HEAD", sha1))
 177                return add_one_path(NULL, path, len, st);
 178
 179        /* Error out. */
 180        return error("%s: is a directory - add files inside instead", path);
 181}
 182
 183static int process_path(const char *path)
 184{
 185        int pos, len;
 186        struct stat st;
 187        const struct cache_entry *ce;
 188
 189        len = strlen(path);
 190        if (has_symlink_leading_path(path, len))
 191                return error("'%s' is beyond a symbolic link", path);
 192
 193        pos = cache_name_pos(path, len);
 194        ce = pos < 0 ? NULL : active_cache[pos];
 195        if (ce && ce_skip_worktree(ce)) {
 196                /*
 197                 * working directory version is assumed "good"
 198                 * so updating it does not make sense.
 199                 * On the other hand, removing it from index should work
 200                 */
 201                if (allow_remove && remove_file_from_cache(path))
 202                        return error("%s: cannot remove from the index", path);
 203                return 0;
 204        }
 205
 206        /*
 207         * First things first: get the stat information, to decide
 208         * what to do about the pathname!
 209         */
 210        if (lstat(path, &st) < 0)
 211                return process_lstat_error(path, errno);
 212
 213        if (S_ISDIR(st.st_mode))
 214                return process_directory(path, len, &st);
 215
 216        return add_one_path(ce, path, len, &st);
 217}
 218
 219static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
 220                         const char *path, int stage)
 221{
 222        int size, len, option;
 223        struct cache_entry *ce;
 224
 225        if (!verify_path(path))
 226                return error("Invalid path '%s'", path);
 227
 228        len = strlen(path);
 229        size = cache_entry_size(len);
 230        ce = xcalloc(1, size);
 231
 232        hashcpy(ce->sha1, sha1);
 233        memcpy(ce->name, path, len);
 234        ce->ce_flags = create_ce_flags(stage);
 235        ce->ce_namelen = len;
 236        ce->ce_mode = create_ce_mode(mode);
 237        if (assume_unchanged)
 238                ce->ce_flags |= CE_VALID;
 239        option = allow_add ? ADD_CACHE_OK_TO_ADD : 0;
 240        option |= allow_replace ? ADD_CACHE_OK_TO_REPLACE : 0;
 241        if (add_cache_entry(ce, option))
 242                return error("%s: cannot add to the index - missing --add option?",
 243                             path);
 244        report("add '%s'", path);
 245        return 0;
 246}
 247
 248static void chmod_path(int flip, const char *path)
 249{
 250        int pos;
 251        struct cache_entry *ce;
 252        unsigned int mode;
 253
 254        pos = cache_name_pos(path, strlen(path));
 255        if (pos < 0)
 256                goto fail;
 257        ce = active_cache[pos];
 258        mode = ce->ce_mode;
 259        if (!S_ISREG(mode))
 260                goto fail;
 261        switch (flip) {
 262        case '+':
 263                ce->ce_mode |= 0111; break;
 264        case '-':
 265                ce->ce_mode &= ~0111; break;
 266        default:
 267                goto fail;
 268        }
 269        cache_tree_invalidate_path(active_cache_tree, path);
 270        active_cache_changed = 1;
 271        report("chmod %cx '%s'", flip, path);
 272        return;
 273 fail:
 274        die("git update-index: cannot chmod %cx '%s'", flip, path);
 275}
 276
 277static void update_one(const char *path, const char *prefix, int prefix_length)
 278{
 279        const char *p = prefix_path(prefix, prefix_length, path);
 280        if (!verify_path(p)) {
 281                fprintf(stderr, "Ignoring path %s\n", path);
 282                goto free_return;
 283        }
 284        if (mark_valid_only) {
 285                if (mark_ce_flags(p, CE_VALID, mark_valid_only == MARK_FLAG))
 286                        die("Unable to mark file %s", path);
 287                goto free_return;
 288        }
 289        if (mark_skip_worktree_only) {
 290                if (mark_ce_flags(p, CE_SKIP_WORKTREE, mark_skip_worktree_only == MARK_FLAG))
 291                        die("Unable to mark file %s", path);
 292                goto free_return;
 293        }
 294
 295        if (force_remove) {
 296                if (remove_file_from_cache(p))
 297                        die("git update-index: unable to remove %s", path);
 298                report("remove '%s'", path);
 299                goto free_return;
 300        }
 301        if (process_path(p))
 302                die("Unable to process path %s", path);
 303        report("add '%s'", path);
 304 free_return:
 305        if (p < path || p > path + strlen(path))
 306                free((char *)p);
 307}
 308
 309static void read_index_info(int line_termination)
 310{
 311        struct strbuf buf = STRBUF_INIT;
 312        struct strbuf uq = STRBUF_INIT;
 313
 314        while (strbuf_getline(&buf, stdin, line_termination) != EOF) {
 315                char *ptr, *tab;
 316                char *path_name;
 317                unsigned char sha1[20];
 318                unsigned int mode;
 319                unsigned long ul;
 320                int stage;
 321
 322                /* This reads lines formatted in one of three formats:
 323                 *
 324                 * (1) mode         SP sha1          TAB path
 325                 * The first format is what "git apply --index-info"
 326                 * reports, and used to reconstruct a partial tree
 327                 * that is used for phony merge base tree when falling
 328                 * back on 3-way merge.
 329                 *
 330                 * (2) mode SP type SP sha1          TAB path
 331                 * The second format is to stuff "git ls-tree" output
 332                 * into the index file.
 333                 *
 334                 * (3) mode         SP sha1 SP stage TAB path
 335                 * This format is to put higher order stages into the
 336                 * index file and matches "git ls-files --stage" output.
 337                 */
 338                errno = 0;
 339                ul = strtoul(buf.buf, &ptr, 8);
 340                if (ptr == buf.buf || *ptr != ' '
 341                    || errno || (unsigned int) ul != ul)
 342                        goto bad_line;
 343                mode = ul;
 344
 345                tab = strchr(ptr, '\t');
 346                if (!tab || tab - ptr < 41)
 347                        goto bad_line;
 348
 349                if (tab[-2] == ' ' && '0' <= tab[-1] && tab[-1] <= '3') {
 350                        stage = tab[-1] - '0';
 351                        ptr = tab + 1; /* point at the head of path */
 352                        tab = tab - 2; /* point at tail of sha1 */
 353                }
 354                else {
 355                        stage = 0;
 356                        ptr = tab + 1; /* point at the head of path */
 357                }
 358
 359                if (get_sha1_hex(tab - 40, sha1) || tab[-41] != ' ')
 360                        goto bad_line;
 361
 362                path_name = ptr;
 363                if (line_termination && path_name[0] == '"') {
 364                        strbuf_reset(&uq);
 365                        if (unquote_c_style(&uq, path_name, NULL)) {
 366                                die("git update-index: bad quoting of path name");
 367                        }
 368                        path_name = uq.buf;
 369                }
 370
 371                if (!verify_path(path_name)) {
 372                        fprintf(stderr, "Ignoring path %s\n", path_name);
 373                        continue;
 374                }
 375
 376                if (!mode) {
 377                        /* mode == 0 means there is no such path -- remove */
 378                        if (remove_file_from_cache(path_name))
 379                                die("git update-index: unable to remove %s",
 380                                    ptr);
 381                }
 382                else {
 383                        /* mode ' ' sha1 '\t' name
 384                         * ptr[-1] points at tab,
 385                         * ptr[-41] is at the beginning of sha1
 386                         */
 387                        ptr[-42] = ptr[-1] = 0;
 388                        if (add_cacheinfo(mode, sha1, path_name, stage))
 389                                die("git update-index: unable to update %s",
 390                                    path_name);
 391                }
 392                continue;
 393
 394        bad_line:
 395                die("malformed index info %s", buf.buf);
 396        }
 397        strbuf_release(&buf);
 398        strbuf_release(&uq);
 399}
 400
 401static const char * const update_index_usage[] = {
 402        N_("git update-index [options] [--] [<file>...]"),
 403        NULL
 404};
 405
 406static unsigned char head_sha1[20];
 407static unsigned char merge_head_sha1[20];
 408
 409static struct cache_entry *read_one_ent(const char *which,
 410                                        unsigned char *ent, const char *path,
 411                                        int namelen, int stage)
 412{
 413        unsigned mode;
 414        unsigned char sha1[20];
 415        int size;
 416        struct cache_entry *ce;
 417
 418        if (get_tree_entry(ent, path, sha1, &mode)) {
 419                if (which)
 420                        error("%s: not in %s branch.", path, which);
 421                return NULL;
 422        }
 423        if (mode == S_IFDIR) {
 424                if (which)
 425                        error("%s: not a blob in %s branch.", path, which);
 426                return NULL;
 427        }
 428        size = cache_entry_size(namelen);
 429        ce = xcalloc(1, size);
 430
 431        hashcpy(ce->sha1, sha1);
 432        memcpy(ce->name, path, namelen);
 433        ce->ce_flags = create_ce_flags(stage);
 434        ce->ce_namelen = namelen;
 435        ce->ce_mode = create_ce_mode(mode);
 436        return ce;
 437}
 438
 439static int unresolve_one(const char *path)
 440{
 441        int namelen = strlen(path);
 442        int pos;
 443        int ret = 0;
 444        struct cache_entry *ce_2 = NULL, *ce_3 = NULL;
 445
 446        /* See if there is such entry in the index. */
 447        pos = cache_name_pos(path, namelen);
 448        if (0 <= pos) {
 449                /* already merged */
 450                pos = unmerge_cache_entry_at(pos);
 451                if (pos < active_nr) {
 452                        const struct cache_entry *ce = active_cache[pos];
 453                        if (ce_stage(ce) &&
 454                            ce_namelen(ce) == namelen &&
 455                            !memcmp(ce->name, path, namelen))
 456                                return 0;
 457                }
 458                /* no resolve-undo information; fall back */
 459        } else {
 460                /* If there isn't, either it is unmerged, or
 461                 * resolved as "removed" by mistake.  We do not
 462                 * want to do anything in the former case.
 463                 */
 464                pos = -pos-1;
 465                if (pos < active_nr) {
 466                        const struct cache_entry *ce = active_cache[pos];
 467                        if (ce_namelen(ce) == namelen &&
 468                            !memcmp(ce->name, path, namelen)) {
 469                                fprintf(stderr,
 470                                        "%s: skipping still unmerged path.\n",
 471                                        path);
 472                                goto free_return;
 473                        }
 474                }
 475        }
 476
 477        /* Grab blobs from given path from HEAD and MERGE_HEAD,
 478         * stuff HEAD version in stage #2,
 479         * stuff MERGE_HEAD version in stage #3.
 480         */
 481        ce_2 = read_one_ent("our", head_sha1, path, namelen, 2);
 482        ce_3 = read_one_ent("their", merge_head_sha1, path, namelen, 3);
 483
 484        if (!ce_2 || !ce_3) {
 485                ret = -1;
 486                goto free_return;
 487        }
 488        if (!hashcmp(ce_2->sha1, ce_3->sha1) &&
 489            ce_2->ce_mode == ce_3->ce_mode) {
 490                fprintf(stderr, "%s: identical in both, skipping.\n",
 491                        path);
 492                goto free_return;
 493        }
 494
 495        remove_file_from_cache(path);
 496        if (add_cache_entry(ce_2, ADD_CACHE_OK_TO_ADD)) {
 497                error("%s: cannot add our version to the index.", path);
 498                ret = -1;
 499                goto free_return;
 500        }
 501        if (!add_cache_entry(ce_3, ADD_CACHE_OK_TO_ADD))
 502                return 0;
 503        error("%s: cannot add their version to the index.", path);
 504        ret = -1;
 505 free_return:
 506        free(ce_2);
 507        free(ce_3);
 508        return ret;
 509}
 510
 511static void read_head_pointers(void)
 512{
 513        if (read_ref("HEAD", head_sha1))
 514                die("No HEAD -- no initial commit yet?");
 515        if (read_ref("MERGE_HEAD", merge_head_sha1)) {
 516                fprintf(stderr, "Not in the middle of a merge.\n");
 517                exit(0);
 518        }
 519}
 520
 521static int do_unresolve(int ac, const char **av,
 522                        const char *prefix, int prefix_length)
 523{
 524        int i;
 525        int err = 0;
 526
 527        /* Read HEAD and MERGE_HEAD; if MERGE_HEAD does not exist, we
 528         * are not doing a merge, so exit with success status.
 529         */
 530        read_head_pointers();
 531
 532        for (i = 1; i < ac; i++) {
 533                const char *arg = av[i];
 534                const char *p = prefix_path(prefix, prefix_length, arg);
 535                err |= unresolve_one(p);
 536                if (p < arg || p > arg + strlen(arg))
 537                        free((char *)p);
 538        }
 539        return err;
 540}
 541
 542static int do_reupdate(int ac, const char **av,
 543                       const char *prefix, int prefix_length)
 544{
 545        /* Read HEAD and run update-index on paths that are
 546         * merged and already different between index and HEAD.
 547         */
 548        int pos;
 549        int has_head = 1;
 550        struct pathspec pathspec;
 551
 552        parse_pathspec(&pathspec, 0,
 553                       PATHSPEC_PREFER_CWD,
 554                       prefix, av + 1);
 555
 556        if (read_ref("HEAD", head_sha1))
 557                /* If there is no HEAD, that means it is an initial
 558                 * commit.  Update everything in the index.
 559                 */
 560                has_head = 0;
 561 redo:
 562        for (pos = 0; pos < active_nr; pos++) {
 563                const struct cache_entry *ce = active_cache[pos];
 564                struct cache_entry *old = NULL;
 565                int save_nr;
 566
 567                if (ce_stage(ce) || !ce_path_match(ce, &pathspec))
 568                        continue;
 569                if (has_head)
 570                        old = read_one_ent(NULL, head_sha1,
 571                                           ce->name, ce_namelen(ce), 0);
 572                if (old && ce->ce_mode == old->ce_mode &&
 573                    !hashcmp(ce->sha1, old->sha1)) {
 574                        free(old);
 575                        continue; /* unchanged */
 576                }
 577                /* Be careful.  The working tree may not have the
 578                 * path anymore, in which case, under 'allow_remove',
 579                 * or worse yet 'allow_replace', active_nr may decrease.
 580                 */
 581                save_nr = active_nr;
 582                update_one(ce->name + prefix_length, prefix, prefix_length);
 583                if (save_nr != active_nr)
 584                        goto redo;
 585        }
 586        free_pathspec(&pathspec);
 587        return 0;
 588}
 589
 590struct refresh_params {
 591        unsigned int flags;
 592        int *has_errors;
 593};
 594
 595static int refresh(struct refresh_params *o, unsigned int flag)
 596{
 597        setup_work_tree();
 598        read_cache_preload(NULL);
 599        *o->has_errors |= refresh_cache(o->flags | flag);
 600        return 0;
 601}
 602
 603static int refresh_callback(const struct option *opt,
 604                                const char *arg, int unset)
 605{
 606        return refresh(opt->value, 0);
 607}
 608
 609static int really_refresh_callback(const struct option *opt,
 610                                const char *arg, int unset)
 611{
 612        return refresh(opt->value, REFRESH_REALLY);
 613}
 614
 615static int chmod_callback(const struct option *opt,
 616                                const char *arg, int unset)
 617{
 618        char *flip = opt->value;
 619        if ((arg[0] != '-' && arg[0] != '+') || arg[1] != 'x' || arg[2])
 620                return error("option 'chmod' expects \"+x\" or \"-x\"");
 621        *flip = arg[0];
 622        return 0;
 623}
 624
 625static int resolve_undo_clear_callback(const struct option *opt,
 626                                const char *arg, int unset)
 627{
 628        resolve_undo_clear();
 629        return 0;
 630}
 631
 632static int cacheinfo_callback(struct parse_opt_ctx_t *ctx,
 633                                const struct option *opt, int unset)
 634{
 635        unsigned char sha1[20];
 636        unsigned int mode;
 637
 638        if (ctx->argc <= 3)
 639                return error("option 'cacheinfo' expects three arguments");
 640        if (strtoul_ui(*++ctx->argv, 8, &mode) ||
 641            get_sha1_hex(*++ctx->argv, sha1) ||
 642            add_cacheinfo(mode, sha1, *++ctx->argv, 0))
 643                die("git update-index: --cacheinfo cannot add %s", *ctx->argv);
 644        ctx->argc -= 3;
 645        return 0;
 646}
 647
 648static int stdin_cacheinfo_callback(struct parse_opt_ctx_t *ctx,
 649                              const struct option *opt, int unset)
 650{
 651        int *line_termination = opt->value;
 652
 653        if (ctx->argc != 1)
 654                return error("option '%s' must be the last argument", opt->long_name);
 655        allow_add = allow_replace = allow_remove = 1;
 656        read_index_info(*line_termination);
 657        return 0;
 658}
 659
 660static int stdin_callback(struct parse_opt_ctx_t *ctx,
 661                                const struct option *opt, int unset)
 662{
 663        int *read_from_stdin = opt->value;
 664
 665        if (ctx->argc != 1)
 666                return error("option '%s' must be the last argument", opt->long_name);
 667        *read_from_stdin = 1;
 668        return 0;
 669}
 670
 671static int unresolve_callback(struct parse_opt_ctx_t *ctx,
 672                                const struct option *opt, int flags)
 673{
 674        int *has_errors = opt->value;
 675        const char *prefix = startup_info->prefix;
 676
 677        /* consume remaining arguments. */
 678        *has_errors = do_unresolve(ctx->argc, ctx->argv,
 679                                prefix, prefix ? strlen(prefix) : 0);
 680        if (*has_errors)
 681                active_cache_changed = 0;
 682
 683        ctx->argv += ctx->argc - 1;
 684        ctx->argc = 1;
 685        return 0;
 686}
 687
 688static int reupdate_callback(struct parse_opt_ctx_t *ctx,
 689                                const struct option *opt, int flags)
 690{
 691        int *has_errors = opt->value;
 692        const char *prefix = startup_info->prefix;
 693
 694        /* consume remaining arguments. */
 695        setup_work_tree();
 696        *has_errors = do_reupdate(ctx->argc, ctx->argv,
 697                                prefix, prefix ? strlen(prefix) : 0);
 698        if (*has_errors)
 699                active_cache_changed = 0;
 700
 701        ctx->argv += ctx->argc - 1;
 702        ctx->argc = 1;
 703        return 0;
 704}
 705
 706int cmd_update_index(int argc, const char **argv, const char *prefix)
 707{
 708        int newfd, entries, has_errors = 0, line_termination = '\n';
 709        int read_from_stdin = 0;
 710        int prefix_length = prefix ? strlen(prefix) : 0;
 711        int preferred_index_format = 0;
 712        char set_executable_bit = 0;
 713        struct refresh_params refresh_args = {0, &has_errors};
 714        int lock_error = 0;
 715        struct lock_file *lock_file;
 716        struct parse_opt_ctx_t ctx;
 717        int parseopt_state = PARSE_OPT_UNKNOWN;
 718        struct option options[] = {
 719                OPT_BIT('q', NULL, &refresh_args.flags,
 720                        N_("continue refresh even when index needs update"),
 721                        REFRESH_QUIET),
 722                OPT_BIT(0, "ignore-submodules", &refresh_args.flags,
 723                        N_("refresh: ignore submodules"),
 724                        REFRESH_IGNORE_SUBMODULES),
 725                OPT_SET_INT(0, "add", &allow_add,
 726                        N_("do not ignore new files"), 1),
 727                OPT_SET_INT(0, "replace", &allow_replace,
 728                        N_("let files replace directories and vice-versa"), 1),
 729                OPT_SET_INT(0, "remove", &allow_remove,
 730                        N_("notice files missing from worktree"), 1),
 731                OPT_BIT(0, "unmerged", &refresh_args.flags,
 732                        N_("refresh even if index contains unmerged entries"),
 733                        REFRESH_UNMERGED),
 734                {OPTION_CALLBACK, 0, "refresh", &refresh_args, NULL,
 735                        N_("refresh stat information"),
 736                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 737                        refresh_callback},
 738                {OPTION_CALLBACK, 0, "really-refresh", &refresh_args, NULL,
 739                        N_("like --refresh, but ignore assume-unchanged setting"),
 740                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 741                        really_refresh_callback},
 742                {OPTION_LOWLEVEL_CALLBACK, 0, "cacheinfo", NULL,
 743                        N_("<mode> <object> <path>"),
 744                        N_("add the specified entry to the index"),
 745                        PARSE_OPT_NOARG |       /* disallow --cacheinfo=<mode> form */
 746                        PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
 747                        (parse_opt_cb *) cacheinfo_callback},
 748                {OPTION_CALLBACK, 0, "chmod", &set_executable_bit, N_("(+/-)x"),
 749                        N_("override the executable bit of the listed files"),
 750                        PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
 751                        chmod_callback},
 752                {OPTION_SET_INT, 0, "assume-unchanged", &mark_valid_only, NULL,
 753                        N_("mark files as \"not changing\""),
 754                        PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, MARK_FLAG},
 755                {OPTION_SET_INT, 0, "no-assume-unchanged", &mark_valid_only, NULL,
 756                        N_("clear assumed-unchanged bit"),
 757                        PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, UNMARK_FLAG},
 758                {OPTION_SET_INT, 0, "skip-worktree", &mark_skip_worktree_only, NULL,
 759                        N_("mark files as \"index-only\""),
 760                        PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, MARK_FLAG},
 761                {OPTION_SET_INT, 0, "no-skip-worktree", &mark_skip_worktree_only, NULL,
 762                        N_("clear skip-worktree bit"),
 763                        PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, UNMARK_FLAG},
 764                OPT_SET_INT(0, "info-only", &info_only,
 765                        N_("add to index only; do not add content to object database"), 1),
 766                OPT_SET_INT(0, "force-remove", &force_remove,
 767                        N_("remove named paths even if present in worktree"), 1),
 768                OPT_SET_INT('z', NULL, &line_termination,
 769                        N_("with --stdin: input lines are terminated by null bytes"), '\0'),
 770                {OPTION_LOWLEVEL_CALLBACK, 0, "stdin", &read_from_stdin, NULL,
 771                        N_("read list of paths to be updated from standard input"),
 772                        PARSE_OPT_NONEG | PARSE_OPT_NOARG,
 773                        (parse_opt_cb *) stdin_callback},
 774                {OPTION_LOWLEVEL_CALLBACK, 0, "index-info", &line_termination, NULL,
 775                        N_("add entries from standard input to the index"),
 776                        PARSE_OPT_NONEG | PARSE_OPT_NOARG,
 777                        (parse_opt_cb *) stdin_cacheinfo_callback},
 778                {OPTION_LOWLEVEL_CALLBACK, 0, "unresolve", &has_errors, NULL,
 779                        N_("repopulate stages #2 and #3 for the listed paths"),
 780                        PARSE_OPT_NONEG | PARSE_OPT_NOARG,
 781                        (parse_opt_cb *) unresolve_callback},
 782                {OPTION_LOWLEVEL_CALLBACK, 'g', "again", &has_errors, NULL,
 783                        N_("only update entries that differ from HEAD"),
 784                        PARSE_OPT_NONEG | PARSE_OPT_NOARG,
 785                        (parse_opt_cb *) reupdate_callback},
 786                OPT_BIT(0, "ignore-missing", &refresh_args.flags,
 787                        N_("ignore files missing from worktree"),
 788                        REFRESH_IGNORE_MISSING),
 789                OPT_SET_INT(0, "verbose", &verbose,
 790                        N_("report actions to standard output"), 1),
 791                {OPTION_CALLBACK, 0, "clear-resolve-undo", NULL, NULL,
 792                        N_("(for porcelains) forget saved unresolved conflicts"),
 793                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 794                        resolve_undo_clear_callback},
 795                OPT_INTEGER(0, "index-version", &preferred_index_format,
 796                        N_("write index in this format")),
 797                OPT_END()
 798        };
 799
 800        if (argc == 2 && !strcmp(argv[1], "-h"))
 801                usage_with_options(update_index_usage, options);
 802
 803        git_config(git_default_config, NULL);
 804
 805        /* We can't free this memory, it becomes part of a linked list parsed atexit() */
 806        lock_file = xcalloc(1, sizeof(struct lock_file));
 807
 808        newfd = hold_locked_index(lock_file, 0);
 809        if (newfd < 0)
 810                lock_error = errno;
 811
 812        entries = read_cache();
 813        if (entries < 0)
 814                die("cache corrupted");
 815
 816        /*
 817         * Custom copy of parse_options() because we want to handle
 818         * filename arguments as they come.
 819         */
 820        parse_options_start(&ctx, argc, argv, prefix,
 821                            options, PARSE_OPT_STOP_AT_NON_OPTION);
 822        while (ctx.argc) {
 823                if (parseopt_state != PARSE_OPT_DONE)
 824                        parseopt_state = parse_options_step(&ctx, options,
 825                                                            update_index_usage);
 826                if (!ctx.argc)
 827                        break;
 828                switch (parseopt_state) {
 829                case PARSE_OPT_HELP:
 830                        exit(129);
 831                case PARSE_OPT_NON_OPTION:
 832                case PARSE_OPT_DONE:
 833                {
 834                        const char *path = ctx.argv[0];
 835                        const char *p;
 836
 837                        setup_work_tree();
 838                        p = prefix_path(prefix, prefix_length, path);
 839                        update_one(p, NULL, 0);
 840                        if (set_executable_bit)
 841                                chmod_path(set_executable_bit, p);
 842                        if (p < path || p > path + strlen(path))
 843                                free((char *)p);
 844                        ctx.argc--;
 845                        ctx.argv++;
 846                        break;
 847                }
 848                case PARSE_OPT_UNKNOWN:
 849                        if (ctx.argv[0][1] == '-')
 850                                error("unknown option '%s'", ctx.argv[0] + 2);
 851                        else
 852                                error("unknown switch '%c'", *ctx.opt);
 853                        usage_with_options(update_index_usage, options);
 854                }
 855        }
 856        argc = parse_options_end(&ctx);
 857        if (preferred_index_format) {
 858                if (preferred_index_format < INDEX_FORMAT_LB ||
 859                    INDEX_FORMAT_UB < preferred_index_format)
 860                        die("index-version %d not in range: %d..%d",
 861                            preferred_index_format,
 862                            INDEX_FORMAT_LB, INDEX_FORMAT_UB);
 863
 864                if (the_index.version != preferred_index_format)
 865                        active_cache_changed = 1;
 866                the_index.version = preferred_index_format;
 867        }
 868
 869        if (read_from_stdin) {
 870                struct strbuf buf = STRBUF_INIT, nbuf = STRBUF_INIT;
 871
 872                setup_work_tree();
 873                while (strbuf_getline(&buf, stdin, line_termination) != EOF) {
 874                        const char *p;
 875                        if (line_termination && buf.buf[0] == '"') {
 876                                strbuf_reset(&nbuf);
 877                                if (unquote_c_style(&nbuf, buf.buf, NULL))
 878                                        die("line is badly quoted");
 879                                strbuf_swap(&buf, &nbuf);
 880                        }
 881                        p = prefix_path(prefix, prefix_length, buf.buf);
 882                        update_one(p, NULL, 0);
 883                        if (set_executable_bit)
 884                                chmod_path(set_executable_bit, p);
 885                        if (p < buf.buf || p > buf.buf + buf.len)
 886                                free((char *)p);
 887                }
 888                strbuf_release(&nbuf);
 889                strbuf_release(&buf);
 890        }
 891
 892        if (active_cache_changed) {
 893                if (newfd < 0) {
 894                        if (refresh_args.flags & REFRESH_QUIET)
 895                                exit(128);
 896                        unable_to_lock_index_die(get_index_file(), lock_error);
 897                }
 898                if (write_cache(newfd, active_cache, active_nr) ||
 899                    commit_locked_index(lock_file))
 900                        die("Unable to write new index file");
 901        }
 902
 903        rollback_lock_file(lock_file);
 904
 905        return has_errors ? 1 : 0;
 906}