Add a new test for using a custom merge strategy
[git/dscho.git] / read-cache.c
blob1cae361c6c3066e0aedba7872ebda3766aa94a52
1 /*
2 * GIT - The information manager from hell
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"
12 /* Index extensions.
14 * The first letter should be 'A'..'Z' for extensions that are not
15 * necessary for a correct operation (i.e. optimization data).
16 * When new extensions are added that _needs_ to be understood in
17 * order to correctly interpret the index file, pick character that
18 * is outside the range, to cause the reader to abort.
21 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
22 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
24 struct index_state the_index;
26 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
28 istate->cache[nr] = ce;
29 add_name_hash(istate, ce);
32 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
34 struct cache_entry *old = istate->cache[nr];
36 remove_name_hash(old);
37 set_index_entry(istate, nr, ce);
38 istate->cache_changed = 1;
41 void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
43 struct cache_entry *old = istate->cache[nr], *new;
44 int namelen = strlen(new_name);
46 new = xmalloc(cache_entry_size(namelen));
47 copy_cache_entry(new, old);
48 new->ce_flags &= ~(CE_STATE_MASK | CE_NAMEMASK);
49 new->ce_flags |= (namelen >= CE_NAMEMASK ? CE_NAMEMASK : namelen);
50 memcpy(new->name, new_name, namelen + 1);
52 cache_tree_invalidate_path(istate->cache_tree, old->name);
53 remove_index_entry_at(istate, nr);
54 add_index_entry(istate, new, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
58 * This only updates the "non-critical" parts of the directory
59 * cache, ie the parts that aren't tracked by GIT, and only used
60 * to validate the cache.
62 void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
64 ce->ce_ctime = st->st_ctime;
65 ce->ce_mtime = st->st_mtime;
66 ce->ce_dev = st->st_dev;
67 ce->ce_ino = st->st_ino;
68 ce->ce_uid = st->st_uid;
69 ce->ce_gid = st->st_gid;
70 ce->ce_size = st->st_size;
72 if (assume_unchanged)
73 ce->ce_flags |= CE_VALID;
75 if (S_ISREG(st->st_mode))
76 ce_mark_uptodate(ce);
79 static int ce_compare_data(struct cache_entry *ce, struct stat *st)
81 int match = -1;
82 int fd = open(ce->name, O_RDONLY);
84 if (fd >= 0) {
85 unsigned char sha1[20];
86 if (!index_fd(sha1, fd, st, 0, OBJ_BLOB, ce->name))
87 match = hashcmp(sha1, ce->sha1);
88 /* index_fd() closed the file descriptor already */
90 return match;
93 static int ce_compare_link(struct cache_entry *ce, size_t expected_size)
95 int match = -1;
96 char *target;
97 void *buffer;
98 unsigned long size;
99 enum object_type type;
100 int len;
102 target = xmalloc(expected_size);
103 len = readlink(ce->name, target, expected_size);
104 if (len != expected_size) {
105 free(target);
106 return -1;
108 buffer = read_sha1_file(ce->sha1, &type, &size);
109 if (!buffer) {
110 free(target);
111 return -1;
113 if (size == expected_size)
114 match = memcmp(buffer, target, size);
115 free(buffer);
116 free(target);
117 return match;
120 static int ce_compare_gitlink(struct cache_entry *ce)
122 unsigned char sha1[20];
125 * We don't actually require that the .git directory
126 * under GITLINK directory be a valid git directory. It
127 * might even be missing (in case nobody populated that
128 * sub-project).
130 * If so, we consider it always to match.
132 if (resolve_gitlink_ref(ce->name, "HEAD", sha1) < 0)
133 return 0;
134 return hashcmp(sha1, ce->sha1);
137 static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
139 switch (st->st_mode & S_IFMT) {
140 case S_IFREG:
141 if (ce_compare_data(ce, st))
142 return DATA_CHANGED;
143 break;
144 case S_IFLNK:
145 if (ce_compare_link(ce, xsize_t(st->st_size)))
146 return DATA_CHANGED;
147 break;
148 case S_IFDIR:
149 if (S_ISGITLINK(ce->ce_mode))
150 return 0;
151 default:
152 return TYPE_CHANGED;
154 return 0;
157 static int is_empty_blob_sha1(const unsigned char *sha1)
159 static const unsigned char empty_blob_sha1[20] = {
160 0xe6,0x9d,0xe2,0x9b,0xb2,0xd1,0xd6,0x43,0x4b,0x8b,
161 0x29,0xae,0x77,0x5a,0xd8,0xc2,0xe4,0x8c,0x53,0x91
164 return !hashcmp(sha1, empty_blob_sha1);
167 static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
169 unsigned int changed = 0;
171 if (ce->ce_flags & CE_REMOVE)
172 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
174 switch (ce->ce_mode & S_IFMT) {
175 case S_IFREG:
176 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
177 /* We consider only the owner x bit to be relevant for
178 * "mode changes"
180 if (trust_executable_bit &&
181 (0100 & (ce->ce_mode ^ st->st_mode)))
182 changed |= MODE_CHANGED;
183 break;
184 case S_IFLNK:
185 if (!S_ISLNK(st->st_mode) &&
186 (has_symlinks || !S_ISREG(st->st_mode)))
187 changed |= TYPE_CHANGED;
188 break;
189 case S_IFGITLINK:
190 if (!S_ISDIR(st->st_mode))
191 changed |= TYPE_CHANGED;
192 else if (ce_compare_gitlink(ce))
193 changed |= DATA_CHANGED;
194 return changed;
195 default:
196 die("internal error: ce_mode is %o", ce->ce_mode);
198 if (ce->ce_mtime != (unsigned int) st->st_mtime)
199 changed |= MTIME_CHANGED;
200 if (trust_ctime && ce->ce_ctime != (unsigned int) st->st_ctime)
201 changed |= CTIME_CHANGED;
203 if (ce->ce_uid != (unsigned int) st->st_uid ||
204 ce->ce_gid != (unsigned int) st->st_gid)
205 changed |= OWNER_CHANGED;
206 if (ce->ce_ino != (unsigned int) st->st_ino)
207 changed |= INODE_CHANGED;
209 #ifdef USE_STDEV
211 * st_dev breaks on network filesystems where different
212 * clients will have different views of what "device"
213 * the filesystem is on
215 if (ce->ce_dev != (unsigned int) st->st_dev)
216 changed |= INODE_CHANGED;
217 #endif
219 if (ce->ce_size != (unsigned int) st->st_size)
220 changed |= DATA_CHANGED;
222 /* Racily smudged entry? */
223 if (!ce->ce_size) {
224 if (!is_empty_blob_sha1(ce->sha1))
225 changed |= DATA_CHANGED;
228 return changed;
231 static int is_racy_timestamp(const struct index_state *istate, struct cache_entry *ce)
233 return (!S_ISGITLINK(ce->ce_mode) &&
234 istate->timestamp &&
235 ((unsigned int)istate->timestamp) <= ce->ce_mtime);
238 int ie_match_stat(const struct index_state *istate,
239 struct cache_entry *ce, struct stat *st,
240 unsigned int options)
242 unsigned int changed;
243 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
244 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
247 * If it's marked as always valid in the index, it's
248 * valid whatever the checked-out copy says.
250 if (!ignore_valid && (ce->ce_flags & CE_VALID))
251 return 0;
253 changed = ce_match_stat_basic(ce, st);
256 * Within 1 second of this sequence:
257 * echo xyzzy >file && git-update-index --add file
258 * running this command:
259 * echo frotz >file
260 * would give a falsely clean cache entry. The mtime and
261 * length match the cache, and other stat fields do not change.
263 * We could detect this at update-index time (the cache entry
264 * being registered/updated records the same time as "now")
265 * and delay the return from git-update-index, but that would
266 * effectively mean we can make at most one commit per second,
267 * which is not acceptable. Instead, we check cache entries
268 * whose mtime are the same as the index file timestamp more
269 * carefully than others.
271 if (!changed && is_racy_timestamp(istate, ce)) {
272 if (assume_racy_is_modified)
273 changed |= DATA_CHANGED;
274 else
275 changed |= ce_modified_check_fs(ce, st);
278 return changed;
281 int ie_modified(const struct index_state *istate,
282 struct cache_entry *ce, struct stat *st, unsigned int options)
284 int changed, changed_fs;
286 changed = ie_match_stat(istate, ce, st, options);
287 if (!changed)
288 return 0;
290 * If the mode or type has changed, there's no point in trying
291 * to refresh the entry - it's not going to match
293 if (changed & (MODE_CHANGED | TYPE_CHANGED))
294 return changed;
296 /* Immediately after read-tree or update-index --cacheinfo,
297 * the length field is zero. For other cases the ce_size
298 * should match the SHA1 recorded in the index entry.
300 if ((changed & DATA_CHANGED) && ce->ce_size != 0)
301 return changed;
303 changed_fs = ce_modified_check_fs(ce, st);
304 if (changed_fs)
305 return changed | changed_fs;
306 return 0;
309 int base_name_compare(const char *name1, int len1, int mode1,
310 const char *name2, int len2, int mode2)
312 unsigned char c1, c2;
313 int len = len1 < len2 ? len1 : len2;
314 int cmp;
316 cmp = memcmp(name1, name2, len);
317 if (cmp)
318 return cmp;
319 c1 = name1[len];
320 c2 = name2[len];
321 if (!c1 && S_ISDIR(mode1))
322 c1 = '/';
323 if (!c2 && S_ISDIR(mode2))
324 c2 = '/';
325 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
329 * df_name_compare() is identical to base_name_compare(), except it
330 * compares conflicting directory/file entries as equal. Note that
331 * while a directory name compares as equal to a regular file, they
332 * then individually compare _differently_ to a filename that has
333 * a dot after the basename (because '\0' < '.' < '/').
335 * This is used by routines that want to traverse the git namespace
336 * but then handle conflicting entries together when possible.
338 int df_name_compare(const char *name1, int len1, int mode1,
339 const char *name2, int len2, int mode2)
341 int len = len1 < len2 ? len1 : len2, cmp;
342 unsigned char c1, c2;
344 cmp = memcmp(name1, name2, len);
345 if (cmp)
346 return cmp;
347 /* Directories and files compare equal (same length, same name) */
348 if (len1 == len2)
349 return 0;
350 c1 = name1[len];
351 if (!c1 && S_ISDIR(mode1))
352 c1 = '/';
353 c2 = name2[len];
354 if (!c2 && S_ISDIR(mode2))
355 c2 = '/';
356 if (c1 == '/' && !c2)
357 return 0;
358 if (c2 == '/' && !c1)
359 return 0;
360 return c1 - c2;
363 int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
365 int len1 = flags1 & CE_NAMEMASK;
366 int len2 = flags2 & CE_NAMEMASK;
367 int len = len1 < len2 ? len1 : len2;
368 int cmp;
370 cmp = memcmp(name1, name2, len);
371 if (cmp)
372 return cmp;
373 if (len1 < len2)
374 return -1;
375 if (len1 > len2)
376 return 1;
378 /* Compare stages */
379 flags1 &= CE_STAGEMASK;
380 flags2 &= CE_STAGEMASK;
382 if (flags1 < flags2)
383 return -1;
384 if (flags1 > flags2)
385 return 1;
386 return 0;
389 int index_name_pos(const struct index_state *istate, const char *name, int namelen)
391 int first, last;
393 first = 0;
394 last = istate->cache_nr;
395 while (last > first) {
396 int next = (last + first) >> 1;
397 struct cache_entry *ce = istate->cache[next];
398 int cmp = cache_name_compare(name, namelen, ce->name, ce->ce_flags);
399 if (!cmp)
400 return next;
401 if (cmp < 0) {
402 last = next;
403 continue;
405 first = next+1;
407 return -first-1;
410 /* Remove entry, return true if there are more entries to go.. */
411 int remove_index_entry_at(struct index_state *istate, int pos)
413 struct cache_entry *ce = istate->cache[pos];
415 remove_name_hash(ce);
416 istate->cache_changed = 1;
417 istate->cache_nr--;
418 if (pos >= istate->cache_nr)
419 return 0;
420 memmove(istate->cache + pos,
421 istate->cache + pos + 1,
422 (istate->cache_nr - pos) * sizeof(struct cache_entry *));
423 return 1;
426 int remove_file_from_index(struct index_state *istate, const char *path)
428 int pos = index_name_pos(istate, path, strlen(path));
429 if (pos < 0)
430 pos = -pos-1;
431 cache_tree_invalidate_path(istate->cache_tree, path);
432 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
433 remove_index_entry_at(istate, pos);
434 return 0;
437 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
439 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
442 static int index_name_pos_also_unmerged(struct index_state *istate,
443 const char *path, int namelen)
445 int pos = index_name_pos(istate, path, namelen);
446 struct cache_entry *ce;
448 if (pos >= 0)
449 return pos;
451 /* maybe unmerged? */
452 pos = -1 - pos;
453 if (pos >= istate->cache_nr ||
454 compare_name((ce = istate->cache[pos]), path, namelen))
455 return -1;
457 /* order of preference: stage 2, 1, 3 */
458 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
459 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
460 !compare_name(ce, path, namelen))
461 pos++;
462 return pos;
465 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
467 int len = ce_namelen(ce);
468 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
472 * If we add a filename that aliases in the cache, we will use the
473 * name that we already have - but we don't want to update the same
474 * alias twice, because that implies that there were actually two
475 * different files with aliasing names!
477 * So we use the CE_ADDED flag to verify that the alias was an old
478 * one before we accept it as
480 static struct cache_entry *create_alias_ce(struct cache_entry *ce, struct cache_entry *alias)
482 int len;
483 struct cache_entry *new;
485 if (alias->ce_flags & CE_ADDED)
486 die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
488 /* Ok, create the new entry using the name of the existing alias */
489 len = ce_namelen(alias);
490 new = xcalloc(1, cache_entry_size(len));
491 memcpy(new->name, alias->name, len);
492 copy_cache_entry(new, ce);
493 free(ce);
494 return new;
497 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
499 int size, namelen, was_same;
500 mode_t st_mode = st->st_mode;
501 struct cache_entry *ce, *alias;
502 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_RACY_IS_DIRTY;
503 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
504 int pretend = flags & ADD_CACHE_PRETEND;
506 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
507 return error("%s: can only add regular files, symbolic links or git-directories", path);
509 namelen = strlen(path);
510 if (S_ISDIR(st_mode)) {
511 while (namelen && path[namelen-1] == '/')
512 namelen--;
514 size = cache_entry_size(namelen);
515 ce = xcalloc(1, size);
516 memcpy(ce->name, path, namelen);
517 ce->ce_flags = namelen;
518 fill_stat_cache_info(ce, st);
520 if (trust_executable_bit && has_symlinks)
521 ce->ce_mode = create_ce_mode(st_mode);
522 else {
523 /* If there is an existing entry, pick the mode bits and type
524 * from it, otherwise assume unexecutable regular file.
526 struct cache_entry *ent;
527 int pos = index_name_pos_also_unmerged(istate, path, namelen);
529 ent = (0 <= pos) ? istate->cache[pos] : NULL;
530 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
533 alias = index_name_exists(istate, ce->name, ce_namelen(ce), ignore_case);
534 if (alias && !ce_stage(alias) && !ie_match_stat(istate, alias, st, ce_option)) {
535 /* Nothing changed, really */
536 free(ce);
537 ce_mark_uptodate(alias);
538 alias->ce_flags |= CE_ADDED;
539 return 0;
541 if (index_path(ce->sha1, path, st, 1))
542 return error("unable to index file %s", path);
543 if (ignore_case && alias && different_name(ce, alias))
544 ce = create_alias_ce(ce, alias);
545 ce->ce_flags |= CE_ADDED;
547 /* It was suspected to be racily clean, but it turns out to be Ok */
548 was_same = (alias &&
549 !ce_stage(alias) &&
550 !hashcmp(alias->sha1, ce->sha1) &&
551 ce->ce_mode == alias->ce_mode);
553 if (pretend)
555 else if (add_index_entry(istate, ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE))
556 return error("unable to add %s to index",path);
557 if (verbose && !was_same)
558 printf("add '%s'\n", path);
559 return 0;
562 int add_file_to_index(struct index_state *istate, const char *path, int flags)
564 struct stat st;
565 if (lstat(path, &st))
566 die("%s: unable to stat (%s)", path, strerror(errno));
567 return add_to_index(istate, path, &st, flags);
570 struct cache_entry *make_cache_entry(unsigned int mode,
571 const unsigned char *sha1, const char *path, int stage,
572 int refresh)
574 int size, len;
575 struct cache_entry *ce;
577 if (!verify_path(path))
578 return NULL;
580 len = strlen(path);
581 size = cache_entry_size(len);
582 ce = xcalloc(1, size);
584 hashcpy(ce->sha1, sha1);
585 memcpy(ce->name, path, len);
586 ce->ce_flags = create_ce_flags(len, stage);
587 ce->ce_mode = create_ce_mode(mode);
589 if (refresh)
590 return refresh_cache_entry(ce, 0);
592 return ce;
595 int ce_same_name(struct cache_entry *a, struct cache_entry *b)
597 int len = ce_namelen(a);
598 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
601 int ce_path_match(const struct cache_entry *ce, const char **pathspec)
603 const char *match, *name;
604 int len;
606 if (!pathspec)
607 return 1;
609 len = ce_namelen(ce);
610 name = ce->name;
611 while ((match = *pathspec++) != NULL) {
612 int matchlen = strlen(match);
613 if (matchlen > len)
614 continue;
615 if (memcmp(name, match, matchlen))
616 continue;
617 if (matchlen && name[matchlen-1] == '/')
618 return 1;
619 if (name[matchlen] == '/' || !name[matchlen])
620 return 1;
621 if (!matchlen)
622 return 1;
624 return 0;
628 * We fundamentally don't like some paths: we don't want
629 * dot or dot-dot anywhere, and for obvious reasons don't
630 * want to recurse into ".git" either.
632 * Also, we don't want double slashes or slashes at the
633 * end that can make pathnames ambiguous.
635 static int verify_dotfile(const char *rest)
638 * The first character was '.', but that
639 * has already been discarded, we now test
640 * the rest.
642 switch (*rest) {
643 /* "." is not allowed */
644 case '\0': case '/':
645 return 0;
648 * ".git" followed by NUL or slash is bad. This
649 * shares the path end test with the ".." case.
651 case 'g':
652 if (rest[1] != 'i')
653 break;
654 if (rest[2] != 't')
655 break;
656 rest += 2;
657 /* fallthrough */
658 case '.':
659 if (rest[1] == '\0' || rest[1] == '/')
660 return 0;
662 return 1;
665 int verify_path(const char *path)
667 char c;
669 goto inside;
670 for (;;) {
671 if (!c)
672 return 1;
673 if (c == '/') {
674 inside:
675 c = *path++;
676 switch (c) {
677 default:
678 continue;
679 case '/': case '\0':
680 break;
681 case '.':
682 if (verify_dotfile(path))
683 continue;
685 return 0;
687 c = *path++;
692 * Do we have another file that has the beginning components being a
693 * proper superset of the name we're trying to add?
695 static int has_file_name(struct index_state *istate,
696 const struct cache_entry *ce, int pos, int ok_to_replace)
698 int retval = 0;
699 int len = ce_namelen(ce);
700 int stage = ce_stage(ce);
701 const char *name = ce->name;
703 while (pos < istate->cache_nr) {
704 struct cache_entry *p = istate->cache[pos++];
706 if (len >= ce_namelen(p))
707 break;
708 if (memcmp(name, p->name, len))
709 break;
710 if (ce_stage(p) != stage)
711 continue;
712 if (p->name[len] != '/')
713 continue;
714 if (p->ce_flags & CE_REMOVE)
715 continue;
716 retval = -1;
717 if (!ok_to_replace)
718 break;
719 remove_index_entry_at(istate, --pos);
721 return retval;
725 * Do we have another file with a pathname that is a proper
726 * subset of the name we're trying to add?
728 static int has_dir_name(struct index_state *istate,
729 const struct cache_entry *ce, int pos, int ok_to_replace)
731 int retval = 0;
732 int stage = ce_stage(ce);
733 const char *name = ce->name;
734 const char *slash = name + ce_namelen(ce);
736 for (;;) {
737 int len;
739 for (;;) {
740 if (*--slash == '/')
741 break;
742 if (slash <= ce->name)
743 return retval;
745 len = slash - name;
747 pos = index_name_pos(istate, name, create_ce_flags(len, stage));
748 if (pos >= 0) {
750 * Found one, but not so fast. This could
751 * be a marker that says "I was here, but
752 * I am being removed". Such an entry is
753 * not a part of the resulting tree, and
754 * it is Ok to have a directory at the same
755 * path.
757 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
758 retval = -1;
759 if (!ok_to_replace)
760 break;
761 remove_index_entry_at(istate, pos);
762 continue;
765 else
766 pos = -pos-1;
769 * Trivial optimization: if we find an entry that
770 * already matches the sub-directory, then we know
771 * we're ok, and we can exit.
773 while (pos < istate->cache_nr) {
774 struct cache_entry *p = istate->cache[pos];
775 if ((ce_namelen(p) <= len) ||
776 (p->name[len] != '/') ||
777 memcmp(p->name, name, len))
778 break; /* not our subdirectory */
779 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
781 * p is at the same stage as our entry, and
782 * is a subdirectory of what we are looking
783 * at, so we cannot have conflicts at our
784 * level or anything shorter.
786 return retval;
787 pos++;
790 return retval;
793 /* We may be in a situation where we already have path/file and path
794 * is being added, or we already have path and path/file is being
795 * added. Either one would result in a nonsense tree that has path
796 * twice when git-write-tree tries to write it out. Prevent it.
798 * If ok-to-replace is specified, we remove the conflicting entries
799 * from the cache so the caller should recompute the insert position.
800 * When this happens, we return non-zero.
802 static int check_file_directory_conflict(struct index_state *istate,
803 const struct cache_entry *ce,
804 int pos, int ok_to_replace)
806 int retval;
809 * When ce is an "I am going away" entry, we allow it to be added
811 if (ce->ce_flags & CE_REMOVE)
812 return 0;
815 * We check if the path is a sub-path of a subsequent pathname
816 * first, since removing those will not change the position
817 * in the array.
819 retval = has_file_name(istate, ce, pos, ok_to_replace);
822 * Then check if the path might have a clashing sub-directory
823 * before it.
825 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
828 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
830 int pos;
831 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
832 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
833 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
835 cache_tree_invalidate_path(istate->cache_tree, ce->name);
836 pos = index_name_pos(istate, ce->name, ce->ce_flags);
838 /* existing match? Just replace it. */
839 if (pos >= 0) {
840 replace_index_entry(istate, pos, ce);
841 return 0;
843 pos = -pos-1;
846 * Inserting a merged entry ("stage 0") into the index
847 * will always replace all non-merged entries..
849 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
850 while (ce_same_name(istate->cache[pos], ce)) {
851 ok_to_add = 1;
852 if (!remove_index_entry_at(istate, pos))
853 break;
857 if (!ok_to_add)
858 return -1;
859 if (!verify_path(ce->name))
860 return -1;
862 if (!skip_df_check &&
863 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
864 if (!ok_to_replace)
865 return error("'%s' appears as both a file and as a directory",
866 ce->name);
867 pos = index_name_pos(istate, ce->name, ce->ce_flags);
868 pos = -pos-1;
870 return pos + 1;
873 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
875 int pos;
877 if (option & ADD_CACHE_JUST_APPEND)
878 pos = istate->cache_nr;
879 else {
880 int ret;
881 ret = add_index_entry_with_check(istate, ce, option);
882 if (ret <= 0)
883 return ret;
884 pos = ret - 1;
887 /* Make sure the array is big enough .. */
888 if (istate->cache_nr == istate->cache_alloc) {
889 istate->cache_alloc = alloc_nr(istate->cache_alloc);
890 istate->cache = xrealloc(istate->cache,
891 istate->cache_alloc * sizeof(struct cache_entry *));
894 /* Add it in.. */
895 istate->cache_nr++;
896 if (istate->cache_nr > pos + 1)
897 memmove(istate->cache + pos + 1,
898 istate->cache + pos,
899 (istate->cache_nr - pos - 1) * sizeof(ce));
900 set_index_entry(istate, pos, ce);
901 istate->cache_changed = 1;
902 return 0;
906 * "refresh" does not calculate a new sha1 file or bring the
907 * cache up-to-date for mode/content changes. But what it
908 * _does_ do is to "re-match" the stat information of a file
909 * with the cache, so that you can refresh the cache for a
910 * file that hasn't been changed but where the stat entry is
911 * out of date.
913 * For example, you'd want to do this after doing a "git-read-tree",
914 * to link up the stat cache details with the proper files.
916 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
917 struct cache_entry *ce,
918 unsigned int options, int *err)
920 struct stat st;
921 struct cache_entry *updated;
922 int changed, size;
923 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
925 if (ce_uptodate(ce))
926 return ce;
929 * CE_VALID means the user promised us that the change to
930 * the work tree does not matter and told us not to worry.
932 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
933 ce_mark_uptodate(ce);
934 return ce;
937 if (lstat(ce->name, &st) < 0) {
938 if (err)
939 *err = errno;
940 return NULL;
943 changed = ie_match_stat(istate, ce, &st, options);
944 if (!changed) {
946 * The path is unchanged. If we were told to ignore
947 * valid bit, then we did the actual stat check and
948 * found that the entry is unmodified. If the entry
949 * is not marked VALID, this is the place to mark it
950 * valid again, under "assume unchanged" mode.
952 if (ignore_valid && assume_unchanged &&
953 !(ce->ce_flags & CE_VALID))
954 ; /* mark this one VALID again */
955 else {
957 * We do not mark the index itself "modified"
958 * because CE_UPTODATE flag is in-core only;
959 * we are not going to write this change out.
961 ce_mark_uptodate(ce);
962 return ce;
966 if (ie_modified(istate, ce, &st, options)) {
967 if (err)
968 *err = EINVAL;
969 return NULL;
972 size = ce_size(ce);
973 updated = xmalloc(size);
974 memcpy(updated, ce, size);
975 fill_stat_cache_info(updated, &st);
977 * If ignore_valid is not set, we should leave CE_VALID bit
978 * alone. Otherwise, paths marked with --no-assume-unchanged
979 * (i.e. things to be edited) will reacquire CE_VALID bit
980 * automatically, which is not really what we want.
982 if (!ignore_valid && assume_unchanged &&
983 !(ce->ce_flags & CE_VALID))
984 updated->ce_flags &= ~CE_VALID;
986 return updated;
989 int refresh_index(struct index_state *istate, unsigned int flags, const char **pathspec, char *seen)
991 int i;
992 int has_errors = 0;
993 int really = (flags & REFRESH_REALLY) != 0;
994 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
995 int quiet = (flags & REFRESH_QUIET) != 0;
996 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
997 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
998 unsigned int options = really ? CE_MATCH_IGNORE_VALID : 0;
999 const char *needs_update_message;
1001 needs_update_message = ((flags & REFRESH_SAY_CHANGED)
1002 ? "locally modified" : "needs update");
1003 for (i = 0; i < istate->cache_nr; i++) {
1004 struct cache_entry *ce, *new;
1005 int cache_errno = 0;
1007 ce = istate->cache[i];
1008 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1009 continue;
1011 if (ce_stage(ce)) {
1012 while ((i < istate->cache_nr) &&
1013 ! strcmp(istate->cache[i]->name, ce->name))
1014 i++;
1015 i--;
1016 if (allow_unmerged)
1017 continue;
1018 printf("%s: needs merge\n", ce->name);
1019 has_errors = 1;
1020 continue;
1023 if (pathspec && !match_pathspec(pathspec, ce->name, strlen(ce->name), 0, seen))
1024 continue;
1026 new = refresh_cache_ent(istate, ce, options, &cache_errno);
1027 if (new == ce)
1028 continue;
1029 if (!new) {
1030 if (not_new && cache_errno == ENOENT)
1031 continue;
1032 if (really && cache_errno == EINVAL) {
1033 /* If we are doing --really-refresh that
1034 * means the index is not valid anymore.
1036 ce->ce_flags &= ~CE_VALID;
1037 istate->cache_changed = 1;
1039 if (quiet)
1040 continue;
1041 printf("%s: %s\n", ce->name, needs_update_message);
1042 has_errors = 1;
1043 continue;
1046 replace_index_entry(istate, i, new);
1048 return has_errors;
1051 struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
1053 return refresh_cache_ent(&the_index, ce, really, NULL);
1056 static int verify_hdr(struct cache_header *hdr, unsigned long size)
1058 SHA_CTX c;
1059 unsigned char sha1[20];
1061 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1062 return error("bad signature");
1063 if (hdr->hdr_version != htonl(2))
1064 return error("bad index version");
1065 SHA1_Init(&c);
1066 SHA1_Update(&c, hdr, size - 20);
1067 SHA1_Final(sha1, &c);
1068 if (hashcmp(sha1, (unsigned char *)hdr + size - 20))
1069 return error("bad index file sha1 signature");
1070 return 0;
1073 static int read_index_extension(struct index_state *istate,
1074 const char *ext, void *data, unsigned long sz)
1076 switch (CACHE_EXT(ext)) {
1077 case CACHE_EXT_TREE:
1078 istate->cache_tree = cache_tree_read(data, sz);
1079 break;
1080 default:
1081 if (*ext < 'A' || 'Z' < *ext)
1082 return error("index uses %.4s extension, which we do not understand",
1083 ext);
1084 fprintf(stderr, "ignoring %.4s extension\n", ext);
1085 break;
1087 return 0;
1090 int read_index(struct index_state *istate)
1092 return read_index_from(istate, get_index_file());
1095 static void convert_from_disk(struct ondisk_cache_entry *ondisk, struct cache_entry *ce)
1097 size_t len;
1099 ce->ce_ctime = ntohl(ondisk->ctime.sec);
1100 ce->ce_mtime = ntohl(ondisk->mtime.sec);
1101 ce->ce_dev = ntohl(ondisk->dev);
1102 ce->ce_ino = ntohl(ondisk->ino);
1103 ce->ce_mode = ntohl(ondisk->mode);
1104 ce->ce_uid = ntohl(ondisk->uid);
1105 ce->ce_gid = ntohl(ondisk->gid);
1106 ce->ce_size = ntohl(ondisk->size);
1107 /* On-disk flags are just 16 bits */
1108 ce->ce_flags = ntohs(ondisk->flags);
1109 hashcpy(ce->sha1, ondisk->sha1);
1111 len = ce->ce_flags & CE_NAMEMASK;
1112 if (len == CE_NAMEMASK)
1113 len = strlen(ondisk->name);
1115 * NEEDSWORK: If the original index is crafted, this copy could
1116 * go unchecked.
1118 memcpy(ce->name, ondisk->name, len + 1);
1121 static inline size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1123 long per_entry;
1125 per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1128 * Alignment can cause differences. This should be "alignof", but
1129 * since that's a gcc'ism, just use the size of a pointer.
1131 per_entry += sizeof(void *);
1132 return ondisk_size + entries*per_entry;
1135 /* remember to discard_cache() before reading a different cache! */
1136 int read_index_from(struct index_state *istate, const char *path)
1138 int fd, i;
1139 struct stat st;
1140 unsigned long src_offset, dst_offset;
1141 struct cache_header *hdr;
1142 void *mmap;
1143 size_t mmap_size;
1145 errno = EBUSY;
1146 if (istate->alloc)
1147 return istate->cache_nr;
1149 errno = ENOENT;
1150 istate->timestamp = 0;
1151 fd = open(path, O_RDONLY);
1152 if (fd < 0) {
1153 if (errno == ENOENT)
1154 return 0;
1155 die("index file open failed (%s)", strerror(errno));
1158 if (fstat(fd, &st))
1159 die("cannot stat the open index (%s)", strerror(errno));
1161 errno = EINVAL;
1162 mmap_size = xsize_t(st.st_size);
1163 if (mmap_size < sizeof(struct cache_header) + 20)
1164 die("index file smaller than expected");
1166 mmap = xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
1167 close(fd);
1168 if (mmap == MAP_FAILED)
1169 die("unable to map index file");
1171 hdr = mmap;
1172 if (verify_hdr(hdr, mmap_size) < 0)
1173 goto unmap;
1175 istate->cache_nr = ntohl(hdr->hdr_entries);
1176 istate->cache_alloc = alloc_nr(istate->cache_nr);
1177 istate->cache = xcalloc(istate->cache_alloc, sizeof(struct cache_entry *));
1180 * The disk format is actually larger than the in-memory format,
1181 * due to space for nsec etc, so even though the in-memory one
1182 * has room for a few more flags, we can allocate using the same
1183 * index size
1185 istate->alloc = xmalloc(estimate_cache_size(mmap_size, istate->cache_nr));
1187 src_offset = sizeof(*hdr);
1188 dst_offset = 0;
1189 for (i = 0; i < istate->cache_nr; i++) {
1190 struct ondisk_cache_entry *disk_ce;
1191 struct cache_entry *ce;
1193 disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
1194 ce = (struct cache_entry *)((char *)istate->alloc + dst_offset);
1195 convert_from_disk(disk_ce, ce);
1196 set_index_entry(istate, i, ce);
1198 src_offset += ondisk_ce_size(ce);
1199 dst_offset += ce_size(ce);
1201 istate->timestamp = st.st_mtime;
1202 while (src_offset <= mmap_size - 20 - 8) {
1203 /* After an array of active_nr index entries,
1204 * there can be arbitrary number of extended
1205 * sections, each of which is prefixed with
1206 * extension name (4-byte) and section length
1207 * in 4-byte network byte order.
1209 unsigned long extsize;
1210 memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
1211 extsize = ntohl(extsize);
1212 if (read_index_extension(istate,
1213 (const char *) mmap + src_offset,
1214 (char *) mmap + src_offset + 8,
1215 extsize) < 0)
1216 goto unmap;
1217 src_offset += 8;
1218 src_offset += extsize;
1220 munmap(mmap, mmap_size);
1221 return istate->cache_nr;
1223 unmap:
1224 munmap(mmap, mmap_size);
1225 errno = EINVAL;
1226 die("index file corrupt");
1229 int discard_index(struct index_state *istate)
1231 istate->cache_nr = 0;
1232 istate->cache_changed = 0;
1233 istate->timestamp = 0;
1234 free_hash(&istate->name_hash);
1235 cache_tree_free(&(istate->cache_tree));
1236 free(istate->alloc);
1237 istate->alloc = NULL;
1239 /* no need to throw away allocated active_cache */
1240 return 0;
1243 int unmerged_index(const struct index_state *istate)
1245 int i;
1246 for (i = 0; i < istate->cache_nr; i++) {
1247 if (ce_stage(istate->cache[i]))
1248 return 1;
1250 return 0;
1253 #define WRITE_BUFFER_SIZE 8192
1254 static unsigned char write_buffer[WRITE_BUFFER_SIZE];
1255 static unsigned long write_buffer_len;
1257 static int ce_write_flush(SHA_CTX *context, int fd)
1259 unsigned int buffered = write_buffer_len;
1260 if (buffered) {
1261 SHA1_Update(context, write_buffer, buffered);
1262 if (write_in_full(fd, write_buffer, buffered) != buffered)
1263 return -1;
1264 write_buffer_len = 0;
1266 return 0;
1269 static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
1271 while (len) {
1272 unsigned int buffered = write_buffer_len;
1273 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
1274 if (partial > len)
1275 partial = len;
1276 memcpy(write_buffer + buffered, data, partial);
1277 buffered += partial;
1278 if (buffered == WRITE_BUFFER_SIZE) {
1279 write_buffer_len = buffered;
1280 if (ce_write_flush(context, fd))
1281 return -1;
1282 buffered = 0;
1284 write_buffer_len = buffered;
1285 len -= partial;
1286 data = (char *) data + partial;
1288 return 0;
1291 static int write_index_ext_header(SHA_CTX *context, int fd,
1292 unsigned int ext, unsigned int sz)
1294 ext = htonl(ext);
1295 sz = htonl(sz);
1296 return ((ce_write(context, fd, &ext, 4) < 0) ||
1297 (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
1300 static int ce_flush(SHA_CTX *context, int fd)
1302 unsigned int left = write_buffer_len;
1304 if (left) {
1305 write_buffer_len = 0;
1306 SHA1_Update(context, write_buffer, left);
1309 /* Flush first if not enough space for SHA1 signature */
1310 if (left + 20 > WRITE_BUFFER_SIZE) {
1311 if (write_in_full(fd, write_buffer, left) != left)
1312 return -1;
1313 left = 0;
1316 /* Append the SHA1 signature at the end */
1317 SHA1_Final(write_buffer + left, context);
1318 left += 20;
1319 return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0;
1322 static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
1325 * The only thing we care about in this function is to smudge the
1326 * falsely clean entry due to touch-update-touch race, so we leave
1327 * everything else as they are. We are called for entries whose
1328 * ce_mtime match the index file mtime.
1330 struct stat st;
1332 if (lstat(ce->name, &st) < 0)
1333 return;
1334 if (ce_match_stat_basic(ce, &st))
1335 return;
1336 if (ce_modified_check_fs(ce, &st)) {
1337 /* This is "racily clean"; smudge it. Note that this
1338 * is a tricky code. At first glance, it may appear
1339 * that it can break with this sequence:
1341 * $ echo xyzzy >frotz
1342 * $ git-update-index --add frotz
1343 * $ : >frotz
1344 * $ sleep 3
1345 * $ echo filfre >nitfol
1346 * $ git-update-index --add nitfol
1348 * but it does not. When the second update-index runs,
1349 * it notices that the entry "frotz" has the same timestamp
1350 * as index, and if we were to smudge it by resetting its
1351 * size to zero here, then the object name recorded
1352 * in index is the 6-byte file but the cached stat information
1353 * becomes zero --- which would then match what we would
1354 * obtain from the filesystem next time we stat("frotz").
1356 * However, the second update-index, before calling
1357 * this function, notices that the cached size is 6
1358 * bytes and what is on the filesystem is an empty
1359 * file, and never calls us, so the cached size information
1360 * for "frotz" stays 6 which does not match the filesystem.
1362 ce->ce_size = 0;
1366 static int ce_write_entry(SHA_CTX *c, int fd, struct cache_entry *ce)
1368 int size = ondisk_ce_size(ce);
1369 struct ondisk_cache_entry *ondisk = xcalloc(1, size);
1371 ondisk->ctime.sec = htonl(ce->ce_ctime);
1372 ondisk->ctime.nsec = 0;
1373 ondisk->mtime.sec = htonl(ce->ce_mtime);
1374 ondisk->mtime.nsec = 0;
1375 ondisk->dev = htonl(ce->ce_dev);
1376 ondisk->ino = htonl(ce->ce_ino);
1377 ondisk->mode = htonl(ce->ce_mode);
1378 ondisk->uid = htonl(ce->ce_uid);
1379 ondisk->gid = htonl(ce->ce_gid);
1380 ondisk->size = htonl(ce->ce_size);
1381 hashcpy(ondisk->sha1, ce->sha1);
1382 ondisk->flags = htons(ce->ce_flags);
1383 memcpy(ondisk->name, ce->name, ce_namelen(ce));
1385 return ce_write(c, fd, ondisk, size);
1388 int write_index(const struct index_state *istate, int newfd)
1390 SHA_CTX c;
1391 struct cache_header hdr;
1392 int i, err, removed;
1393 struct cache_entry **cache = istate->cache;
1394 int entries = istate->cache_nr;
1396 for (i = removed = 0; i < entries; i++)
1397 if (cache[i]->ce_flags & CE_REMOVE)
1398 removed++;
1400 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
1401 hdr.hdr_version = htonl(2);
1402 hdr.hdr_entries = htonl(entries - removed);
1404 SHA1_Init(&c);
1405 if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
1406 return -1;
1408 for (i = 0; i < entries; i++) {
1409 struct cache_entry *ce = cache[i];
1410 if (ce->ce_flags & CE_REMOVE)
1411 continue;
1412 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
1413 ce_smudge_racily_clean_entry(ce);
1414 if (ce_write_entry(&c, newfd, ce) < 0)
1415 return -1;
1418 /* Write extension data here */
1419 if (istate->cache_tree) {
1420 struct strbuf sb;
1422 strbuf_init(&sb, 0);
1423 cache_tree_write(&sb, istate->cache_tree);
1424 err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
1425 || ce_write(&c, newfd, sb.buf, sb.len) < 0;
1426 strbuf_release(&sb);
1427 if (err)
1428 return -1;
1430 return ce_flush(&c, newfd);
1434 * Read the index file that is potentially unmerged into given
1435 * index_state, dropping any unmerged entries. Returns true is
1436 * the index is unmerged. Callers who want to refuse to work
1437 * from an unmerged state can call this and check its return value,
1438 * instead of calling read_cache().
1440 int read_index_unmerged(struct index_state *istate)
1442 int i;
1443 struct cache_entry **dst;
1444 struct cache_entry *last = NULL;
1446 read_index(istate);
1447 dst = istate->cache;
1448 for (i = 0; i < istate->cache_nr; i++) {
1449 struct cache_entry *ce = istate->cache[i];
1450 if (ce_stage(ce)) {
1451 remove_name_hash(ce);
1452 if (last && !strcmp(ce->name, last->name))
1453 continue;
1454 cache_tree_invalidate_path(istate->cache_tree, ce->name);
1455 last = ce;
1456 continue;
1458 *dst++ = ce;
1460 istate->cache_nr = dst - istate->cache;
1461 return !!last;