builtin-bundle: add a --basis option that specifies a basis
[git/pieter.git] / read-cache.c
bloba940f8dfacb7cdefa8fcd43bcd46857273a2f0f2
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"
11 #include "tree.h"
12 #include "commit.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "revision.h"
17 /* Index extensions.
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.
26 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
27 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
29 struct index_state the_index;
31 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
33 istate->cache[nr] = ce;
34 add_name_hash(istate, ce);
37 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
39 struct cache_entry *old = istate->cache[nr];
41 remove_name_hash(old);
42 set_index_entry(istate, nr, ce);
43 istate->cache_changed = 1;
46 void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
48 struct cache_entry *old = istate->cache[nr], *new;
49 int namelen = strlen(new_name);
51 new = xmalloc(cache_entry_size(namelen));
52 copy_cache_entry(new, old);
53 new->ce_flags &= ~(CE_STATE_MASK | CE_NAMEMASK);
54 new->ce_flags |= (namelen >= CE_NAMEMASK ? CE_NAMEMASK : namelen);
55 memcpy(new->name, new_name, namelen + 1);
57 cache_tree_invalidate_path(istate->cache_tree, old->name);
58 remove_index_entry_at(istate, nr);
59 add_index_entry(istate, new, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
63 * This only updates the "non-critical" parts of the directory
64 * cache, ie the parts that aren't tracked by GIT, and only used
65 * to validate the cache.
67 void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
69 ce->ce_ctime = st->st_ctime;
70 ce->ce_mtime = st->st_mtime;
71 ce->ce_dev = st->st_dev;
72 ce->ce_ino = st->st_ino;
73 ce->ce_uid = st->st_uid;
74 ce->ce_gid = st->st_gid;
75 ce->ce_size = st->st_size;
77 if (assume_unchanged)
78 ce->ce_flags |= CE_VALID;
80 if (S_ISREG(st->st_mode))
81 ce_mark_uptodate(ce);
84 static int ce_compare_data(struct cache_entry *ce, struct stat *st)
86 int match = -1;
87 int fd = open(ce->name, O_RDONLY);
89 if (fd >= 0) {
90 unsigned char sha1[20];
91 if (!index_fd(sha1, fd, st, 0, OBJ_BLOB, ce->name))
92 match = hashcmp(sha1, ce->sha1);
93 /* index_fd() closed the file descriptor already */
95 return match;
98 static int ce_compare_link(struct cache_entry *ce, size_t expected_size)
100 int match = -1;
101 char *target;
102 void *buffer;
103 unsigned long size;
104 enum object_type type;
105 int len;
107 target = xmalloc(expected_size);
108 len = readlink(ce->name, target, expected_size);
109 if (len != expected_size) {
110 free(target);
111 return -1;
113 buffer = read_sha1_file(ce->sha1, &type, &size);
114 if (!buffer) {
115 free(target);
116 return -1;
118 if (size == expected_size)
119 match = memcmp(buffer, target, size);
120 free(buffer);
121 free(target);
122 return match;
125 static int ce_compare_gitlink(struct cache_entry *ce)
127 unsigned char sha1[20];
130 * We don't actually require that the .git directory
131 * under GITLINK directory be a valid git directory. It
132 * might even be missing (in case nobody populated that
133 * sub-project).
135 * If so, we consider it always to match.
137 if (resolve_gitlink_ref(ce->name, "HEAD", sha1) < 0)
138 return 0;
139 return hashcmp(sha1, ce->sha1);
142 static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
144 switch (st->st_mode & S_IFMT) {
145 case S_IFREG:
146 if (ce_compare_data(ce, st))
147 return DATA_CHANGED;
148 break;
149 case S_IFLNK:
150 if (ce_compare_link(ce, xsize_t(st->st_size)))
151 return DATA_CHANGED;
152 break;
153 case S_IFDIR:
154 if (S_ISGITLINK(ce->ce_mode))
155 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
156 default:
157 return TYPE_CHANGED;
159 return 0;
162 static int is_empty_blob_sha1(const unsigned char *sha1)
164 static const unsigned char empty_blob_sha1[20] = {
165 0xe6,0x9d,0xe2,0x9b,0xb2,0xd1,0xd6,0x43,0x4b,0x8b,
166 0x29,0xae,0x77,0x5a,0xd8,0xc2,0xe4,0x8c,0x53,0x91
169 return !hashcmp(sha1, empty_blob_sha1);
172 static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
174 unsigned int changed = 0;
176 if (ce->ce_flags & CE_REMOVE)
177 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
179 switch (ce->ce_mode & S_IFMT) {
180 case S_IFREG:
181 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
182 /* We consider only the owner x bit to be relevant for
183 * "mode changes"
185 if (trust_executable_bit &&
186 (0100 & (ce->ce_mode ^ st->st_mode)))
187 changed |= MODE_CHANGED;
188 break;
189 case S_IFLNK:
190 if (!S_ISLNK(st->st_mode) &&
191 (has_symlinks || !S_ISREG(st->st_mode)))
192 changed |= TYPE_CHANGED;
193 break;
194 case S_IFGITLINK:
195 /* We ignore most of the st_xxx fields for gitlinks */
196 if (!S_ISDIR(st->st_mode))
197 changed |= TYPE_CHANGED;
198 else if (ce_compare_gitlink(ce))
199 changed |= DATA_CHANGED;
200 return changed;
201 default:
202 die("internal error: ce_mode is %o", ce->ce_mode);
204 if (ce->ce_mtime != (unsigned int) st->st_mtime)
205 changed |= MTIME_CHANGED;
206 if (trust_ctime && ce->ce_ctime != (unsigned int) st->st_ctime)
207 changed |= CTIME_CHANGED;
209 if (ce->ce_uid != (unsigned int) st->st_uid ||
210 ce->ce_gid != (unsigned int) st->st_gid)
211 changed |= OWNER_CHANGED;
212 if (ce->ce_ino != (unsigned int) st->st_ino)
213 changed |= INODE_CHANGED;
215 #ifdef USE_STDEV
217 * st_dev breaks on network filesystems where different
218 * clients will have different views of what "device"
219 * the filesystem is on
221 if (ce->ce_dev != (unsigned int) st->st_dev)
222 changed |= INODE_CHANGED;
223 #endif
225 if (ce->ce_size != (unsigned int) st->st_size)
226 changed |= DATA_CHANGED;
228 /* Racily smudged entry? */
229 if (!ce->ce_size) {
230 if (!is_empty_blob_sha1(ce->sha1))
231 changed |= DATA_CHANGED;
234 return changed;
237 static int is_racy_timestamp(const struct index_state *istate, struct cache_entry *ce)
239 return (!S_ISGITLINK(ce->ce_mode) &&
240 istate->timestamp &&
241 ((unsigned int)istate->timestamp) <= ce->ce_mtime);
244 int ie_match_stat(const struct index_state *istate,
245 struct cache_entry *ce, struct stat *st,
246 unsigned int options)
248 unsigned int changed;
249 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
250 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
253 * If it's marked as always valid in the index, it's
254 * valid whatever the checked-out copy says.
256 if (!ignore_valid && (ce->ce_flags & CE_VALID))
257 return 0;
259 changed = ce_match_stat_basic(ce, st);
262 * Within 1 second of this sequence:
263 * echo xyzzy >file && git-update-index --add file
264 * running this command:
265 * echo frotz >file
266 * would give a falsely clean cache entry. The mtime and
267 * length match the cache, and other stat fields do not change.
269 * We could detect this at update-index time (the cache entry
270 * being registered/updated records the same time as "now")
271 * and delay the return from git-update-index, but that would
272 * effectively mean we can make at most one commit per second,
273 * which is not acceptable. Instead, we check cache entries
274 * whose mtime are the same as the index file timestamp more
275 * carefully than others.
277 if (!changed && is_racy_timestamp(istate, ce)) {
278 if (assume_racy_is_modified)
279 changed |= DATA_CHANGED;
280 else
281 changed |= ce_modified_check_fs(ce, st);
284 return changed;
287 int ie_modified(const struct index_state *istate,
288 struct cache_entry *ce, struct stat *st, unsigned int options)
290 int changed, changed_fs;
292 changed = ie_match_stat(istate, ce, st, options);
293 if (!changed)
294 return 0;
296 * If the mode or type has changed, there's no point in trying
297 * to refresh the entry - it's not going to match
299 if (changed & (MODE_CHANGED | TYPE_CHANGED))
300 return changed;
303 * Immediately after read-tree or update-index --cacheinfo,
304 * the length field is zero, as we have never even read the
305 * lstat(2) information once, and we cannot trust DATA_CHANGED
306 * returned by ie_match_stat() which in turn was returned by
307 * ce_match_stat_basic() to signal that the filesize of the
308 * blob changed. We have to actually go to the filesystem to
309 * see if the contents match, and if so, should answer "unchanged".
311 * The logic does not apply to gitlinks, as ce_match_stat_basic()
312 * already has checked the actual HEAD from the filesystem in the
313 * subproject. If ie_match_stat() already said it is different,
314 * then we know it is.
316 if ((changed & DATA_CHANGED) &&
317 (S_ISGITLINK(ce->ce_mode) || ce->ce_size != 0))
318 return changed;
320 changed_fs = ce_modified_check_fs(ce, st);
321 if (changed_fs)
322 return changed | changed_fs;
323 return 0;
326 int base_name_compare(const char *name1, int len1, int mode1,
327 const char *name2, int len2, int mode2)
329 unsigned char c1, c2;
330 int len = len1 < len2 ? len1 : len2;
331 int cmp;
333 cmp = memcmp(name1, name2, len);
334 if (cmp)
335 return cmp;
336 c1 = name1[len];
337 c2 = name2[len];
338 if (!c1 && S_ISDIR(mode1))
339 c1 = '/';
340 if (!c2 && S_ISDIR(mode2))
341 c2 = '/';
342 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
346 * df_name_compare() is identical to base_name_compare(), except it
347 * compares conflicting directory/file entries as equal. Note that
348 * while a directory name compares as equal to a regular file, they
349 * then individually compare _differently_ to a filename that has
350 * a dot after the basename (because '\0' < '.' < '/').
352 * This is used by routines that want to traverse the git namespace
353 * but then handle conflicting entries together when possible.
355 int df_name_compare(const char *name1, int len1, int mode1,
356 const char *name2, int len2, int mode2)
358 int len = len1 < len2 ? len1 : len2, cmp;
359 unsigned char c1, c2;
361 cmp = memcmp(name1, name2, len);
362 if (cmp)
363 return cmp;
364 /* Directories and files compare equal (same length, same name) */
365 if (len1 == len2)
366 return 0;
367 c1 = name1[len];
368 if (!c1 && S_ISDIR(mode1))
369 c1 = '/';
370 c2 = name2[len];
371 if (!c2 && S_ISDIR(mode2))
372 c2 = '/';
373 if (c1 == '/' && !c2)
374 return 0;
375 if (c2 == '/' && !c1)
376 return 0;
377 return c1 - c2;
380 int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
382 int len1 = flags1 & CE_NAMEMASK;
383 int len2 = flags2 & CE_NAMEMASK;
384 int len = len1 < len2 ? len1 : len2;
385 int cmp;
387 cmp = memcmp(name1, name2, len);
388 if (cmp)
389 return cmp;
390 if (len1 < len2)
391 return -1;
392 if (len1 > len2)
393 return 1;
395 /* Compare stages */
396 flags1 &= CE_STAGEMASK;
397 flags2 &= CE_STAGEMASK;
399 if (flags1 < flags2)
400 return -1;
401 if (flags1 > flags2)
402 return 1;
403 return 0;
406 int index_name_pos(const struct index_state *istate, const char *name, int namelen)
408 int first, last;
410 first = 0;
411 last = istate->cache_nr;
412 while (last > first) {
413 int next = (last + first) >> 1;
414 struct cache_entry *ce = istate->cache[next];
415 int cmp = cache_name_compare(name, namelen, ce->name, ce->ce_flags);
416 if (!cmp)
417 return next;
418 if (cmp < 0) {
419 last = next;
420 continue;
422 first = next+1;
424 return -first-1;
427 /* Remove entry, return true if there are more entries to go.. */
428 int remove_index_entry_at(struct index_state *istate, int pos)
430 struct cache_entry *ce = istate->cache[pos];
432 remove_name_hash(ce);
433 istate->cache_changed = 1;
434 istate->cache_nr--;
435 if (pos >= istate->cache_nr)
436 return 0;
437 memmove(istate->cache + pos,
438 istate->cache + pos + 1,
439 (istate->cache_nr - pos) * sizeof(struct cache_entry *));
440 return 1;
443 int remove_file_from_index(struct index_state *istate, const char *path)
445 int pos = index_name_pos(istate, path, strlen(path));
446 if (pos < 0)
447 pos = -pos-1;
448 cache_tree_invalidate_path(istate->cache_tree, path);
449 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
450 remove_index_entry_at(istate, pos);
451 return 0;
454 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
456 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
459 static int index_name_pos_also_unmerged(struct index_state *istate,
460 const char *path, int namelen)
462 int pos = index_name_pos(istate, path, namelen);
463 struct cache_entry *ce;
465 if (pos >= 0)
466 return pos;
468 /* maybe unmerged? */
469 pos = -1 - pos;
470 if (pos >= istate->cache_nr ||
471 compare_name((ce = istate->cache[pos]), path, namelen))
472 return -1;
474 /* order of preference: stage 2, 1, 3 */
475 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
476 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
477 !compare_name(ce, path, namelen))
478 pos++;
479 return pos;
482 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
484 int len = ce_namelen(ce);
485 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
489 * If we add a filename that aliases in the cache, we will use the
490 * name that we already have - but we don't want to update the same
491 * alias twice, because that implies that there were actually two
492 * different files with aliasing names!
494 * So we use the CE_ADDED flag to verify that the alias was an old
495 * one before we accept it as
497 static struct cache_entry *create_alias_ce(struct cache_entry *ce, struct cache_entry *alias)
499 int len;
500 struct cache_entry *new;
502 if (alias->ce_flags & CE_ADDED)
503 die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
505 /* Ok, create the new entry using the name of the existing alias */
506 len = ce_namelen(alias);
507 new = xcalloc(1, cache_entry_size(len));
508 memcpy(new->name, alias->name, len);
509 copy_cache_entry(new, ce);
510 free(ce);
511 return new;
514 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
516 int size, namelen, was_same;
517 mode_t st_mode = st->st_mode;
518 struct cache_entry *ce, *alias;
519 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_RACY_IS_DIRTY;
520 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
521 int pretend = flags & ADD_CACHE_PRETEND;
523 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
524 return error("%s: can only add regular files, symbolic links or git-directories", path);
526 namelen = strlen(path);
527 if (S_ISDIR(st_mode)) {
528 while (namelen && path[namelen-1] == '/')
529 namelen--;
531 size = cache_entry_size(namelen);
532 ce = xcalloc(1, size);
533 memcpy(ce->name, path, namelen);
534 ce->ce_flags = namelen;
535 fill_stat_cache_info(ce, st);
537 if (trust_executable_bit && has_symlinks)
538 ce->ce_mode = create_ce_mode(st_mode);
539 else {
540 /* If there is an existing entry, pick the mode bits and type
541 * from it, otherwise assume unexecutable regular file.
543 struct cache_entry *ent;
544 int pos = index_name_pos_also_unmerged(istate, path, namelen);
546 ent = (0 <= pos) ? istate->cache[pos] : NULL;
547 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
550 alias = index_name_exists(istate, ce->name, ce_namelen(ce), ignore_case);
551 if (alias && !ce_stage(alias) && !ie_match_stat(istate, alias, st, ce_option)) {
552 /* Nothing changed, really */
553 free(ce);
554 ce_mark_uptodate(alias);
555 alias->ce_flags |= CE_ADDED;
556 return 0;
558 if (index_path(ce->sha1, path, st, 1))
559 return error("unable to index file %s", path);
560 if (ignore_case && alias && different_name(ce, alias))
561 ce = create_alias_ce(ce, alias);
562 ce->ce_flags |= CE_ADDED;
564 /* It was suspected to be racily clean, but it turns out to be Ok */
565 was_same = (alias &&
566 !ce_stage(alias) &&
567 !hashcmp(alias->sha1, ce->sha1) &&
568 ce->ce_mode == alias->ce_mode);
570 if (pretend)
572 else if (add_index_entry(istate, ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE))
573 return error("unable to add %s to index",path);
574 if (verbose && !was_same)
575 printf("add '%s'\n", path);
576 return 0;
579 int add_file_to_index(struct index_state *istate, const char *path, int flags)
581 struct stat st;
582 if (lstat(path, &st))
583 die("%s: unable to stat (%s)", path, strerror(errno));
584 return add_to_index(istate, path, &st, flags);
587 struct cache_entry *make_cache_entry(unsigned int mode,
588 const unsigned char *sha1, const char *path, int stage,
589 int refresh)
591 int size, len;
592 struct cache_entry *ce;
594 if (!verify_path(path))
595 return NULL;
597 len = strlen(path);
598 size = cache_entry_size(len);
599 ce = xcalloc(1, size);
601 hashcpy(ce->sha1, sha1);
602 memcpy(ce->name, path, len);
603 ce->ce_flags = create_ce_flags(len, stage);
604 ce->ce_mode = create_ce_mode(mode);
606 if (refresh)
607 return refresh_cache_entry(ce, 0);
609 return ce;
612 int ce_same_name(struct cache_entry *a, struct cache_entry *b)
614 int len = ce_namelen(a);
615 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
618 int ce_path_match(const struct cache_entry *ce, const char **pathspec)
620 const char *match, *name;
621 int len;
623 if (!pathspec)
624 return 1;
626 len = ce_namelen(ce);
627 name = ce->name;
628 while ((match = *pathspec++) != NULL) {
629 int matchlen = strlen(match);
630 if (matchlen > len)
631 continue;
632 if (memcmp(name, match, matchlen))
633 continue;
634 if (matchlen && name[matchlen-1] == '/')
635 return 1;
636 if (name[matchlen] == '/' || !name[matchlen])
637 return 1;
638 if (!matchlen)
639 return 1;
641 return 0;
645 * We fundamentally don't like some paths: we don't want
646 * dot or dot-dot anywhere, and for obvious reasons don't
647 * want to recurse into ".git" either.
649 * Also, we don't want double slashes or slashes at the
650 * end that can make pathnames ambiguous.
652 static int verify_dotfile(const char *rest)
655 * The first character was '.', but that
656 * has already been discarded, we now test
657 * the rest.
659 switch (*rest) {
660 /* "." is not allowed */
661 case '\0': case '/':
662 return 0;
665 * ".git" followed by NUL or slash is bad. This
666 * shares the path end test with the ".." case.
668 case 'g':
669 if (rest[1] != 'i')
670 break;
671 if (rest[2] != 't')
672 break;
673 rest += 2;
674 /* fallthrough */
675 case '.':
676 if (rest[1] == '\0' || rest[1] == '/')
677 return 0;
679 return 1;
682 int verify_path(const char *path)
684 char c;
686 goto inside;
687 for (;;) {
688 if (!c)
689 return 1;
690 if (c == '/') {
691 inside:
692 c = *path++;
693 switch (c) {
694 default:
695 continue;
696 case '/': case '\0':
697 break;
698 case '.':
699 if (verify_dotfile(path))
700 continue;
702 return 0;
704 c = *path++;
709 * Do we have another file that has the beginning components being a
710 * proper superset of the name we're trying to add?
712 static int has_file_name(struct index_state *istate,
713 const struct cache_entry *ce, int pos, int ok_to_replace)
715 int retval = 0;
716 int len = ce_namelen(ce);
717 int stage = ce_stage(ce);
718 const char *name = ce->name;
720 while (pos < istate->cache_nr) {
721 struct cache_entry *p = istate->cache[pos++];
723 if (len >= ce_namelen(p))
724 break;
725 if (memcmp(name, p->name, len))
726 break;
727 if (ce_stage(p) != stage)
728 continue;
729 if (p->name[len] != '/')
730 continue;
731 if (p->ce_flags & CE_REMOVE)
732 continue;
733 retval = -1;
734 if (!ok_to_replace)
735 break;
736 remove_index_entry_at(istate, --pos);
738 return retval;
742 * Do we have another file with a pathname that is a proper
743 * subset of the name we're trying to add?
745 static int has_dir_name(struct index_state *istate,
746 const struct cache_entry *ce, int pos, int ok_to_replace)
748 int retval = 0;
749 int stage = ce_stage(ce);
750 const char *name = ce->name;
751 const char *slash = name + ce_namelen(ce);
753 for (;;) {
754 int len;
756 for (;;) {
757 if (*--slash == '/')
758 break;
759 if (slash <= ce->name)
760 return retval;
762 len = slash - name;
764 pos = index_name_pos(istate, name, create_ce_flags(len, stage));
765 if (pos >= 0) {
767 * Found one, but not so fast. This could
768 * be a marker that says "I was here, but
769 * I am being removed". Such an entry is
770 * not a part of the resulting tree, and
771 * it is Ok to have a directory at the same
772 * path.
774 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
775 retval = -1;
776 if (!ok_to_replace)
777 break;
778 remove_index_entry_at(istate, pos);
779 continue;
782 else
783 pos = -pos-1;
786 * Trivial optimization: if we find an entry that
787 * already matches the sub-directory, then we know
788 * we're ok, and we can exit.
790 while (pos < istate->cache_nr) {
791 struct cache_entry *p = istate->cache[pos];
792 if ((ce_namelen(p) <= len) ||
793 (p->name[len] != '/') ||
794 memcmp(p->name, name, len))
795 break; /* not our subdirectory */
796 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
798 * p is at the same stage as our entry, and
799 * is a subdirectory of what we are looking
800 * at, so we cannot have conflicts at our
801 * level or anything shorter.
803 return retval;
804 pos++;
807 return retval;
810 /* We may be in a situation where we already have path/file and path
811 * is being added, or we already have path and path/file is being
812 * added. Either one would result in a nonsense tree that has path
813 * twice when git-write-tree tries to write it out. Prevent it.
815 * If ok-to-replace is specified, we remove the conflicting entries
816 * from the cache so the caller should recompute the insert position.
817 * When this happens, we return non-zero.
819 static int check_file_directory_conflict(struct index_state *istate,
820 const struct cache_entry *ce,
821 int pos, int ok_to_replace)
823 int retval;
826 * When ce is an "I am going away" entry, we allow it to be added
828 if (ce->ce_flags & CE_REMOVE)
829 return 0;
832 * We check if the path is a sub-path of a subsequent pathname
833 * first, since removing those will not change the position
834 * in the array.
836 retval = has_file_name(istate, ce, pos, ok_to_replace);
839 * Then check if the path might have a clashing sub-directory
840 * before it.
842 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
845 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
847 int pos;
848 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
849 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
850 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
852 cache_tree_invalidate_path(istate->cache_tree, ce->name);
853 pos = index_name_pos(istate, ce->name, ce->ce_flags);
855 /* existing match? Just replace it. */
856 if (pos >= 0) {
857 replace_index_entry(istate, pos, ce);
858 return 0;
860 pos = -pos-1;
863 * Inserting a merged entry ("stage 0") into the index
864 * will always replace all non-merged entries..
866 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
867 while (ce_same_name(istate->cache[pos], ce)) {
868 ok_to_add = 1;
869 if (!remove_index_entry_at(istate, pos))
870 break;
874 if (!ok_to_add)
875 return -1;
876 if (!verify_path(ce->name))
877 return -1;
879 if (!skip_df_check &&
880 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
881 if (!ok_to_replace)
882 return error("'%s' appears as both a file and as a directory",
883 ce->name);
884 pos = index_name_pos(istate, ce->name, ce->ce_flags);
885 pos = -pos-1;
887 return pos + 1;
890 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
892 int pos;
894 if (option & ADD_CACHE_JUST_APPEND)
895 pos = istate->cache_nr;
896 else {
897 int ret;
898 ret = add_index_entry_with_check(istate, ce, option);
899 if (ret <= 0)
900 return ret;
901 pos = ret - 1;
904 /* Make sure the array is big enough .. */
905 if (istate->cache_nr == istate->cache_alloc) {
906 istate->cache_alloc = alloc_nr(istate->cache_alloc);
907 istate->cache = xrealloc(istate->cache,
908 istate->cache_alloc * sizeof(struct cache_entry *));
911 /* Add it in.. */
912 istate->cache_nr++;
913 if (istate->cache_nr > pos + 1)
914 memmove(istate->cache + pos + 1,
915 istate->cache + pos,
916 (istate->cache_nr - pos - 1) * sizeof(ce));
917 set_index_entry(istate, pos, ce);
918 istate->cache_changed = 1;
919 return 0;
923 * "refresh" does not calculate a new sha1 file or bring the
924 * cache up-to-date for mode/content changes. But what it
925 * _does_ do is to "re-match" the stat information of a file
926 * with the cache, so that you can refresh the cache for a
927 * file that hasn't been changed but where the stat entry is
928 * out of date.
930 * For example, you'd want to do this after doing a "git-read-tree",
931 * to link up the stat cache details with the proper files.
933 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
934 struct cache_entry *ce,
935 unsigned int options, int *err)
937 struct stat st;
938 struct cache_entry *updated;
939 int changed, size;
940 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
942 if (ce_uptodate(ce))
943 return ce;
946 * CE_VALID means the user promised us that the change to
947 * the work tree does not matter and told us not to worry.
949 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
950 ce_mark_uptodate(ce);
951 return ce;
954 if (lstat(ce->name, &st) < 0) {
955 if (err)
956 *err = errno;
957 return NULL;
960 changed = ie_match_stat(istate, ce, &st, options);
961 if (!changed) {
963 * The path is unchanged. If we were told to ignore
964 * valid bit, then we did the actual stat check and
965 * found that the entry is unmodified. If the entry
966 * is not marked VALID, this is the place to mark it
967 * valid again, under "assume unchanged" mode.
969 if (ignore_valid && assume_unchanged &&
970 !(ce->ce_flags & CE_VALID))
971 ; /* mark this one VALID again */
972 else {
974 * We do not mark the index itself "modified"
975 * because CE_UPTODATE flag is in-core only;
976 * we are not going to write this change out.
978 ce_mark_uptodate(ce);
979 return ce;
983 if (ie_modified(istate, ce, &st, options)) {
984 if (err)
985 *err = EINVAL;
986 return NULL;
989 size = ce_size(ce);
990 updated = xmalloc(size);
991 memcpy(updated, ce, size);
992 fill_stat_cache_info(updated, &st);
994 * If ignore_valid is not set, we should leave CE_VALID bit
995 * alone. Otherwise, paths marked with --no-assume-unchanged
996 * (i.e. things to be edited) will reacquire CE_VALID bit
997 * automatically, which is not really what we want.
999 if (!ignore_valid && assume_unchanged &&
1000 !(ce->ce_flags & CE_VALID))
1001 updated->ce_flags &= ~CE_VALID;
1003 return updated;
1006 int refresh_index(struct index_state *istate, unsigned int flags, const char **pathspec, char *seen)
1008 int i;
1009 int has_errors = 0;
1010 int really = (flags & REFRESH_REALLY) != 0;
1011 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1012 int quiet = (flags & REFRESH_QUIET) != 0;
1013 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1014 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1015 unsigned int options = really ? CE_MATCH_IGNORE_VALID : 0;
1016 const char *needs_update_message;
1018 needs_update_message = ((flags & REFRESH_SAY_CHANGED)
1019 ? "locally modified" : "needs update");
1020 for (i = 0; i < istate->cache_nr; i++) {
1021 struct cache_entry *ce, *new;
1022 int cache_errno = 0;
1024 ce = istate->cache[i];
1025 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1026 continue;
1028 if (ce_stage(ce)) {
1029 while ((i < istate->cache_nr) &&
1030 ! strcmp(istate->cache[i]->name, ce->name))
1031 i++;
1032 i--;
1033 if (allow_unmerged)
1034 continue;
1035 printf("%s: needs merge\n", ce->name);
1036 has_errors = 1;
1037 continue;
1040 if (pathspec && !match_pathspec(pathspec, ce->name, strlen(ce->name), 0, seen))
1041 continue;
1043 new = refresh_cache_ent(istate, ce, options, &cache_errno);
1044 if (new == ce)
1045 continue;
1046 if (!new) {
1047 if (not_new && cache_errno == ENOENT)
1048 continue;
1049 if (really && cache_errno == EINVAL) {
1050 /* If we are doing --really-refresh that
1051 * means the index is not valid anymore.
1053 ce->ce_flags &= ~CE_VALID;
1054 istate->cache_changed = 1;
1056 if (quiet)
1057 continue;
1058 printf("%s: %s\n", ce->name, needs_update_message);
1059 has_errors = 1;
1060 continue;
1063 replace_index_entry(istate, i, new);
1065 return has_errors;
1068 struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
1070 return refresh_cache_ent(&the_index, ce, really, NULL);
1073 static int verify_hdr(struct cache_header *hdr, unsigned long size)
1075 SHA_CTX c;
1076 unsigned char sha1[20];
1078 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1079 return error("bad signature");
1080 if (hdr->hdr_version != htonl(2))
1081 return error("bad index version");
1082 SHA1_Init(&c);
1083 SHA1_Update(&c, hdr, size - 20);
1084 SHA1_Final(sha1, &c);
1085 if (hashcmp(sha1, (unsigned char *)hdr + size - 20))
1086 return error("bad index file sha1 signature");
1087 return 0;
1090 static int read_index_extension(struct index_state *istate,
1091 const char *ext, void *data, unsigned long sz)
1093 switch (CACHE_EXT(ext)) {
1094 case CACHE_EXT_TREE:
1095 istate->cache_tree = cache_tree_read(data, sz);
1096 break;
1097 default:
1098 if (*ext < 'A' || 'Z' < *ext)
1099 return error("index uses %.4s extension, which we do not understand",
1100 ext);
1101 fprintf(stderr, "ignoring %.4s extension\n", ext);
1102 break;
1104 return 0;
1107 int read_index(struct index_state *istate)
1109 return read_index_from(istate, get_index_file());
1112 static void convert_from_disk(struct ondisk_cache_entry *ondisk, struct cache_entry *ce)
1114 size_t len;
1116 ce->ce_ctime = ntohl(ondisk->ctime.sec);
1117 ce->ce_mtime = ntohl(ondisk->mtime.sec);
1118 ce->ce_dev = ntohl(ondisk->dev);
1119 ce->ce_ino = ntohl(ondisk->ino);
1120 ce->ce_mode = ntohl(ondisk->mode);
1121 ce->ce_uid = ntohl(ondisk->uid);
1122 ce->ce_gid = ntohl(ondisk->gid);
1123 ce->ce_size = ntohl(ondisk->size);
1124 /* On-disk flags are just 16 bits */
1125 ce->ce_flags = ntohs(ondisk->flags);
1126 hashcpy(ce->sha1, ondisk->sha1);
1128 len = ce->ce_flags & CE_NAMEMASK;
1129 if (len == CE_NAMEMASK)
1130 len = strlen(ondisk->name);
1132 * NEEDSWORK: If the original index is crafted, this copy could
1133 * go unchecked.
1135 memcpy(ce->name, ondisk->name, len + 1);
1138 static inline size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1140 long per_entry;
1142 per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1145 * Alignment can cause differences. This should be "alignof", but
1146 * since that's a gcc'ism, just use the size of a pointer.
1148 per_entry += sizeof(void *);
1149 return ondisk_size + entries*per_entry;
1152 /* remember to discard_cache() before reading a different cache! */
1153 int read_index_from(struct index_state *istate, const char *path)
1155 int fd, i;
1156 struct stat st;
1157 unsigned long src_offset, dst_offset;
1158 struct cache_header *hdr;
1159 void *mmap;
1160 size_t mmap_size;
1162 errno = EBUSY;
1163 if (istate->alloc)
1164 return istate->cache_nr;
1166 errno = ENOENT;
1167 istate->timestamp = 0;
1168 fd = open(path, O_RDONLY);
1169 if (fd < 0) {
1170 if (errno == ENOENT)
1171 return 0;
1172 die("index file open failed (%s)", strerror(errno));
1175 if (fstat(fd, &st))
1176 die("cannot stat the open index (%s)", strerror(errno));
1178 errno = EINVAL;
1179 mmap_size = xsize_t(st.st_size);
1180 if (mmap_size < sizeof(struct cache_header) + 20)
1181 die("index file smaller than expected");
1183 mmap = xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
1184 close(fd);
1185 if (mmap == MAP_FAILED)
1186 die("unable to map index file");
1188 hdr = mmap;
1189 if (verify_hdr(hdr, mmap_size) < 0)
1190 goto unmap;
1192 istate->cache_nr = ntohl(hdr->hdr_entries);
1193 istate->cache_alloc = alloc_nr(istate->cache_nr);
1194 istate->cache = xcalloc(istate->cache_alloc, sizeof(struct cache_entry *));
1197 * The disk format is actually larger than the in-memory format,
1198 * due to space for nsec etc, so even though the in-memory one
1199 * has room for a few more flags, we can allocate using the same
1200 * index size
1202 istate->alloc = xmalloc(estimate_cache_size(mmap_size, istate->cache_nr));
1204 src_offset = sizeof(*hdr);
1205 dst_offset = 0;
1206 for (i = 0; i < istate->cache_nr; i++) {
1207 struct ondisk_cache_entry *disk_ce;
1208 struct cache_entry *ce;
1210 disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
1211 ce = (struct cache_entry *)((char *)istate->alloc + dst_offset);
1212 convert_from_disk(disk_ce, ce);
1213 set_index_entry(istate, i, ce);
1215 src_offset += ondisk_ce_size(ce);
1216 dst_offset += ce_size(ce);
1218 istate->timestamp = st.st_mtime;
1219 while (src_offset <= mmap_size - 20 - 8) {
1220 /* After an array of active_nr index entries,
1221 * there can be arbitrary number of extended
1222 * sections, each of which is prefixed with
1223 * extension name (4-byte) and section length
1224 * in 4-byte network byte order.
1226 unsigned long extsize;
1227 memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
1228 extsize = ntohl(extsize);
1229 if (read_index_extension(istate,
1230 (const char *) mmap + src_offset,
1231 (char *) mmap + src_offset + 8,
1232 extsize) < 0)
1233 goto unmap;
1234 src_offset += 8;
1235 src_offset += extsize;
1237 munmap(mmap, mmap_size);
1238 return istate->cache_nr;
1240 unmap:
1241 munmap(mmap, mmap_size);
1242 errno = EINVAL;
1243 die("index file corrupt");
1246 int discard_index(struct index_state *istate)
1248 istate->cache_nr = 0;
1249 istate->cache_changed = 0;
1250 istate->timestamp = 0;
1251 free_hash(&istate->name_hash);
1252 cache_tree_free(&(istate->cache_tree));
1253 free(istate->alloc);
1254 istate->alloc = NULL;
1256 /* no need to throw away allocated active_cache */
1257 return 0;
1260 int unmerged_index(const struct index_state *istate)
1262 int i;
1263 for (i = 0; i < istate->cache_nr; i++) {
1264 if (ce_stage(istate->cache[i]))
1265 return 1;
1267 return 0;
1270 #define WRITE_BUFFER_SIZE 8192
1271 static unsigned char write_buffer[WRITE_BUFFER_SIZE];
1272 static unsigned long write_buffer_len;
1274 static int ce_write_flush(SHA_CTX *context, int fd)
1276 unsigned int buffered = write_buffer_len;
1277 if (buffered) {
1278 SHA1_Update(context, write_buffer, buffered);
1279 if (write_in_full(fd, write_buffer, buffered) != buffered)
1280 return -1;
1281 write_buffer_len = 0;
1283 return 0;
1286 static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
1288 while (len) {
1289 unsigned int buffered = write_buffer_len;
1290 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
1291 if (partial > len)
1292 partial = len;
1293 memcpy(write_buffer + buffered, data, partial);
1294 buffered += partial;
1295 if (buffered == WRITE_BUFFER_SIZE) {
1296 write_buffer_len = buffered;
1297 if (ce_write_flush(context, fd))
1298 return -1;
1299 buffered = 0;
1301 write_buffer_len = buffered;
1302 len -= partial;
1303 data = (char *) data + partial;
1305 return 0;
1308 static int write_index_ext_header(SHA_CTX *context, int fd,
1309 unsigned int ext, unsigned int sz)
1311 ext = htonl(ext);
1312 sz = htonl(sz);
1313 return ((ce_write(context, fd, &ext, 4) < 0) ||
1314 (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
1317 static int ce_flush(SHA_CTX *context, int fd)
1319 unsigned int left = write_buffer_len;
1321 if (left) {
1322 write_buffer_len = 0;
1323 SHA1_Update(context, write_buffer, left);
1326 /* Flush first if not enough space for SHA1 signature */
1327 if (left + 20 > WRITE_BUFFER_SIZE) {
1328 if (write_in_full(fd, write_buffer, left) != left)
1329 return -1;
1330 left = 0;
1333 /* Append the SHA1 signature at the end */
1334 SHA1_Final(write_buffer + left, context);
1335 left += 20;
1336 return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0;
1339 static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
1342 * The only thing we care about in this function is to smudge the
1343 * falsely clean entry due to touch-update-touch race, so we leave
1344 * everything else as they are. We are called for entries whose
1345 * ce_mtime match the index file mtime.
1347 * Note that this actually does not do much for gitlinks, for
1348 * which ce_match_stat_basic() always goes to the actual
1349 * contents. The caller checks with is_racy_timestamp() which
1350 * always says "no" for gitlinks, so we are not called for them ;-)
1352 struct stat st;
1354 if (lstat(ce->name, &st) < 0)
1355 return;
1356 if (ce_match_stat_basic(ce, &st))
1357 return;
1358 if (ce_modified_check_fs(ce, &st)) {
1359 /* This is "racily clean"; smudge it. Note that this
1360 * is a tricky code. At first glance, it may appear
1361 * that it can break with this sequence:
1363 * $ echo xyzzy >frotz
1364 * $ git-update-index --add frotz
1365 * $ : >frotz
1366 * $ sleep 3
1367 * $ echo filfre >nitfol
1368 * $ git-update-index --add nitfol
1370 * but it does not. When the second update-index runs,
1371 * it notices that the entry "frotz" has the same timestamp
1372 * as index, and if we were to smudge it by resetting its
1373 * size to zero here, then the object name recorded
1374 * in index is the 6-byte file but the cached stat information
1375 * becomes zero --- which would then match what we would
1376 * obtain from the filesystem next time we stat("frotz").
1378 * However, the second update-index, before calling
1379 * this function, notices that the cached size is 6
1380 * bytes and what is on the filesystem is an empty
1381 * file, and never calls us, so the cached size information
1382 * for "frotz" stays 6 which does not match the filesystem.
1384 ce->ce_size = 0;
1388 static int ce_write_entry(SHA_CTX *c, int fd, struct cache_entry *ce)
1390 int size = ondisk_ce_size(ce);
1391 struct ondisk_cache_entry *ondisk = xcalloc(1, size);
1393 ondisk->ctime.sec = htonl(ce->ce_ctime);
1394 ondisk->ctime.nsec = 0;
1395 ondisk->mtime.sec = htonl(ce->ce_mtime);
1396 ondisk->mtime.nsec = 0;
1397 ondisk->dev = htonl(ce->ce_dev);
1398 ondisk->ino = htonl(ce->ce_ino);
1399 ondisk->mode = htonl(ce->ce_mode);
1400 ondisk->uid = htonl(ce->ce_uid);
1401 ondisk->gid = htonl(ce->ce_gid);
1402 ondisk->size = htonl(ce->ce_size);
1403 hashcpy(ondisk->sha1, ce->sha1);
1404 ondisk->flags = htons(ce->ce_flags);
1405 memcpy(ondisk->name, ce->name, ce_namelen(ce));
1407 return ce_write(c, fd, ondisk, size);
1410 int write_index(const struct index_state *istate, int newfd)
1412 SHA_CTX c;
1413 struct cache_header hdr;
1414 int i, err, removed;
1415 struct cache_entry **cache = istate->cache;
1416 int entries = istate->cache_nr;
1418 for (i = removed = 0; i < entries; i++)
1419 if (cache[i]->ce_flags & CE_REMOVE)
1420 removed++;
1422 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
1423 hdr.hdr_version = htonl(2);
1424 hdr.hdr_entries = htonl(entries - removed);
1426 SHA1_Init(&c);
1427 if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
1428 return -1;
1430 for (i = 0; i < entries; i++) {
1431 struct cache_entry *ce = cache[i];
1432 if (ce->ce_flags & CE_REMOVE)
1433 continue;
1434 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
1435 ce_smudge_racily_clean_entry(ce);
1436 if (ce_write_entry(&c, newfd, ce) < 0)
1437 return -1;
1440 /* Write extension data here */
1441 if (istate->cache_tree) {
1442 struct strbuf sb;
1444 strbuf_init(&sb, 0);
1445 cache_tree_write(&sb, istate->cache_tree);
1446 err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
1447 || ce_write(&c, newfd, sb.buf, sb.len) < 0;
1448 strbuf_release(&sb);
1449 if (err)
1450 return -1;
1452 return ce_flush(&c, newfd);
1456 * Read the index file that is potentially unmerged into given
1457 * index_state, dropping any unmerged entries. Returns true is
1458 * the index is unmerged. Callers who want to refuse to work
1459 * from an unmerged state can call this and check its return value,
1460 * instead of calling read_cache().
1462 int read_index_unmerged(struct index_state *istate)
1464 int i;
1465 struct cache_entry **dst;
1466 struct cache_entry *last = NULL;
1468 read_index(istate);
1469 dst = istate->cache;
1470 for (i = 0; i < istate->cache_nr; i++) {
1471 struct cache_entry *ce = istate->cache[i];
1472 if (ce_stage(ce)) {
1473 remove_name_hash(ce);
1474 if (last && !strcmp(ce->name, last->name))
1475 continue;
1476 cache_tree_invalidate_path(istate->cache_tree, ce->name);
1477 last = ce;
1478 continue;
1480 *dst++ = ce;
1482 istate->cache_nr = dst - istate->cache;
1483 return !!last;
1486 struct update_callback_data
1488 int flags;
1489 int add_errors;
1492 static void update_callback(struct diff_queue_struct *q,
1493 struct diff_options *opt, void *cbdata)
1495 int i;
1496 struct update_callback_data *data = cbdata;
1498 for (i = 0; i < q->nr; i++) {
1499 struct diff_filepair *p = q->queue[i];
1500 const char *path = p->one->path;
1501 switch (p->status) {
1502 default:
1503 die("unexpected diff status %c", p->status);
1504 case DIFF_STATUS_UNMERGED:
1505 case DIFF_STATUS_MODIFIED:
1506 case DIFF_STATUS_TYPE_CHANGED:
1507 if (add_file_to_index(&the_index, path, data->flags)) {
1508 if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
1509 die("updating files failed");
1510 data->add_errors++;
1512 break;
1513 case DIFF_STATUS_DELETED:
1514 if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
1515 break;
1516 if (!(data->flags & ADD_CACHE_PRETEND))
1517 remove_file_from_index(&the_index, path);
1518 if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
1519 printf("remove '%s'\n", path);
1520 break;
1525 int add_files_to_cache(const char *prefix, const char **pathspec, int flags)
1527 struct update_callback_data data;
1528 struct rev_info rev;
1529 init_revisions(&rev, prefix);
1530 setup_revisions(0, NULL, &rev, NULL);
1531 rev.prune_data = pathspec;
1532 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1533 rev.diffopt.format_callback = update_callback;
1534 data.flags = flags;
1535 data.add_errors = 0;
1536 rev.diffopt.format_callback_data = &data;
1537 run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
1538 return !!data.add_errors;