read-cache.con commit builtin-add.c: restructure the code for maintainability (041aee3)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6#define NO_THE_INDEX_COMPATIBILITY_MACROS
   7#include "cache.h"
   8#include "cache-tree.h"
   9#include "refs.h"
  10#include "dir.h"
  11#include "tree.h"
  12#include "commit.h"
  13#include "diff.h"
  14#include "diffcore.h"
  15#include "revision.h"
  16
  17/* Index extensions.
  18 *
  19 * The first letter should be 'A'..'Z' for extensions that are not
  20 * necessary for a correct operation (i.e. optimization data).
  21 * When new extensions are added that _needs_ to be understood in
  22 * order to correctly interpret the index file, pick character that
  23 * is outside the range, to cause the reader to abort.
  24 */
  25
  26#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
  27#define CACHE_EXT_TREE 0x54524545       /* "TREE" */
  28
  29struct index_state the_index;
  30
  31static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
  32{
  33        istate->cache[nr] = ce;
  34        add_name_hash(istate, ce);
  35}
  36
  37static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
  38{
  39        struct cache_entry *old = istate->cache[nr];
  40
  41        remove_name_hash(old);
  42        set_index_entry(istate, nr, ce);
  43        istate->cache_changed = 1;
  44}
  45
  46/*
  47 * This only updates the "non-critical" parts of the directory
  48 * cache, ie the parts that aren't tracked by GIT, and only used
  49 * to validate the cache.
  50 */
  51void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
  52{
  53        ce->ce_ctime = st->st_ctime;
  54        ce->ce_mtime = st->st_mtime;
  55        ce->ce_dev = st->st_dev;
  56        ce->ce_ino = st->st_ino;
  57        ce->ce_uid = st->st_uid;
  58        ce->ce_gid = st->st_gid;
  59        ce->ce_size = st->st_size;
  60
  61        if (assume_unchanged)
  62                ce->ce_flags |= CE_VALID;
  63
  64        if (S_ISREG(st->st_mode))
  65                ce_mark_uptodate(ce);
  66}
  67
  68static int ce_compare_data(struct cache_entry *ce, struct stat *st)
  69{
  70        int match = -1;
  71        int fd = open(ce->name, O_RDONLY);
  72
  73        if (fd >= 0) {
  74                unsigned char sha1[20];
  75                if (!index_fd(sha1, fd, st, 0, OBJ_BLOB, ce->name))
  76                        match = hashcmp(sha1, ce->sha1);
  77                /* index_fd() closed the file descriptor already */
  78        }
  79        return match;
  80}
  81
  82static int ce_compare_link(struct cache_entry *ce, size_t expected_size)
  83{
  84        int match = -1;
  85        char *target;
  86        void *buffer;
  87        unsigned long size;
  88        enum object_type type;
  89        int len;
  90
  91        target = xmalloc(expected_size);
  92        len = readlink(ce->name, target, expected_size);
  93        if (len != expected_size) {
  94                free(target);
  95                return -1;
  96        }
  97        buffer = read_sha1_file(ce->sha1, &type, &size);
  98        if (!buffer) {
  99                free(target);
 100                return -1;
 101        }
 102        if (size == expected_size)
 103                match = memcmp(buffer, target, size);
 104        free(buffer);
 105        free(target);
 106        return match;
 107}
 108
 109static int ce_compare_gitlink(struct cache_entry *ce)
 110{
 111        unsigned char sha1[20];
 112
 113        /*
 114         * We don't actually require that the .git directory
 115         * under GITLINK directory be a valid git directory. It
 116         * might even be missing (in case nobody populated that
 117         * sub-project).
 118         *
 119         * If so, we consider it always to match.
 120         */
 121        if (resolve_gitlink_ref(ce->name, "HEAD", sha1) < 0)
 122                return 0;
 123        return hashcmp(sha1, ce->sha1);
 124}
 125
 126static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
 127{
 128        switch (st->st_mode & S_IFMT) {
 129        case S_IFREG:
 130                if (ce_compare_data(ce, st))
 131                        return DATA_CHANGED;
 132                break;
 133        case S_IFLNK:
 134                if (ce_compare_link(ce, xsize_t(st->st_size)))
 135                        return DATA_CHANGED;
 136                break;
 137        case S_IFDIR:
 138                if (S_ISGITLINK(ce->ce_mode))
 139                        return 0;
 140        default:
 141                return TYPE_CHANGED;
 142        }
 143        return 0;
 144}
 145
 146static int is_empty_blob_sha1(const unsigned char *sha1)
 147{
 148        static const unsigned char empty_blob_sha1[20] = {
 149                0xe6,0x9d,0xe2,0x9b,0xb2,0xd1,0xd6,0x43,0x4b,0x8b,
 150                0x29,0xae,0x77,0x5a,0xd8,0xc2,0xe4,0x8c,0x53,0x91
 151        };
 152
 153        return !hashcmp(sha1, empty_blob_sha1);
 154}
 155
 156static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
 157{
 158        unsigned int changed = 0;
 159
 160        if (ce->ce_flags & CE_REMOVE)
 161                return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
 162
 163        switch (ce->ce_mode & S_IFMT) {
 164        case S_IFREG:
 165                changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
 166                /* We consider only the owner x bit to be relevant for
 167                 * "mode changes"
 168                 */
 169                if (trust_executable_bit &&
 170                    (0100 & (ce->ce_mode ^ st->st_mode)))
 171                        changed |= MODE_CHANGED;
 172                break;
 173        case S_IFLNK:
 174                if (!S_ISLNK(st->st_mode) &&
 175                    (has_symlinks || !S_ISREG(st->st_mode)))
 176                        changed |= TYPE_CHANGED;
 177                break;
 178        case S_IFGITLINK:
 179                if (!S_ISDIR(st->st_mode))
 180                        changed |= TYPE_CHANGED;
 181                else if (ce_compare_gitlink(ce))
 182                        changed |= DATA_CHANGED;
 183                return changed;
 184        default:
 185                die("internal error: ce_mode is %o", ce->ce_mode);
 186        }
 187        if (ce->ce_mtime != (unsigned int) st->st_mtime)
 188                changed |= MTIME_CHANGED;
 189        if (ce->ce_ctime != (unsigned int) st->st_ctime)
 190                changed |= CTIME_CHANGED;
 191
 192        if (ce->ce_uid != (unsigned int) st->st_uid ||
 193            ce->ce_gid != (unsigned int) st->st_gid)
 194                changed |= OWNER_CHANGED;
 195        if (ce->ce_ino != (unsigned int) st->st_ino)
 196                changed |= INODE_CHANGED;
 197
 198#ifdef USE_STDEV
 199        /*
 200         * st_dev breaks on network filesystems where different
 201         * clients will have different views of what "device"
 202         * the filesystem is on
 203         */
 204        if (ce->ce_dev != (unsigned int) st->st_dev)
 205                changed |= INODE_CHANGED;
 206#endif
 207
 208        if (ce->ce_size != (unsigned int) st->st_size)
 209                changed |= DATA_CHANGED;
 210
 211        /* Racily smudged entry? */
 212        if (!ce->ce_size) {
 213                if (!is_empty_blob_sha1(ce->sha1))
 214                        changed |= DATA_CHANGED;
 215        }
 216
 217        return changed;
 218}
 219
 220static int is_racy_timestamp(const struct index_state *istate, struct cache_entry *ce)
 221{
 222        return (!S_ISGITLINK(ce->ce_mode) &&
 223                istate->timestamp &&
 224                ((unsigned int)istate->timestamp) <= ce->ce_mtime);
 225}
 226
 227int ie_match_stat(const struct index_state *istate,
 228                  struct cache_entry *ce, struct stat *st,
 229                  unsigned int options)
 230{
 231        unsigned int changed;
 232        int ignore_valid = options & CE_MATCH_IGNORE_VALID;
 233        int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
 234
 235        /*
 236         * If it's marked as always valid in the index, it's
 237         * valid whatever the checked-out copy says.
 238         */
 239        if (!ignore_valid && (ce->ce_flags & CE_VALID))
 240                return 0;
 241
 242        changed = ce_match_stat_basic(ce, st);
 243
 244        /*
 245         * Within 1 second of this sequence:
 246         *      echo xyzzy >file && git-update-index --add file
 247         * running this command:
 248         *      echo frotz >file
 249         * would give a falsely clean cache entry.  The mtime and
 250         * length match the cache, and other stat fields do not change.
 251         *
 252         * We could detect this at update-index time (the cache entry
 253         * being registered/updated records the same time as "now")
 254         * and delay the return from git-update-index, but that would
 255         * effectively mean we can make at most one commit per second,
 256         * which is not acceptable.  Instead, we check cache entries
 257         * whose mtime are the same as the index file timestamp more
 258         * carefully than others.
 259         */
 260        if (!changed && is_racy_timestamp(istate, ce)) {
 261                if (assume_racy_is_modified)
 262                        changed |= DATA_CHANGED;
 263                else
 264                        changed |= ce_modified_check_fs(ce, st);
 265        }
 266
 267        return changed;
 268}
 269
 270int ie_modified(const struct index_state *istate,
 271                struct cache_entry *ce, struct stat *st, unsigned int options)
 272{
 273        int changed, changed_fs;
 274
 275        changed = ie_match_stat(istate, ce, st, options);
 276        if (!changed)
 277                return 0;
 278        /*
 279         * If the mode or type has changed, there's no point in trying
 280         * to refresh the entry - it's not going to match
 281         */
 282        if (changed & (MODE_CHANGED | TYPE_CHANGED))
 283                return changed;
 284
 285        /* Immediately after read-tree or update-index --cacheinfo,
 286         * the length field is zero.  For other cases the ce_size
 287         * should match the SHA1 recorded in the index entry.
 288         */
 289        if ((changed & DATA_CHANGED) && ce->ce_size != 0)
 290                return changed;
 291
 292        changed_fs = ce_modified_check_fs(ce, st);
 293        if (changed_fs)
 294                return changed | changed_fs;
 295        return 0;
 296}
 297
 298int base_name_compare(const char *name1, int len1, int mode1,
 299                      const char *name2, int len2, int mode2)
 300{
 301        unsigned char c1, c2;
 302        int len = len1 < len2 ? len1 : len2;
 303        int cmp;
 304
 305        cmp = memcmp(name1, name2, len);
 306        if (cmp)
 307                return cmp;
 308        c1 = name1[len];
 309        c2 = name2[len];
 310        if (!c1 && S_ISDIR(mode1))
 311                c1 = '/';
 312        if (!c2 && S_ISDIR(mode2))
 313                c2 = '/';
 314        return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
 315}
 316
 317/*
 318 * df_name_compare() is identical to base_name_compare(), except it
 319 * compares conflicting directory/file entries as equal. Note that
 320 * while a directory name compares as equal to a regular file, they
 321 * then individually compare _differently_ to a filename that has
 322 * a dot after the basename (because '\0' < '.' < '/').
 323 *
 324 * This is used by routines that want to traverse the git namespace
 325 * but then handle conflicting entries together when possible.
 326 */
 327int df_name_compare(const char *name1, int len1, int mode1,
 328                    const char *name2, int len2, int mode2)
 329{
 330        int len = len1 < len2 ? len1 : len2, cmp;
 331        unsigned char c1, c2;
 332
 333        cmp = memcmp(name1, name2, len);
 334        if (cmp)
 335                return cmp;
 336        /* Directories and files compare equal (same length, same name) */
 337        if (len1 == len2)
 338                return 0;
 339        c1 = name1[len];
 340        if (!c1 && S_ISDIR(mode1))
 341                c1 = '/';
 342        c2 = name2[len];
 343        if (!c2 && S_ISDIR(mode2))
 344                c2 = '/';
 345        if (c1 == '/' && !c2)
 346                return 0;
 347        if (c2 == '/' && !c1)
 348                return 0;
 349        return c1 - c2;
 350}
 351
 352int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
 353{
 354        int len1 = flags1 & CE_NAMEMASK;
 355        int len2 = flags2 & CE_NAMEMASK;
 356        int len = len1 < len2 ? len1 : len2;
 357        int cmp;
 358
 359        cmp = memcmp(name1, name2, len);
 360        if (cmp)
 361                return cmp;
 362        if (len1 < len2)
 363                return -1;
 364        if (len1 > len2)
 365                return 1;
 366
 367        /* Compare stages  */
 368        flags1 &= CE_STAGEMASK;
 369        flags2 &= CE_STAGEMASK;
 370
 371        if (flags1 < flags2)
 372                return -1;
 373        if (flags1 > flags2)
 374                return 1;
 375        return 0;
 376}
 377
 378int index_name_pos(const struct index_state *istate, const char *name, int namelen)
 379{
 380        int first, last;
 381
 382        first = 0;
 383        last = istate->cache_nr;
 384        while (last > first) {
 385                int next = (last + first) >> 1;
 386                struct cache_entry *ce = istate->cache[next];
 387                int cmp = cache_name_compare(name, namelen, ce->name, ce->ce_flags);
 388                if (!cmp)
 389                        return next;
 390                if (cmp < 0) {
 391                        last = next;
 392                        continue;
 393                }
 394                first = next+1;
 395        }
 396        return -first-1;
 397}
 398
 399/* Remove entry, return true if there are more entries to go.. */
 400int remove_index_entry_at(struct index_state *istate, int pos)
 401{
 402        struct cache_entry *ce = istate->cache[pos];
 403
 404        remove_name_hash(ce);
 405        istate->cache_changed = 1;
 406        istate->cache_nr--;
 407        if (pos >= istate->cache_nr)
 408                return 0;
 409        memmove(istate->cache + pos,
 410                istate->cache + pos + 1,
 411                (istate->cache_nr - pos) * sizeof(struct cache_entry *));
 412        return 1;
 413}
 414
 415int remove_file_from_index(struct index_state *istate, const char *path)
 416{
 417        int pos = index_name_pos(istate, path, strlen(path));
 418        if (pos < 0)
 419                pos = -pos-1;
 420        cache_tree_invalidate_path(istate->cache_tree, path);
 421        while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
 422                remove_index_entry_at(istate, pos);
 423        return 0;
 424}
 425
 426static int compare_name(struct cache_entry *ce, const char *path, int namelen)
 427{
 428        return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
 429}
 430
 431static int index_name_pos_also_unmerged(struct index_state *istate,
 432        const char *path, int namelen)
 433{
 434        int pos = index_name_pos(istate, path, namelen);
 435        struct cache_entry *ce;
 436
 437        if (pos >= 0)
 438                return pos;
 439
 440        /* maybe unmerged? */
 441        pos = -1 - pos;
 442        if (pos >= istate->cache_nr ||
 443                        compare_name((ce = istate->cache[pos]), path, namelen))
 444                return -1;
 445
 446        /* order of preference: stage 2, 1, 3 */
 447        if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
 448                        ce_stage((ce = istate->cache[pos + 1])) == 2 &&
 449                        !compare_name(ce, path, namelen))
 450                pos++;
 451        return pos;
 452}
 453
 454static int different_name(struct cache_entry *ce, struct cache_entry *alias)
 455{
 456        int len = ce_namelen(ce);
 457        return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
 458}
 459
 460/*
 461 * If we add a filename that aliases in the cache, we will use the
 462 * name that we already have - but we don't want to update the same
 463 * alias twice, because that implies that there were actually two
 464 * different files with aliasing names!
 465 *
 466 * So we use the CE_ADDED flag to verify that the alias was an old
 467 * one before we accept it as
 468 */
 469static struct cache_entry *create_alias_ce(struct cache_entry *ce, struct cache_entry *alias)
 470{
 471        int len;
 472        struct cache_entry *new;
 473
 474        if (alias->ce_flags & CE_ADDED)
 475                die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
 476
 477        /* Ok, create the new entry using the name of the existing alias */
 478        len = ce_namelen(alias);
 479        new = xcalloc(1, cache_entry_size(len));
 480        memcpy(new->name, alias->name, len);
 481        copy_cache_entry(new, ce);
 482        free(ce);
 483        return new;
 484}
 485
 486int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
 487{
 488        int size, namelen, was_same;
 489        mode_t st_mode = st->st_mode;
 490        struct cache_entry *ce, *alias;
 491        unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_RACY_IS_DIRTY;
 492        int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
 493        int pretend = flags & ADD_CACHE_PRETEND;
 494
 495        if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
 496                return error("%s: can only add regular files, symbolic links or git-directories", path);
 497
 498        namelen = strlen(path);
 499        if (S_ISDIR(st_mode)) {
 500                while (namelen && path[namelen-1] == '/')
 501                        namelen--;
 502        }
 503        size = cache_entry_size(namelen);
 504        ce = xcalloc(1, size);
 505        memcpy(ce->name, path, namelen);
 506        ce->ce_flags = namelen;
 507        fill_stat_cache_info(ce, st);
 508
 509        if (trust_executable_bit && has_symlinks)
 510                ce->ce_mode = create_ce_mode(st_mode);
 511        else {
 512                /* If there is an existing entry, pick the mode bits and type
 513                 * from it, otherwise assume unexecutable regular file.
 514                 */
 515                struct cache_entry *ent;
 516                int pos = index_name_pos_also_unmerged(istate, path, namelen);
 517
 518                ent = (0 <= pos) ? istate->cache[pos] : NULL;
 519                ce->ce_mode = ce_mode_from_stat(ent, st_mode);
 520        }
 521
 522        alias = index_name_exists(istate, ce->name, ce_namelen(ce), ignore_case);
 523        if (alias && !ce_stage(alias) && !ie_match_stat(istate, alias, st, ce_option)) {
 524                /* Nothing changed, really */
 525                free(ce);
 526                ce_mark_uptodate(alias);
 527                alias->ce_flags |= CE_ADDED;
 528                return 0;
 529        }
 530        if (index_path(ce->sha1, path, st, 1))
 531                return error("unable to index file %s", path);
 532        if (ignore_case && alias && different_name(ce, alias))
 533                ce = create_alias_ce(ce, alias);
 534        ce->ce_flags |= CE_ADDED;
 535
 536        /* It was suspected to be racily clean, but it turns out to be Ok */
 537        was_same = (alias &&
 538                    !ce_stage(alias) &&
 539                    !hashcmp(alias->sha1, ce->sha1) &&
 540                    ce->ce_mode == alias->ce_mode);
 541
 542        if (pretend)
 543                ;
 544        else if (add_index_entry(istate, ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE))
 545                return error("unable to add %s to index",path);
 546        if (verbose && !was_same)
 547                printf("add '%s'\n", path);
 548        return 0;
 549}
 550
 551int add_file_to_index(struct index_state *istate, const char *path, int flags)
 552{
 553        struct stat st;
 554        if (lstat(path, &st))
 555                die("%s: unable to stat (%s)", path, strerror(errno));
 556        return add_to_index(istate, path, &st, flags);
 557}
 558
 559struct cache_entry *make_cache_entry(unsigned int mode,
 560                const unsigned char *sha1, const char *path, int stage,
 561                int refresh)
 562{
 563        int size, len;
 564        struct cache_entry *ce;
 565
 566        if (!verify_path(path))
 567                return NULL;
 568
 569        len = strlen(path);
 570        size = cache_entry_size(len);
 571        ce = xcalloc(1, size);
 572
 573        hashcpy(ce->sha1, sha1);
 574        memcpy(ce->name, path, len);
 575        ce->ce_flags = create_ce_flags(len, stage);
 576        ce->ce_mode = create_ce_mode(mode);
 577
 578        if (refresh)
 579                return refresh_cache_entry(ce, 0);
 580
 581        return ce;
 582}
 583
 584int ce_same_name(struct cache_entry *a, struct cache_entry *b)
 585{
 586        int len = ce_namelen(a);
 587        return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
 588}
 589
 590int ce_path_match(const struct cache_entry *ce, const char **pathspec)
 591{
 592        const char *match, *name;
 593        int len;
 594
 595        if (!pathspec)
 596                return 1;
 597
 598        len = ce_namelen(ce);
 599        name = ce->name;
 600        while ((match = *pathspec++) != NULL) {
 601                int matchlen = strlen(match);
 602                if (matchlen > len)
 603                        continue;
 604                if (memcmp(name, match, matchlen))
 605                        continue;
 606                if (matchlen && name[matchlen-1] == '/')
 607                        return 1;
 608                if (name[matchlen] == '/' || !name[matchlen])
 609                        return 1;
 610                if (!matchlen)
 611                        return 1;
 612        }
 613        return 0;
 614}
 615
 616/*
 617 * We fundamentally don't like some paths: we don't want
 618 * dot or dot-dot anywhere, and for obvious reasons don't
 619 * want to recurse into ".git" either.
 620 *
 621 * Also, we don't want double slashes or slashes at the
 622 * end that can make pathnames ambiguous.
 623 */
 624static int verify_dotfile(const char *rest)
 625{
 626        /*
 627         * The first character was '.', but that
 628         * has already been discarded, we now test
 629         * the rest.
 630         */
 631        switch (*rest) {
 632        /* "." is not allowed */
 633        case '\0': case '/':
 634                return 0;
 635
 636        /*
 637         * ".git" followed by  NUL or slash is bad. This
 638         * shares the path end test with the ".." case.
 639         */
 640        case 'g':
 641                if (rest[1] != 'i')
 642                        break;
 643                if (rest[2] != 't')
 644                        break;
 645                rest += 2;
 646        /* fallthrough */
 647        case '.':
 648                if (rest[1] == '\0' || rest[1] == '/')
 649                        return 0;
 650        }
 651        return 1;
 652}
 653
 654int verify_path(const char *path)
 655{
 656        char c;
 657
 658        goto inside;
 659        for (;;) {
 660                if (!c)
 661                        return 1;
 662                if (c == '/') {
 663inside:
 664                        c = *path++;
 665                        switch (c) {
 666                        default:
 667                                continue;
 668                        case '/': case '\0':
 669                                break;
 670                        case '.':
 671                                if (verify_dotfile(path))
 672                                        continue;
 673                        }
 674                        return 0;
 675                }
 676                c = *path++;
 677        }
 678}
 679
 680/*
 681 * Do we have another file that has the beginning components being a
 682 * proper superset of the name we're trying to add?
 683 */
 684static int has_file_name(struct index_state *istate,
 685                         const struct cache_entry *ce, int pos, int ok_to_replace)
 686{
 687        int retval = 0;
 688        int len = ce_namelen(ce);
 689        int stage = ce_stage(ce);
 690        const char *name = ce->name;
 691
 692        while (pos < istate->cache_nr) {
 693                struct cache_entry *p = istate->cache[pos++];
 694
 695                if (len >= ce_namelen(p))
 696                        break;
 697                if (memcmp(name, p->name, len))
 698                        break;
 699                if (ce_stage(p) != stage)
 700                        continue;
 701                if (p->name[len] != '/')
 702                        continue;
 703                if (p->ce_flags & CE_REMOVE)
 704                        continue;
 705                retval = -1;
 706                if (!ok_to_replace)
 707                        break;
 708                remove_index_entry_at(istate, --pos);
 709        }
 710        return retval;
 711}
 712
 713/*
 714 * Do we have another file with a pathname that is a proper
 715 * subset of the name we're trying to add?
 716 */
 717static int has_dir_name(struct index_state *istate,
 718                        const struct cache_entry *ce, int pos, int ok_to_replace)
 719{
 720        int retval = 0;
 721        int stage = ce_stage(ce);
 722        const char *name = ce->name;
 723        const char *slash = name + ce_namelen(ce);
 724
 725        for (;;) {
 726                int len;
 727
 728                for (;;) {
 729                        if (*--slash == '/')
 730                                break;
 731                        if (slash <= ce->name)
 732                                return retval;
 733                }
 734                len = slash - name;
 735
 736                pos = index_name_pos(istate, name, create_ce_flags(len, stage));
 737                if (pos >= 0) {
 738                        /*
 739                         * Found one, but not so fast.  This could
 740                         * be a marker that says "I was here, but
 741                         * I am being removed".  Such an entry is
 742                         * not a part of the resulting tree, and
 743                         * it is Ok to have a directory at the same
 744                         * path.
 745                         */
 746                        if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
 747                                retval = -1;
 748                                if (!ok_to_replace)
 749                                        break;
 750                                remove_index_entry_at(istate, pos);
 751                                continue;
 752                        }
 753                }
 754                else
 755                        pos = -pos-1;
 756
 757                /*
 758                 * Trivial optimization: if we find an entry that
 759                 * already matches the sub-directory, then we know
 760                 * we're ok, and we can exit.
 761                 */
 762                while (pos < istate->cache_nr) {
 763                        struct cache_entry *p = istate->cache[pos];
 764                        if ((ce_namelen(p) <= len) ||
 765                            (p->name[len] != '/') ||
 766                            memcmp(p->name, name, len))
 767                                break; /* not our subdirectory */
 768                        if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
 769                                /*
 770                                 * p is at the same stage as our entry, and
 771                                 * is a subdirectory of what we are looking
 772                                 * at, so we cannot have conflicts at our
 773                                 * level or anything shorter.
 774                                 */
 775                                return retval;
 776                        pos++;
 777                }
 778        }
 779        return retval;
 780}
 781
 782/* We may be in a situation where we already have path/file and path
 783 * is being added, or we already have path and path/file is being
 784 * added.  Either one would result in a nonsense tree that has path
 785 * twice when git-write-tree tries to write it out.  Prevent it.
 786 *
 787 * If ok-to-replace is specified, we remove the conflicting entries
 788 * from the cache so the caller should recompute the insert position.
 789 * When this happens, we return non-zero.
 790 */
 791static int check_file_directory_conflict(struct index_state *istate,
 792                                         const struct cache_entry *ce,
 793                                         int pos, int ok_to_replace)
 794{
 795        int retval;
 796
 797        /*
 798         * When ce is an "I am going away" entry, we allow it to be added
 799         */
 800        if (ce->ce_flags & CE_REMOVE)
 801                return 0;
 802
 803        /*
 804         * We check if the path is a sub-path of a subsequent pathname
 805         * first, since removing those will not change the position
 806         * in the array.
 807         */
 808        retval = has_file_name(istate, ce, pos, ok_to_replace);
 809
 810        /*
 811         * Then check if the path might have a clashing sub-directory
 812         * before it.
 813         */
 814        return retval + has_dir_name(istate, ce, pos, ok_to_replace);
 815}
 816
 817static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
 818{
 819        int pos;
 820        int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
 821        int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
 822        int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
 823
 824        cache_tree_invalidate_path(istate->cache_tree, ce->name);
 825        pos = index_name_pos(istate, ce->name, ce->ce_flags);
 826
 827        /* existing match? Just replace it. */
 828        if (pos >= 0) {
 829                replace_index_entry(istate, pos, ce);
 830                return 0;
 831        }
 832        pos = -pos-1;
 833
 834        /*
 835         * Inserting a merged entry ("stage 0") into the index
 836         * will always replace all non-merged entries..
 837         */
 838        if (pos < istate->cache_nr && ce_stage(ce) == 0) {
 839                while (ce_same_name(istate->cache[pos], ce)) {
 840                        ok_to_add = 1;
 841                        if (!remove_index_entry_at(istate, pos))
 842                                break;
 843                }
 844        }
 845
 846        if (!ok_to_add)
 847                return -1;
 848        if (!verify_path(ce->name))
 849                return -1;
 850
 851        if (!skip_df_check &&
 852            check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
 853                if (!ok_to_replace)
 854                        return error("'%s' appears as both a file and as a directory",
 855                                     ce->name);
 856                pos = index_name_pos(istate, ce->name, ce->ce_flags);
 857                pos = -pos-1;
 858        }
 859        return pos + 1;
 860}
 861
 862int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
 863{
 864        int pos;
 865
 866        if (option & ADD_CACHE_JUST_APPEND)
 867                pos = istate->cache_nr;
 868        else {
 869                int ret;
 870                ret = add_index_entry_with_check(istate, ce, option);
 871                if (ret <= 0)
 872                        return ret;
 873                pos = ret - 1;
 874        }
 875
 876        /* Make sure the array is big enough .. */
 877        if (istate->cache_nr == istate->cache_alloc) {
 878                istate->cache_alloc = alloc_nr(istate->cache_alloc);
 879                istate->cache = xrealloc(istate->cache,
 880                                        istate->cache_alloc * sizeof(struct cache_entry *));
 881        }
 882
 883        /* Add it in.. */
 884        istate->cache_nr++;
 885        if (istate->cache_nr > pos + 1)
 886                memmove(istate->cache + pos + 1,
 887                        istate->cache + pos,
 888                        (istate->cache_nr - pos - 1) * sizeof(ce));
 889        set_index_entry(istate, pos, ce);
 890        istate->cache_changed = 1;
 891        return 0;
 892}
 893
 894/*
 895 * "refresh" does not calculate a new sha1 file or bring the
 896 * cache up-to-date for mode/content changes. But what it
 897 * _does_ do is to "re-match" the stat information of a file
 898 * with the cache, so that you can refresh the cache for a
 899 * file that hasn't been changed but where the stat entry is
 900 * out of date.
 901 *
 902 * For example, you'd want to do this after doing a "git-read-tree",
 903 * to link up the stat cache details with the proper files.
 904 */
 905static struct cache_entry *refresh_cache_ent(struct index_state *istate,
 906                                             struct cache_entry *ce,
 907                                             unsigned int options, int *err)
 908{
 909        struct stat st;
 910        struct cache_entry *updated;
 911        int changed, size;
 912        int ignore_valid = options & CE_MATCH_IGNORE_VALID;
 913
 914        if (ce_uptodate(ce))
 915                return ce;
 916
 917        /*
 918         * CE_VALID means the user promised us that the change to
 919         * the work tree does not matter and told us not to worry.
 920         */
 921        if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
 922                ce_mark_uptodate(ce);
 923                return ce;
 924        }
 925
 926        if (lstat(ce->name, &st) < 0) {
 927                if (err)
 928                        *err = errno;
 929                return NULL;
 930        }
 931
 932        changed = ie_match_stat(istate, ce, &st, options);
 933        if (!changed) {
 934                /*
 935                 * The path is unchanged.  If we were told to ignore
 936                 * valid bit, then we did the actual stat check and
 937                 * found that the entry is unmodified.  If the entry
 938                 * is not marked VALID, this is the place to mark it
 939                 * valid again, under "assume unchanged" mode.
 940                 */
 941                if (ignore_valid && assume_unchanged &&
 942                    !(ce->ce_flags & CE_VALID))
 943                        ; /* mark this one VALID again */
 944                else {
 945                        /*
 946                         * We do not mark the index itself "modified"
 947                         * because CE_UPTODATE flag is in-core only;
 948                         * we are not going to write this change out.
 949                         */
 950                        ce_mark_uptodate(ce);
 951                        return ce;
 952                }
 953        }
 954
 955        if (ie_modified(istate, ce, &st, options)) {
 956                if (err)
 957                        *err = EINVAL;
 958                return NULL;
 959        }
 960
 961        size = ce_size(ce);
 962        updated = xmalloc(size);
 963        memcpy(updated, ce, size);
 964        fill_stat_cache_info(updated, &st);
 965        /*
 966         * If ignore_valid is not set, we should leave CE_VALID bit
 967         * alone.  Otherwise, paths marked with --no-assume-unchanged
 968         * (i.e. things to be edited) will reacquire CE_VALID bit
 969         * automatically, which is not really what we want.
 970         */
 971        if (!ignore_valid && assume_unchanged &&
 972            !(ce->ce_flags & CE_VALID))
 973                updated->ce_flags &= ~CE_VALID;
 974
 975        return updated;
 976}
 977
 978int refresh_index(struct index_state *istate, unsigned int flags, const char **pathspec, char *seen)
 979{
 980        int i;
 981        int has_errors = 0;
 982        int really = (flags & REFRESH_REALLY) != 0;
 983        int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
 984        int quiet = (flags & REFRESH_QUIET) != 0;
 985        int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
 986        int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
 987        unsigned int options = really ? CE_MATCH_IGNORE_VALID : 0;
 988        const char *needs_update_message;
 989
 990        needs_update_message = ((flags & REFRESH_SAY_CHANGED)
 991                                ? "locally modified" : "needs update");
 992        for (i = 0; i < istate->cache_nr; i++) {
 993                struct cache_entry *ce, *new;
 994                int cache_errno = 0;
 995
 996                ce = istate->cache[i];
 997                if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
 998                        continue;
 999
1000                if (ce_stage(ce)) {
1001                        while ((i < istate->cache_nr) &&
1002                               ! strcmp(istate->cache[i]->name, ce->name))
1003                                i++;
1004                        i--;
1005                        if (allow_unmerged)
1006                                continue;
1007                        printf("%s: needs merge\n", ce->name);
1008                        has_errors = 1;
1009                        continue;
1010                }
1011
1012                if (pathspec && !match_pathspec(pathspec, ce->name, strlen(ce->name), 0, seen))
1013                        continue;
1014
1015                new = refresh_cache_ent(istate, ce, options, &cache_errno);
1016                if (new == ce)
1017                        continue;
1018                if (!new) {
1019                        if (not_new && cache_errno == ENOENT)
1020                                continue;
1021                        if (really && cache_errno == EINVAL) {
1022                                /* If we are doing --really-refresh that
1023                                 * means the index is not valid anymore.
1024                                 */
1025                                ce->ce_flags &= ~CE_VALID;
1026                                istate->cache_changed = 1;
1027                        }
1028                        if (quiet)
1029                                continue;
1030                        printf("%s: %s\n", ce->name, needs_update_message);
1031                        has_errors = 1;
1032                        continue;
1033                }
1034
1035                replace_index_entry(istate, i, new);
1036        }
1037        return has_errors;
1038}
1039
1040struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
1041{
1042        return refresh_cache_ent(&the_index, ce, really, NULL);
1043}
1044
1045static int verify_hdr(struct cache_header *hdr, unsigned long size)
1046{
1047        SHA_CTX c;
1048        unsigned char sha1[20];
1049
1050        if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1051                return error("bad signature");
1052        if (hdr->hdr_version != htonl(2))
1053                return error("bad index version");
1054        SHA1_Init(&c);
1055        SHA1_Update(&c, hdr, size - 20);
1056        SHA1_Final(sha1, &c);
1057        if (hashcmp(sha1, (unsigned char *)hdr + size - 20))
1058                return error("bad index file sha1 signature");
1059        return 0;
1060}
1061
1062static int read_index_extension(struct index_state *istate,
1063                                const char *ext, void *data, unsigned long sz)
1064{
1065        switch (CACHE_EXT(ext)) {
1066        case CACHE_EXT_TREE:
1067                istate->cache_tree = cache_tree_read(data, sz);
1068                break;
1069        default:
1070                if (*ext < 'A' || 'Z' < *ext)
1071                        return error("index uses %.4s extension, which we do not understand",
1072                                     ext);
1073                fprintf(stderr, "ignoring %.4s extension\n", ext);
1074                break;
1075        }
1076        return 0;
1077}
1078
1079int read_index(struct index_state *istate)
1080{
1081        return read_index_from(istate, get_index_file());
1082}
1083
1084static void convert_from_disk(struct ondisk_cache_entry *ondisk, struct cache_entry *ce)
1085{
1086        size_t len;
1087
1088        ce->ce_ctime = ntohl(ondisk->ctime.sec);
1089        ce->ce_mtime = ntohl(ondisk->mtime.sec);
1090        ce->ce_dev   = ntohl(ondisk->dev);
1091        ce->ce_ino   = ntohl(ondisk->ino);
1092        ce->ce_mode  = ntohl(ondisk->mode);
1093        ce->ce_uid   = ntohl(ondisk->uid);
1094        ce->ce_gid   = ntohl(ondisk->gid);
1095        ce->ce_size  = ntohl(ondisk->size);
1096        /* On-disk flags are just 16 bits */
1097        ce->ce_flags = ntohs(ondisk->flags);
1098        hashcpy(ce->sha1, ondisk->sha1);
1099
1100        len = ce->ce_flags & CE_NAMEMASK;
1101        if (len == CE_NAMEMASK)
1102                len = strlen(ondisk->name);
1103        /*
1104         * NEEDSWORK: If the original index is crafted, this copy could
1105         * go unchecked.
1106         */
1107        memcpy(ce->name, ondisk->name, len + 1);
1108}
1109
1110static inline size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1111{
1112        long per_entry;
1113
1114        per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1115
1116        /*
1117         * Alignment can cause differences. This should be "alignof", but
1118         * since that's a gcc'ism, just use the size of a pointer.
1119         */
1120        per_entry += sizeof(void *);
1121        return ondisk_size + entries*per_entry;
1122}
1123
1124/* remember to discard_cache() before reading a different cache! */
1125int read_index_from(struct index_state *istate, const char *path)
1126{
1127        int fd, i;
1128        struct stat st;
1129        unsigned long src_offset, dst_offset;
1130        struct cache_header *hdr;
1131        void *mmap;
1132        size_t mmap_size;
1133
1134        errno = EBUSY;
1135        if (istate->alloc)
1136                return istate->cache_nr;
1137
1138        errno = ENOENT;
1139        istate->timestamp = 0;
1140        fd = open(path, O_RDONLY);
1141        if (fd < 0) {
1142                if (errno == ENOENT)
1143                        return 0;
1144                die("index file open failed (%s)", strerror(errno));
1145        }
1146
1147        if (fstat(fd, &st))
1148                die("cannot stat the open index (%s)", strerror(errno));
1149
1150        errno = EINVAL;
1151        mmap_size = xsize_t(st.st_size);
1152        if (mmap_size < sizeof(struct cache_header) + 20)
1153                die("index file smaller than expected");
1154
1155        mmap = xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
1156        close(fd);
1157        if (mmap == MAP_FAILED)
1158                die("unable to map index file");
1159
1160        hdr = mmap;
1161        if (verify_hdr(hdr, mmap_size) < 0)
1162                goto unmap;
1163
1164        istate->cache_nr = ntohl(hdr->hdr_entries);
1165        istate->cache_alloc = alloc_nr(istate->cache_nr);
1166        istate->cache = xcalloc(istate->cache_alloc, sizeof(struct cache_entry *));
1167
1168        /*
1169         * The disk format is actually larger than the in-memory format,
1170         * due to space for nsec etc, so even though the in-memory one
1171         * has room for a few  more flags, we can allocate using the same
1172         * index size
1173         */
1174        istate->alloc = xmalloc(estimate_cache_size(mmap_size, istate->cache_nr));
1175
1176        src_offset = sizeof(*hdr);
1177        dst_offset = 0;
1178        for (i = 0; i < istate->cache_nr; i++) {
1179                struct ondisk_cache_entry *disk_ce;
1180                struct cache_entry *ce;
1181
1182                disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
1183                ce = (struct cache_entry *)((char *)istate->alloc + dst_offset);
1184                convert_from_disk(disk_ce, ce);
1185                set_index_entry(istate, i, ce);
1186
1187                src_offset += ondisk_ce_size(ce);
1188                dst_offset += ce_size(ce);
1189        }
1190        istate->timestamp = st.st_mtime;
1191        while (src_offset <= mmap_size - 20 - 8) {
1192                /* After an array of active_nr index entries,
1193                 * there can be arbitrary number of extended
1194                 * sections, each of which is prefixed with
1195                 * extension name (4-byte) and section length
1196                 * in 4-byte network byte order.
1197                 */
1198                unsigned long extsize;
1199                memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
1200                extsize = ntohl(extsize);
1201                if (read_index_extension(istate,
1202                                         (const char *) mmap + src_offset,
1203                                         (char *) mmap + src_offset + 8,
1204                                         extsize) < 0)
1205                        goto unmap;
1206                src_offset += 8;
1207                src_offset += extsize;
1208        }
1209        munmap(mmap, mmap_size);
1210        return istate->cache_nr;
1211
1212unmap:
1213        munmap(mmap, mmap_size);
1214        errno = EINVAL;
1215        die("index file corrupt");
1216}
1217
1218int discard_index(struct index_state *istate)
1219{
1220        istate->cache_nr = 0;
1221        istate->cache_changed = 0;
1222        istate->timestamp = 0;
1223        free_hash(&istate->name_hash);
1224        cache_tree_free(&(istate->cache_tree));
1225        free(istate->alloc);
1226        istate->alloc = NULL;
1227
1228        /* no need to throw away allocated active_cache */
1229        return 0;
1230}
1231
1232int unmerged_index(const struct index_state *istate)
1233{
1234        int i;
1235        for (i = 0; i < istate->cache_nr; i++) {
1236                if (ce_stage(istate->cache[i]))
1237                        return 1;
1238        }
1239        return 0;
1240}
1241
1242#define WRITE_BUFFER_SIZE 8192
1243static unsigned char write_buffer[WRITE_BUFFER_SIZE];
1244static unsigned long write_buffer_len;
1245
1246static int ce_write_flush(SHA_CTX *context, int fd)
1247{
1248        unsigned int buffered = write_buffer_len;
1249        if (buffered) {
1250                SHA1_Update(context, write_buffer, buffered);
1251                if (write_in_full(fd, write_buffer, buffered) != buffered)
1252                        return -1;
1253                write_buffer_len = 0;
1254        }
1255        return 0;
1256}
1257
1258static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
1259{
1260        while (len) {
1261                unsigned int buffered = write_buffer_len;
1262                unsigned int partial = WRITE_BUFFER_SIZE - buffered;
1263                if (partial > len)
1264                        partial = len;
1265                memcpy(write_buffer + buffered, data, partial);
1266                buffered += partial;
1267                if (buffered == WRITE_BUFFER_SIZE) {
1268                        write_buffer_len = buffered;
1269                        if (ce_write_flush(context, fd))
1270                                return -1;
1271                        buffered = 0;
1272                }
1273                write_buffer_len = buffered;
1274                len -= partial;
1275                data = (char *) data + partial;
1276        }
1277        return 0;
1278}
1279
1280static int write_index_ext_header(SHA_CTX *context, int fd,
1281                                  unsigned int ext, unsigned int sz)
1282{
1283        ext = htonl(ext);
1284        sz = htonl(sz);
1285        return ((ce_write(context, fd, &ext, 4) < 0) ||
1286                (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
1287}
1288
1289static int ce_flush(SHA_CTX *context, int fd)
1290{
1291        unsigned int left = write_buffer_len;
1292
1293        if (left) {
1294                write_buffer_len = 0;
1295                SHA1_Update(context, write_buffer, left);
1296        }
1297
1298        /* Flush first if not enough space for SHA1 signature */
1299        if (left + 20 > WRITE_BUFFER_SIZE) {
1300                if (write_in_full(fd, write_buffer, left) != left)
1301                        return -1;
1302                left = 0;
1303        }
1304
1305        /* Append the SHA1 signature at the end */
1306        SHA1_Final(write_buffer + left, context);
1307        left += 20;
1308        return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0;
1309}
1310
1311static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
1312{
1313        /*
1314         * The only thing we care about in this function is to smudge the
1315         * falsely clean entry due to touch-update-touch race, so we leave
1316         * everything else as they are.  We are called for entries whose
1317         * ce_mtime match the index file mtime.
1318         */
1319        struct stat st;
1320
1321        if (lstat(ce->name, &st) < 0)
1322                return;
1323        if (ce_match_stat_basic(ce, &st))
1324                return;
1325        if (ce_modified_check_fs(ce, &st)) {
1326                /* This is "racily clean"; smudge it.  Note that this
1327                 * is a tricky code.  At first glance, it may appear
1328                 * that it can break with this sequence:
1329                 *
1330                 * $ echo xyzzy >frotz
1331                 * $ git-update-index --add frotz
1332                 * $ : >frotz
1333                 * $ sleep 3
1334                 * $ echo filfre >nitfol
1335                 * $ git-update-index --add nitfol
1336                 *
1337                 * but it does not.  When the second update-index runs,
1338                 * it notices that the entry "frotz" has the same timestamp
1339                 * as index, and if we were to smudge it by resetting its
1340                 * size to zero here, then the object name recorded
1341                 * in index is the 6-byte file but the cached stat information
1342                 * becomes zero --- which would then match what we would
1343                 * obtain from the filesystem next time we stat("frotz").
1344                 *
1345                 * However, the second update-index, before calling
1346                 * this function, notices that the cached size is 6
1347                 * bytes and what is on the filesystem is an empty
1348                 * file, and never calls us, so the cached size information
1349                 * for "frotz" stays 6 which does not match the filesystem.
1350                 */
1351                ce->ce_size = 0;
1352        }
1353}
1354
1355static int ce_write_entry(SHA_CTX *c, int fd, struct cache_entry *ce)
1356{
1357        int size = ondisk_ce_size(ce);
1358        struct ondisk_cache_entry *ondisk = xcalloc(1, size);
1359
1360        ondisk->ctime.sec = htonl(ce->ce_ctime);
1361        ondisk->ctime.nsec = 0;
1362        ondisk->mtime.sec = htonl(ce->ce_mtime);
1363        ondisk->mtime.nsec = 0;
1364        ondisk->dev  = htonl(ce->ce_dev);
1365        ondisk->ino  = htonl(ce->ce_ino);
1366        ondisk->mode = htonl(ce->ce_mode);
1367        ondisk->uid  = htonl(ce->ce_uid);
1368        ondisk->gid  = htonl(ce->ce_gid);
1369        ondisk->size = htonl(ce->ce_size);
1370        hashcpy(ondisk->sha1, ce->sha1);
1371        ondisk->flags = htons(ce->ce_flags);
1372        memcpy(ondisk->name, ce->name, ce_namelen(ce));
1373
1374        return ce_write(c, fd, ondisk, size);
1375}
1376
1377int write_index(const struct index_state *istate, int newfd)
1378{
1379        SHA_CTX c;
1380        struct cache_header hdr;
1381        int i, err, removed;
1382        struct cache_entry **cache = istate->cache;
1383        int entries = istate->cache_nr;
1384
1385        for (i = removed = 0; i < entries; i++)
1386                if (cache[i]->ce_flags & CE_REMOVE)
1387                        removed++;
1388
1389        hdr.hdr_signature = htonl(CACHE_SIGNATURE);
1390        hdr.hdr_version = htonl(2);
1391        hdr.hdr_entries = htonl(entries - removed);
1392
1393        SHA1_Init(&c);
1394        if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
1395                return -1;
1396
1397        for (i = 0; i < entries; i++) {
1398                struct cache_entry *ce = cache[i];
1399                if (ce->ce_flags & CE_REMOVE)
1400                        continue;
1401                if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
1402                        ce_smudge_racily_clean_entry(ce);
1403                if (ce_write_entry(&c, newfd, ce) < 0)
1404                        return -1;
1405        }
1406
1407        /* Write extension data here */
1408        if (istate->cache_tree) {
1409                struct strbuf sb;
1410
1411                strbuf_init(&sb, 0);
1412                cache_tree_write(&sb, istate->cache_tree);
1413                err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
1414                        || ce_write(&c, newfd, sb.buf, sb.len) < 0;
1415                strbuf_release(&sb);
1416                if (err)
1417                        return -1;
1418        }
1419        return ce_flush(&c, newfd);
1420}
1421
1422/*
1423 * Read the index file that is potentially unmerged into given
1424 * index_state, dropping any unmerged entries.  Returns true is
1425 * the index is unmerged.  Callers who want to refuse to work
1426 * from an unmerged state can call this and check its return value,
1427 * instead of calling read_cache().
1428 */
1429int read_index_unmerged(struct index_state *istate)
1430{
1431        int i;
1432        struct cache_entry **dst;
1433        struct cache_entry *last = NULL;
1434
1435        read_index(istate);
1436        dst = istate->cache;
1437        for (i = 0; i < istate->cache_nr; i++) {
1438                struct cache_entry *ce = istate->cache[i];
1439                if (ce_stage(ce)) {
1440                        remove_name_hash(ce);
1441                        if (last && !strcmp(ce->name, last->name))
1442                                continue;
1443                        cache_tree_invalidate_path(istate->cache_tree, ce->name);
1444                        last = ce;
1445                        continue;
1446                }
1447                *dst++ = ce;
1448        }
1449        istate->cache_nr = dst - istate->cache;
1450        return !!last;
1451}
1452
1453struct update_callback_data
1454{
1455        int flags;
1456        int add_errors;
1457};
1458
1459static void update_callback(struct diff_queue_struct *q,
1460                            struct diff_options *opt, void *cbdata)
1461{
1462        int i;
1463        struct update_callback_data *data = cbdata;
1464
1465        for (i = 0; i < q->nr; i++) {
1466                struct diff_filepair *p = q->queue[i];
1467                const char *path = p->one->path;
1468                switch (p->status) {
1469                default:
1470                        die("unexpected diff status %c", p->status);
1471                case DIFF_STATUS_UNMERGED:
1472                case DIFF_STATUS_MODIFIED:
1473                case DIFF_STATUS_TYPE_CHANGED:
1474                        if (add_file_to_index(&the_index, path, data->flags)) {
1475                                if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
1476                                        die("updating files failed");
1477                                data->add_errors++;
1478                        }
1479                        break;
1480                case DIFF_STATUS_DELETED:
1481                        if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
1482                                break;
1483                        if (!(data->flags & ADD_CACHE_PRETEND))
1484                                remove_file_from_index(&the_index, path);
1485                        if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
1486                                printf("remove '%s'\n", path);
1487                        break;
1488                }
1489        }
1490}
1491
1492int add_files_to_cache(const char *prefix, const char **pathspec, int flags)
1493{
1494        struct update_callback_data data;
1495        struct rev_info rev;
1496        init_revisions(&rev, prefix);
1497        setup_revisions(0, NULL, &rev, NULL);
1498        rev.prune_data = pathspec;
1499        rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1500        rev.diffopt.format_callback = update_callback;
1501        data.flags = flags;
1502        data.add_errors = 0;
1503        rev.diffopt.format_callback_data = &data;
1504        run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
1505        return !!data.add_errors;
1506}
1507