symlinks.c: remove unused functions
[git/git-svn.git] / read-cache.c
blob9f4f44cb62567375ca1169acbc0542d4463793d4
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"
16 #include "blob.h"
18 static struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really);
20 /* Index extensions.
22 * The first letter should be 'A'..'Z' for extensions that are not
23 * necessary for a correct operation (i.e. optimization data).
24 * When new extensions are added that _needs_ to be understood in
25 * order to correctly interpret the index file, pick character that
26 * is outside the range, to cause the reader to abort.
29 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
30 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
32 struct index_state the_index;
34 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
36 istate->cache[nr] = ce;
37 add_name_hash(istate, ce);
40 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
42 struct cache_entry *old = istate->cache[nr];
44 remove_name_hash(old);
45 set_index_entry(istate, nr, ce);
46 istate->cache_changed = 1;
49 void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
51 struct cache_entry *old = istate->cache[nr], *new;
52 int namelen = strlen(new_name);
54 new = xmalloc(cache_entry_size(namelen));
55 copy_cache_entry(new, old);
56 new->ce_flags &= ~(CE_STATE_MASK | CE_NAMEMASK);
57 new->ce_flags |= (namelen >= CE_NAMEMASK ? CE_NAMEMASK : namelen);
58 memcpy(new->name, new_name, namelen + 1);
60 cache_tree_invalidate_path(istate->cache_tree, old->name);
61 remove_index_entry_at(istate, nr);
62 add_index_entry(istate, new, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
66 * This only updates the "non-critical" parts of the directory
67 * cache, ie the parts that aren't tracked by GIT, and only used
68 * to validate the cache.
70 void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
72 ce->ce_ctime.sec = (unsigned int)st->st_ctime;
73 ce->ce_mtime.sec = (unsigned int)st->st_mtime;
74 ce->ce_ctime.nsec = ST_CTIME_NSEC(*st);
75 ce->ce_mtime.nsec = ST_MTIME_NSEC(*st);
76 ce->ce_dev = st->st_dev;
77 ce->ce_ino = st->st_ino;
78 ce->ce_uid = st->st_uid;
79 ce->ce_gid = st->st_gid;
80 ce->ce_size = st->st_size;
82 if (assume_unchanged)
83 ce->ce_flags |= CE_VALID;
85 if (S_ISREG(st->st_mode))
86 ce_mark_uptodate(ce);
89 static int ce_compare_data(struct cache_entry *ce, struct stat *st)
91 int match = -1;
92 int fd = open(ce->name, O_RDONLY);
94 if (fd >= 0) {
95 unsigned char sha1[20];
96 if (!index_fd(sha1, fd, st, 0, OBJ_BLOB, ce->name))
97 match = hashcmp(sha1, ce->sha1);
98 /* index_fd() closed the file descriptor already */
100 return match;
103 static int ce_compare_link(struct cache_entry *ce, size_t expected_size)
105 int match = -1;
106 void *buffer;
107 unsigned long size;
108 enum object_type type;
109 struct strbuf sb = STRBUF_INIT;
111 if (strbuf_readlink(&sb, ce->name, expected_size))
112 return -1;
114 buffer = read_sha1_file(ce->sha1, &type, &size);
115 if (buffer) {
116 if (size == sb.len)
117 match = memcmp(buffer, sb.buf, size);
118 free(buffer);
120 strbuf_release(&sb);
121 return match;
124 static int ce_compare_gitlink(struct cache_entry *ce)
126 unsigned char sha1[20];
129 * We don't actually require that the .git directory
130 * under GITLINK directory be a valid git directory. It
131 * might even be missing (in case nobody populated that
132 * sub-project).
134 * If so, we consider it always to match.
136 if (resolve_gitlink_ref(ce->name, "HEAD", sha1) < 0)
137 return 0;
138 return hashcmp(sha1, ce->sha1);
141 static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
143 switch (st->st_mode & S_IFMT) {
144 case S_IFREG:
145 if (ce_compare_data(ce, st))
146 return DATA_CHANGED;
147 break;
148 case S_IFLNK:
149 if (ce_compare_link(ce, xsize_t(st->st_size)))
150 return DATA_CHANGED;
151 break;
152 case S_IFDIR:
153 if (S_ISGITLINK(ce->ce_mode))
154 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
155 default:
156 return TYPE_CHANGED;
158 return 0;
161 static int is_empty_blob_sha1(const unsigned char *sha1)
163 static const unsigned char empty_blob_sha1[20] = {
164 0xe6,0x9d,0xe2,0x9b,0xb2,0xd1,0xd6,0x43,0x4b,0x8b,
165 0x29,0xae,0x77,0x5a,0xd8,0xc2,0xe4,0x8c,0x53,0x91
168 return !hashcmp(sha1, empty_blob_sha1);
171 static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
173 unsigned int changed = 0;
175 if (ce->ce_flags & CE_REMOVE)
176 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
178 switch (ce->ce_mode & S_IFMT) {
179 case S_IFREG:
180 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
181 /* We consider only the owner x bit to be relevant for
182 * "mode changes"
184 if (trust_executable_bit &&
185 (0100 & (ce->ce_mode ^ st->st_mode)))
186 changed |= MODE_CHANGED;
187 break;
188 case S_IFLNK:
189 if (!S_ISLNK(st->st_mode) &&
190 (has_symlinks || !S_ISREG(st->st_mode)))
191 changed |= TYPE_CHANGED;
192 break;
193 case S_IFGITLINK:
194 /* We ignore most of the st_xxx fields for gitlinks */
195 if (!S_ISDIR(st->st_mode))
196 changed |= TYPE_CHANGED;
197 else if (ce_compare_gitlink(ce))
198 changed |= DATA_CHANGED;
199 return changed;
200 default:
201 die("internal error: ce_mode is %o", ce->ce_mode);
203 if (ce->ce_mtime.sec != (unsigned int)st->st_mtime)
204 changed |= MTIME_CHANGED;
205 if (trust_ctime && ce->ce_ctime.sec != (unsigned int)st->st_ctime)
206 changed |= CTIME_CHANGED;
208 #ifdef USE_NSEC
209 if (ce->ce_mtime.nsec != ST_MTIME_NSEC(*st))
210 changed |= MTIME_CHANGED;
211 if (trust_ctime && ce->ce_ctime.nsec != ST_CTIME_NSEC(*st))
212 changed |= CTIME_CHANGED;
213 #endif
215 if (ce->ce_uid != (unsigned int) st->st_uid ||
216 ce->ce_gid != (unsigned int) st->st_gid)
217 changed |= OWNER_CHANGED;
218 if (ce->ce_ino != (unsigned int) st->st_ino)
219 changed |= INODE_CHANGED;
221 #ifdef USE_STDEV
223 * st_dev breaks on network filesystems where different
224 * clients will have different views of what "device"
225 * the filesystem is on
227 if (ce->ce_dev != (unsigned int) st->st_dev)
228 changed |= INODE_CHANGED;
229 #endif
231 if (ce->ce_size != (unsigned int) st->st_size)
232 changed |= DATA_CHANGED;
234 /* Racily smudged entry? */
235 if (!ce->ce_size) {
236 if (!is_empty_blob_sha1(ce->sha1))
237 changed |= DATA_CHANGED;
240 return changed;
243 static int is_racy_timestamp(const struct index_state *istate, struct cache_entry *ce)
245 return (!S_ISGITLINK(ce->ce_mode) &&
246 istate->timestamp.sec &&
247 #ifdef USE_NSEC
248 /* nanosecond timestamped files can also be racy! */
249 (istate->timestamp.sec < ce->ce_mtime.sec ||
250 (istate->timestamp.sec == ce->ce_mtime.sec &&
251 istate->timestamp.nsec <= ce->ce_mtime.nsec))
252 #else
253 istate->timestamp.sec <= ce->ce_mtime.sec
254 #endif
258 int ie_match_stat(const struct index_state *istate,
259 struct cache_entry *ce, struct stat *st,
260 unsigned int options)
262 unsigned int changed;
263 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
264 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
267 * If it's marked as always valid in the index, it's
268 * valid whatever the checked-out copy says.
270 if (!ignore_valid && (ce->ce_flags & CE_VALID))
271 return 0;
274 * Intent-to-add entries have not been added, so the index entry
275 * by definition never matches what is in the work tree until it
276 * actually gets added.
278 if (ce->ce_flags & CE_INTENT_TO_ADD)
279 return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
281 changed = ce_match_stat_basic(ce, st);
284 * Within 1 second of this sequence:
285 * echo xyzzy >file && git-update-index --add file
286 * running this command:
287 * echo frotz >file
288 * would give a falsely clean cache entry. The mtime and
289 * length match the cache, and other stat fields do not change.
291 * We could detect this at update-index time (the cache entry
292 * being registered/updated records the same time as "now")
293 * and delay the return from git-update-index, but that would
294 * effectively mean we can make at most one commit per second,
295 * which is not acceptable. Instead, we check cache entries
296 * whose mtime are the same as the index file timestamp more
297 * carefully than others.
299 if (!changed && is_racy_timestamp(istate, ce)) {
300 if (assume_racy_is_modified)
301 changed |= DATA_CHANGED;
302 else
303 changed |= ce_modified_check_fs(ce, st);
306 return changed;
309 int ie_modified(const struct index_state *istate,
310 struct cache_entry *ce, struct stat *st, unsigned int options)
312 int changed, changed_fs;
314 changed = ie_match_stat(istate, ce, st, options);
315 if (!changed)
316 return 0;
318 * If the mode or type has changed, there's no point in trying
319 * to refresh the entry - it's not going to match
321 if (changed & (MODE_CHANGED | TYPE_CHANGED))
322 return changed;
325 * Immediately after read-tree or update-index --cacheinfo,
326 * the length field is zero, as we have never even read the
327 * lstat(2) information once, and we cannot trust DATA_CHANGED
328 * returned by ie_match_stat() which in turn was returned by
329 * ce_match_stat_basic() to signal that the filesize of the
330 * blob changed. We have to actually go to the filesystem to
331 * see if the contents match, and if so, should answer "unchanged".
333 * The logic does not apply to gitlinks, as ce_match_stat_basic()
334 * already has checked the actual HEAD from the filesystem in the
335 * subproject. If ie_match_stat() already said it is different,
336 * then we know it is.
338 if ((changed & DATA_CHANGED) &&
339 (S_ISGITLINK(ce->ce_mode) || ce->ce_size != 0))
340 return changed;
342 changed_fs = ce_modified_check_fs(ce, st);
343 if (changed_fs)
344 return changed | changed_fs;
345 return 0;
348 int base_name_compare(const char *name1, int len1, int mode1,
349 const char *name2, int len2, int mode2)
351 unsigned char c1, c2;
352 int len = len1 < len2 ? len1 : len2;
353 int cmp;
355 cmp = memcmp(name1, name2, len);
356 if (cmp)
357 return cmp;
358 c1 = name1[len];
359 c2 = name2[len];
360 if (!c1 && S_ISDIR(mode1))
361 c1 = '/';
362 if (!c2 && S_ISDIR(mode2))
363 c2 = '/';
364 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
368 * df_name_compare() is identical to base_name_compare(), except it
369 * compares conflicting directory/file entries as equal. Note that
370 * while a directory name compares as equal to a regular file, they
371 * then individually compare _differently_ to a filename that has
372 * a dot after the basename (because '\0' < '.' < '/').
374 * This is used by routines that want to traverse the git namespace
375 * but then handle conflicting entries together when possible.
377 int df_name_compare(const char *name1, int len1, int mode1,
378 const char *name2, int len2, int mode2)
380 int len = len1 < len2 ? len1 : len2, cmp;
381 unsigned char c1, c2;
383 cmp = memcmp(name1, name2, len);
384 if (cmp)
385 return cmp;
386 /* Directories and files compare equal (same length, same name) */
387 if (len1 == len2)
388 return 0;
389 c1 = name1[len];
390 if (!c1 && S_ISDIR(mode1))
391 c1 = '/';
392 c2 = name2[len];
393 if (!c2 && S_ISDIR(mode2))
394 c2 = '/';
395 if (c1 == '/' && !c2)
396 return 0;
397 if (c2 == '/' && !c1)
398 return 0;
399 return c1 - c2;
402 int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
404 int len1 = flags1 & CE_NAMEMASK;
405 int len2 = flags2 & CE_NAMEMASK;
406 int len = len1 < len2 ? len1 : len2;
407 int cmp;
409 cmp = memcmp(name1, name2, len);
410 if (cmp)
411 return cmp;
412 if (len1 < len2)
413 return -1;
414 if (len1 > len2)
415 return 1;
417 /* Compare stages */
418 flags1 &= CE_STAGEMASK;
419 flags2 &= CE_STAGEMASK;
421 if (flags1 < flags2)
422 return -1;
423 if (flags1 > flags2)
424 return 1;
425 return 0;
428 int index_name_pos(const struct index_state *istate, const char *name, int namelen)
430 int first, last;
432 first = 0;
433 last = istate->cache_nr;
434 while (last > first) {
435 int next = (last + first) >> 1;
436 struct cache_entry *ce = istate->cache[next];
437 int cmp = cache_name_compare(name, namelen, ce->name, ce->ce_flags);
438 if (!cmp)
439 return next;
440 if (cmp < 0) {
441 last = next;
442 continue;
444 first = next+1;
446 return -first-1;
449 /* Remove entry, return true if there are more entries to go.. */
450 int remove_index_entry_at(struct index_state *istate, int pos)
452 struct cache_entry *ce = istate->cache[pos];
454 remove_name_hash(ce);
455 istate->cache_changed = 1;
456 istate->cache_nr--;
457 if (pos >= istate->cache_nr)
458 return 0;
459 memmove(istate->cache + pos,
460 istate->cache + pos + 1,
461 (istate->cache_nr - pos) * sizeof(struct cache_entry *));
462 return 1;
466 * Remove all cache ententries marked for removal, that is where
467 * CE_REMOVE is set in ce_flags. This is much more effective than
468 * calling remove_index_entry_at() for each entry to be removed.
470 void remove_marked_cache_entries(struct index_state *istate)
472 struct cache_entry **ce_array = istate->cache;
473 unsigned int i, j;
475 for (i = j = 0; i < istate->cache_nr; i++) {
476 if (ce_array[i]->ce_flags & CE_REMOVE)
477 remove_name_hash(ce_array[i]);
478 else
479 ce_array[j++] = ce_array[i];
481 istate->cache_changed = 1;
482 istate->cache_nr = j;
485 int remove_file_from_index(struct index_state *istate, const char *path)
487 int pos = index_name_pos(istate, path, strlen(path));
488 if (pos < 0)
489 pos = -pos-1;
490 cache_tree_invalidate_path(istate->cache_tree, path);
491 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
492 remove_index_entry_at(istate, pos);
493 return 0;
496 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
498 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
501 static int index_name_pos_also_unmerged(struct index_state *istate,
502 const char *path, int namelen)
504 int pos = index_name_pos(istate, path, namelen);
505 struct cache_entry *ce;
507 if (pos >= 0)
508 return pos;
510 /* maybe unmerged? */
511 pos = -1 - pos;
512 if (pos >= istate->cache_nr ||
513 compare_name((ce = istate->cache[pos]), path, namelen))
514 return -1;
516 /* order of preference: stage 2, 1, 3 */
517 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
518 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
519 !compare_name(ce, path, namelen))
520 pos++;
521 return pos;
524 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
526 int len = ce_namelen(ce);
527 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
531 * If we add a filename that aliases in the cache, we will use the
532 * name that we already have - but we don't want to update the same
533 * alias twice, because that implies that there were actually two
534 * different files with aliasing names!
536 * So we use the CE_ADDED flag to verify that the alias was an old
537 * one before we accept it as
539 static struct cache_entry *create_alias_ce(struct cache_entry *ce, struct cache_entry *alias)
541 int len;
542 struct cache_entry *new;
544 if (alias->ce_flags & CE_ADDED)
545 die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
547 /* Ok, create the new entry using the name of the existing alias */
548 len = ce_namelen(alias);
549 new = xcalloc(1, cache_entry_size(len));
550 memcpy(new->name, alias->name, len);
551 copy_cache_entry(new, ce);
552 free(ce);
553 return new;
556 static void record_intent_to_add(struct cache_entry *ce)
558 unsigned char sha1[20];
559 if (write_sha1_file("", 0, blob_type, sha1))
560 die("cannot create an empty blob in the object database");
561 hashcpy(ce->sha1, sha1);
564 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
566 int size, namelen, was_same;
567 mode_t st_mode = st->st_mode;
568 struct cache_entry *ce, *alias;
569 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_RACY_IS_DIRTY;
570 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
571 int pretend = flags & ADD_CACHE_PRETEND;
572 int intent_only = flags & ADD_CACHE_INTENT;
573 int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
574 (intent_only ? ADD_CACHE_NEW_ONLY : 0));
576 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
577 return error("%s: can only add regular files, symbolic links or git-directories", path);
579 namelen = strlen(path);
580 if (S_ISDIR(st_mode)) {
581 while (namelen && path[namelen-1] == '/')
582 namelen--;
584 size = cache_entry_size(namelen);
585 ce = xcalloc(1, size);
586 memcpy(ce->name, path, namelen);
587 ce->ce_flags = namelen;
588 if (!intent_only)
589 fill_stat_cache_info(ce, st);
590 else
591 ce->ce_flags |= CE_INTENT_TO_ADD;
593 if (trust_executable_bit && has_symlinks)
594 ce->ce_mode = create_ce_mode(st_mode);
595 else {
596 /* If there is an existing entry, pick the mode bits and type
597 * from it, otherwise assume unexecutable regular file.
599 struct cache_entry *ent;
600 int pos = index_name_pos_also_unmerged(istate, path, namelen);
602 ent = (0 <= pos) ? istate->cache[pos] : NULL;
603 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
606 alias = index_name_exists(istate, ce->name, ce_namelen(ce), ignore_case);
607 if (alias && !ce_stage(alias) && !ie_match_stat(istate, alias, st, ce_option)) {
608 /* Nothing changed, really */
609 free(ce);
610 ce_mark_uptodate(alias);
611 alias->ce_flags |= CE_ADDED;
612 return 0;
614 if (!intent_only) {
615 if (index_path(ce->sha1, path, st, 1))
616 return error("unable to index file %s", path);
617 } else
618 record_intent_to_add(ce);
620 if (ignore_case && alias && different_name(ce, alias))
621 ce = create_alias_ce(ce, alias);
622 ce->ce_flags |= CE_ADDED;
624 /* It was suspected to be racily clean, but it turns out to be Ok */
625 was_same = (alias &&
626 !ce_stage(alias) &&
627 !hashcmp(alias->sha1, ce->sha1) &&
628 ce->ce_mode == alias->ce_mode);
630 if (pretend)
632 else if (add_index_entry(istate, ce, add_option))
633 return error("unable to add %s to index",path);
634 if (verbose && !was_same)
635 printf("add '%s'\n", path);
636 return 0;
639 int add_file_to_index(struct index_state *istate, const char *path, int flags)
641 struct stat st;
642 if (lstat(path, &st))
643 die_errno("unable to stat '%s'", path);
644 return add_to_index(istate, path, &st, flags);
647 struct cache_entry *make_cache_entry(unsigned int mode,
648 const unsigned char *sha1, const char *path, int stage,
649 int refresh)
651 int size, len;
652 struct cache_entry *ce;
654 if (!verify_path(path)) {
655 error("Invalid path '%s'", path);
656 return NULL;
659 len = strlen(path);
660 size = cache_entry_size(len);
661 ce = xcalloc(1, size);
663 hashcpy(ce->sha1, sha1);
664 memcpy(ce->name, path, len);
665 ce->ce_flags = create_ce_flags(len, stage);
666 ce->ce_mode = create_ce_mode(mode);
668 if (refresh)
669 return refresh_cache_entry(ce, 0);
671 return ce;
674 int ce_same_name(struct cache_entry *a, struct cache_entry *b)
676 int len = ce_namelen(a);
677 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
680 int ce_path_match(const struct cache_entry *ce, const char **pathspec)
682 const char *match, *name;
683 int len;
685 if (!pathspec)
686 return 1;
688 len = ce_namelen(ce);
689 name = ce->name;
690 while ((match = *pathspec++) != NULL) {
691 int matchlen = strlen(match);
692 if (matchlen > len)
693 continue;
694 if (memcmp(name, match, matchlen))
695 continue;
696 if (matchlen && name[matchlen-1] == '/')
697 return 1;
698 if (name[matchlen] == '/' || !name[matchlen])
699 return 1;
700 if (!matchlen)
701 return 1;
703 return 0;
707 * We fundamentally don't like some paths: we don't want
708 * dot or dot-dot anywhere, and for obvious reasons don't
709 * want to recurse into ".git" either.
711 * Also, we don't want double slashes or slashes at the
712 * end that can make pathnames ambiguous.
714 static int verify_dotfile(const char *rest)
717 * The first character was '.', but that
718 * has already been discarded, we now test
719 * the rest.
721 switch (*rest) {
722 /* "." is not allowed */
723 case '\0': case '/':
724 return 0;
727 * ".git" followed by NUL or slash is bad. This
728 * shares the path end test with the ".." case.
730 case 'g':
731 if (rest[1] != 'i')
732 break;
733 if (rest[2] != 't')
734 break;
735 rest += 2;
736 /* fallthrough */
737 case '.':
738 if (rest[1] == '\0' || rest[1] == '/')
739 return 0;
741 return 1;
744 int verify_path(const char *path)
746 char c;
748 goto inside;
749 for (;;) {
750 if (!c)
751 return 1;
752 if (c == '/') {
753 inside:
754 c = *path++;
755 switch (c) {
756 default:
757 continue;
758 case '/': case '\0':
759 break;
760 case '.':
761 if (verify_dotfile(path))
762 continue;
764 return 0;
766 c = *path++;
771 * Do we have another file that has the beginning components being a
772 * proper superset of the name we're trying to add?
774 static int has_file_name(struct index_state *istate,
775 const struct cache_entry *ce, int pos, int ok_to_replace)
777 int retval = 0;
778 int len = ce_namelen(ce);
779 int stage = ce_stage(ce);
780 const char *name = ce->name;
782 while (pos < istate->cache_nr) {
783 struct cache_entry *p = istate->cache[pos++];
785 if (len >= ce_namelen(p))
786 break;
787 if (memcmp(name, p->name, len))
788 break;
789 if (ce_stage(p) != stage)
790 continue;
791 if (p->name[len] != '/')
792 continue;
793 if (p->ce_flags & CE_REMOVE)
794 continue;
795 retval = -1;
796 if (!ok_to_replace)
797 break;
798 remove_index_entry_at(istate, --pos);
800 return retval;
804 * Do we have another file with a pathname that is a proper
805 * subset of the name we're trying to add?
807 static int has_dir_name(struct index_state *istate,
808 const struct cache_entry *ce, int pos, int ok_to_replace)
810 int retval = 0;
811 int stage = ce_stage(ce);
812 const char *name = ce->name;
813 const char *slash = name + ce_namelen(ce);
815 for (;;) {
816 int len;
818 for (;;) {
819 if (*--slash == '/')
820 break;
821 if (slash <= ce->name)
822 return retval;
824 len = slash - name;
826 pos = index_name_pos(istate, name, create_ce_flags(len, stage));
827 if (pos >= 0) {
829 * Found one, but not so fast. This could
830 * be a marker that says "I was here, but
831 * I am being removed". Such an entry is
832 * not a part of the resulting tree, and
833 * it is Ok to have a directory at the same
834 * path.
836 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
837 retval = -1;
838 if (!ok_to_replace)
839 break;
840 remove_index_entry_at(istate, pos);
841 continue;
844 else
845 pos = -pos-1;
848 * Trivial optimization: if we find an entry that
849 * already matches the sub-directory, then we know
850 * we're ok, and we can exit.
852 while (pos < istate->cache_nr) {
853 struct cache_entry *p = istate->cache[pos];
854 if ((ce_namelen(p) <= len) ||
855 (p->name[len] != '/') ||
856 memcmp(p->name, name, len))
857 break; /* not our subdirectory */
858 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
860 * p is at the same stage as our entry, and
861 * is a subdirectory of what we are looking
862 * at, so we cannot have conflicts at our
863 * level or anything shorter.
865 return retval;
866 pos++;
869 return retval;
872 /* We may be in a situation where we already have path/file and path
873 * is being added, or we already have path and path/file is being
874 * added. Either one would result in a nonsense tree that has path
875 * twice when git-write-tree tries to write it out. Prevent it.
877 * If ok-to-replace is specified, we remove the conflicting entries
878 * from the cache so the caller should recompute the insert position.
879 * When this happens, we return non-zero.
881 static int check_file_directory_conflict(struct index_state *istate,
882 const struct cache_entry *ce,
883 int pos, int ok_to_replace)
885 int retval;
888 * When ce is an "I am going away" entry, we allow it to be added
890 if (ce->ce_flags & CE_REMOVE)
891 return 0;
894 * We check if the path is a sub-path of a subsequent pathname
895 * first, since removing those will not change the position
896 * in the array.
898 retval = has_file_name(istate, ce, pos, ok_to_replace);
901 * Then check if the path might have a clashing sub-directory
902 * before it.
904 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
907 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
909 int pos;
910 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
911 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
912 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
913 int new_only = option & ADD_CACHE_NEW_ONLY;
915 cache_tree_invalidate_path(istate->cache_tree, ce->name);
916 pos = index_name_pos(istate, ce->name, ce->ce_flags);
918 /* existing match? Just replace it. */
919 if (pos >= 0) {
920 if (!new_only)
921 replace_index_entry(istate, pos, ce);
922 return 0;
924 pos = -pos-1;
927 * Inserting a merged entry ("stage 0") into the index
928 * will always replace all non-merged entries..
930 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
931 while (ce_same_name(istate->cache[pos], ce)) {
932 ok_to_add = 1;
933 if (!remove_index_entry_at(istate, pos))
934 break;
938 if (!ok_to_add)
939 return -1;
940 if (!verify_path(ce->name))
941 return error("Invalid path '%s'", ce->name);
943 if (!skip_df_check &&
944 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
945 if (!ok_to_replace)
946 return error("'%s' appears as both a file and as a directory",
947 ce->name);
948 pos = index_name_pos(istate, ce->name, ce->ce_flags);
949 pos = -pos-1;
951 return pos + 1;
954 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
956 int pos;
958 if (option & ADD_CACHE_JUST_APPEND)
959 pos = istate->cache_nr;
960 else {
961 int ret;
962 ret = add_index_entry_with_check(istate, ce, option);
963 if (ret <= 0)
964 return ret;
965 pos = ret - 1;
968 /* Make sure the array is big enough .. */
969 if (istate->cache_nr == istate->cache_alloc) {
970 istate->cache_alloc = alloc_nr(istate->cache_alloc);
971 istate->cache = xrealloc(istate->cache,
972 istate->cache_alloc * sizeof(struct cache_entry *));
975 /* Add it in.. */
976 istate->cache_nr++;
977 if (istate->cache_nr > pos + 1)
978 memmove(istate->cache + pos + 1,
979 istate->cache + pos,
980 (istate->cache_nr - pos - 1) * sizeof(ce));
981 set_index_entry(istate, pos, ce);
982 istate->cache_changed = 1;
983 return 0;
987 * "refresh" does not calculate a new sha1 file or bring the
988 * cache up-to-date for mode/content changes. But what it
989 * _does_ do is to "re-match" the stat information of a file
990 * with the cache, so that you can refresh the cache for a
991 * file that hasn't been changed but where the stat entry is
992 * out of date.
994 * For example, you'd want to do this after doing a "git-read-tree",
995 * to link up the stat cache details with the proper files.
997 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
998 struct cache_entry *ce,
999 unsigned int options, int *err)
1001 struct stat st;
1002 struct cache_entry *updated;
1003 int changed, size;
1004 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
1006 if (ce_uptodate(ce))
1007 return ce;
1010 * CE_VALID means the user promised us that the change to
1011 * the work tree does not matter and told us not to worry.
1013 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1014 ce_mark_uptodate(ce);
1015 return ce;
1018 if (lstat(ce->name, &st) < 0) {
1019 if (err)
1020 *err = errno;
1021 return NULL;
1024 changed = ie_match_stat(istate, ce, &st, options);
1025 if (!changed) {
1027 * The path is unchanged. If we were told to ignore
1028 * valid bit, then we did the actual stat check and
1029 * found that the entry is unmodified. If the entry
1030 * is not marked VALID, this is the place to mark it
1031 * valid again, under "assume unchanged" mode.
1033 if (ignore_valid && assume_unchanged &&
1034 !(ce->ce_flags & CE_VALID))
1035 ; /* mark this one VALID again */
1036 else {
1038 * We do not mark the index itself "modified"
1039 * because CE_UPTODATE flag is in-core only;
1040 * we are not going to write this change out.
1042 ce_mark_uptodate(ce);
1043 return ce;
1047 if (ie_modified(istate, ce, &st, options)) {
1048 if (err)
1049 *err = EINVAL;
1050 return NULL;
1053 size = ce_size(ce);
1054 updated = xmalloc(size);
1055 memcpy(updated, ce, size);
1056 fill_stat_cache_info(updated, &st);
1058 * If ignore_valid is not set, we should leave CE_VALID bit
1059 * alone. Otherwise, paths marked with --no-assume-unchanged
1060 * (i.e. things to be edited) will reacquire CE_VALID bit
1061 * automatically, which is not really what we want.
1063 if (!ignore_valid && assume_unchanged &&
1064 !(ce->ce_flags & CE_VALID))
1065 updated->ce_flags &= ~CE_VALID;
1067 return updated;
1070 static void show_file(const char * fmt, const char * name, int in_porcelain,
1071 int * first, char *header_msg)
1073 if (in_porcelain && *first && header_msg) {
1074 printf("%s\n", header_msg);
1075 *first=0;
1077 printf(fmt, name);
1080 int refresh_index(struct index_state *istate, unsigned int flags, const char **pathspec,
1081 char *seen, char *header_msg)
1083 int i;
1084 int has_errors = 0;
1085 int really = (flags & REFRESH_REALLY) != 0;
1086 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1087 int quiet = (flags & REFRESH_QUIET) != 0;
1088 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1089 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1090 int first = 1;
1091 int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1092 unsigned int options = really ? CE_MATCH_IGNORE_VALID : 0;
1093 const char *needs_update_fmt;
1094 const char *needs_merge_fmt;
1096 needs_update_fmt = (in_porcelain ? "M\t%s\n" : "%s: needs update\n");
1097 needs_merge_fmt = (in_porcelain ? "U\t%s\n" : "%s: needs merge\n");
1098 for (i = 0; i < istate->cache_nr; i++) {
1099 struct cache_entry *ce, *new;
1100 int cache_errno = 0;
1102 ce = istate->cache[i];
1103 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1104 continue;
1106 if (ce_stage(ce)) {
1107 while ((i < istate->cache_nr) &&
1108 ! strcmp(istate->cache[i]->name, ce->name))
1109 i++;
1110 i--;
1111 if (allow_unmerged)
1112 continue;
1113 show_file(needs_merge_fmt, ce->name, in_porcelain, &first, header_msg);
1114 has_errors = 1;
1115 continue;
1118 if (pathspec && !match_pathspec(pathspec, ce->name, strlen(ce->name), 0, seen))
1119 continue;
1121 new = refresh_cache_ent(istate, ce, options, &cache_errno);
1122 if (new == ce)
1123 continue;
1124 if (!new) {
1125 if (not_new && cache_errno == ENOENT)
1126 continue;
1127 if (really && cache_errno == EINVAL) {
1128 /* If we are doing --really-refresh that
1129 * means the index is not valid anymore.
1131 ce->ce_flags &= ~CE_VALID;
1132 istate->cache_changed = 1;
1134 if (quiet)
1135 continue;
1136 show_file(needs_update_fmt, ce->name, in_porcelain, &first, header_msg);
1137 has_errors = 1;
1138 continue;
1141 replace_index_entry(istate, i, new);
1143 return has_errors;
1146 static struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
1148 return refresh_cache_ent(&the_index, ce, really, NULL);
1151 static int verify_hdr(struct cache_header *hdr, unsigned long size)
1153 git_SHA_CTX c;
1154 unsigned char sha1[20];
1156 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1157 return error("bad signature");
1158 if (hdr->hdr_version != htonl(2) && hdr->hdr_version != htonl(3))
1159 return error("bad index version");
1160 git_SHA1_Init(&c);
1161 git_SHA1_Update(&c, hdr, size - 20);
1162 git_SHA1_Final(sha1, &c);
1163 if (hashcmp(sha1, (unsigned char *)hdr + size - 20))
1164 return error("bad index file sha1 signature");
1165 return 0;
1168 static int read_index_extension(struct index_state *istate,
1169 const char *ext, void *data, unsigned long sz)
1171 switch (CACHE_EXT(ext)) {
1172 case CACHE_EXT_TREE:
1173 istate->cache_tree = cache_tree_read(data, sz);
1174 break;
1175 default:
1176 if (*ext < 'A' || 'Z' < *ext)
1177 return error("index uses %.4s extension, which we do not understand",
1178 ext);
1179 fprintf(stderr, "ignoring %.4s extension\n", ext);
1180 break;
1182 return 0;
1185 int read_index(struct index_state *istate)
1187 return read_index_from(istate, get_index_file());
1190 static void convert_from_disk(struct ondisk_cache_entry *ondisk, struct cache_entry *ce)
1192 size_t len;
1193 const char *name;
1195 ce->ce_ctime.sec = ntohl(ondisk->ctime.sec);
1196 ce->ce_mtime.sec = ntohl(ondisk->mtime.sec);
1197 ce->ce_ctime.nsec = ntohl(ondisk->ctime.nsec);
1198 ce->ce_mtime.nsec = ntohl(ondisk->mtime.nsec);
1199 ce->ce_dev = ntohl(ondisk->dev);
1200 ce->ce_ino = ntohl(ondisk->ino);
1201 ce->ce_mode = ntohl(ondisk->mode);
1202 ce->ce_uid = ntohl(ondisk->uid);
1203 ce->ce_gid = ntohl(ondisk->gid);
1204 ce->ce_size = ntohl(ondisk->size);
1205 /* On-disk flags are just 16 bits */
1206 ce->ce_flags = ntohs(ondisk->flags);
1208 hashcpy(ce->sha1, ondisk->sha1);
1210 len = ce->ce_flags & CE_NAMEMASK;
1212 if (ce->ce_flags & CE_EXTENDED) {
1213 struct ondisk_cache_entry_extended *ondisk2;
1214 int extended_flags;
1215 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
1216 extended_flags = ntohs(ondisk2->flags2) << 16;
1217 /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1218 if (extended_flags & ~CE_EXTENDED_FLAGS)
1219 die("Unknown index entry format %08x", extended_flags);
1220 ce->ce_flags |= extended_flags;
1221 name = ondisk2->name;
1223 else
1224 name = ondisk->name;
1226 if (len == CE_NAMEMASK)
1227 len = strlen(name);
1229 * NEEDSWORK: If the original index is crafted, this copy could
1230 * go unchecked.
1232 memcpy(ce->name, name, len + 1);
1235 static inline size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1237 long per_entry;
1239 per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1242 * Alignment can cause differences. This should be "alignof", but
1243 * since that's a gcc'ism, just use the size of a pointer.
1245 per_entry += sizeof(void *);
1246 return ondisk_size + entries*per_entry;
1249 /* remember to discard_cache() before reading a different cache! */
1250 int read_index_from(struct index_state *istate, const char *path)
1252 int fd, i;
1253 struct stat st;
1254 unsigned long src_offset, dst_offset;
1255 struct cache_header *hdr;
1256 void *mmap;
1257 size_t mmap_size;
1259 errno = EBUSY;
1260 if (istate->initialized)
1261 return istate->cache_nr;
1263 errno = ENOENT;
1264 istate->timestamp.sec = 0;
1265 istate->timestamp.nsec = 0;
1266 fd = open(path, O_RDONLY);
1267 if (fd < 0) {
1268 if (errno == ENOENT)
1269 return 0;
1270 die_errno("index file open failed");
1273 if (fstat(fd, &st))
1274 die_errno("cannot stat the open index");
1276 errno = EINVAL;
1277 mmap_size = xsize_t(st.st_size);
1278 if (mmap_size < sizeof(struct cache_header) + 20)
1279 die("index file smaller than expected");
1281 mmap = xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
1282 close(fd);
1283 if (mmap == MAP_FAILED)
1284 die_errno("unable to map index file");
1286 hdr = mmap;
1287 if (verify_hdr(hdr, mmap_size) < 0)
1288 goto unmap;
1290 istate->cache_nr = ntohl(hdr->hdr_entries);
1291 istate->cache_alloc = alloc_nr(istate->cache_nr);
1292 istate->cache = xcalloc(istate->cache_alloc, sizeof(struct cache_entry *));
1295 * The disk format is actually larger than the in-memory format,
1296 * due to space for nsec etc, so even though the in-memory one
1297 * has room for a few more flags, we can allocate using the same
1298 * index size
1300 istate->alloc = xmalloc(estimate_cache_size(mmap_size, istate->cache_nr));
1301 istate->initialized = 1;
1303 src_offset = sizeof(*hdr);
1304 dst_offset = 0;
1305 for (i = 0; i < istate->cache_nr; i++) {
1306 struct ondisk_cache_entry *disk_ce;
1307 struct cache_entry *ce;
1309 disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
1310 ce = (struct cache_entry *)((char *)istate->alloc + dst_offset);
1311 convert_from_disk(disk_ce, ce);
1312 set_index_entry(istate, i, ce);
1314 src_offset += ondisk_ce_size(ce);
1315 dst_offset += ce_size(ce);
1317 istate->timestamp.sec = st.st_mtime;
1318 istate->timestamp.nsec = ST_MTIME_NSEC(st);
1320 while (src_offset <= mmap_size - 20 - 8) {
1321 /* After an array of active_nr index entries,
1322 * there can be arbitrary number of extended
1323 * sections, each of which is prefixed with
1324 * extension name (4-byte) and section length
1325 * in 4-byte network byte order.
1327 uint32_t extsize;
1328 memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
1329 extsize = ntohl(extsize);
1330 if (read_index_extension(istate,
1331 (const char *) mmap + src_offset,
1332 (char *) mmap + src_offset + 8,
1333 extsize) < 0)
1334 goto unmap;
1335 src_offset += 8;
1336 src_offset += extsize;
1338 munmap(mmap, mmap_size);
1339 return istate->cache_nr;
1341 unmap:
1342 munmap(mmap, mmap_size);
1343 errno = EINVAL;
1344 die("index file corrupt");
1347 int is_index_unborn(struct index_state *istate)
1349 return (!istate->cache_nr && !istate->alloc && !istate->timestamp.sec);
1352 int discard_index(struct index_state *istate)
1354 istate->cache_nr = 0;
1355 istate->cache_changed = 0;
1356 istate->timestamp.sec = 0;
1357 istate->timestamp.nsec = 0;
1358 istate->name_hash_initialized = 0;
1359 free_hash(&istate->name_hash);
1360 cache_tree_free(&(istate->cache_tree));
1361 free(istate->alloc);
1362 istate->alloc = NULL;
1363 istate->initialized = 0;
1365 /* no need to throw away allocated active_cache */
1366 return 0;
1369 int unmerged_index(const struct index_state *istate)
1371 int i;
1372 for (i = 0; i < istate->cache_nr; i++) {
1373 if (ce_stage(istate->cache[i]))
1374 return 1;
1376 return 0;
1379 #define WRITE_BUFFER_SIZE 8192
1380 static unsigned char write_buffer[WRITE_BUFFER_SIZE];
1381 static unsigned long write_buffer_len;
1383 static int ce_write_flush(git_SHA_CTX *context, int fd)
1385 unsigned int buffered = write_buffer_len;
1386 if (buffered) {
1387 git_SHA1_Update(context, write_buffer, buffered);
1388 if (write_in_full(fd, write_buffer, buffered) != buffered)
1389 return -1;
1390 write_buffer_len = 0;
1392 return 0;
1395 static int ce_write(git_SHA_CTX *context, int fd, void *data, unsigned int len)
1397 while (len) {
1398 unsigned int buffered = write_buffer_len;
1399 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
1400 if (partial > len)
1401 partial = len;
1402 memcpy(write_buffer + buffered, data, partial);
1403 buffered += partial;
1404 if (buffered == WRITE_BUFFER_SIZE) {
1405 write_buffer_len = buffered;
1406 if (ce_write_flush(context, fd))
1407 return -1;
1408 buffered = 0;
1410 write_buffer_len = buffered;
1411 len -= partial;
1412 data = (char *) data + partial;
1414 return 0;
1417 static int write_index_ext_header(git_SHA_CTX *context, int fd,
1418 unsigned int ext, unsigned int sz)
1420 ext = htonl(ext);
1421 sz = htonl(sz);
1422 return ((ce_write(context, fd, &ext, 4) < 0) ||
1423 (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
1426 static int ce_flush(git_SHA_CTX *context, int fd)
1428 unsigned int left = write_buffer_len;
1430 if (left) {
1431 write_buffer_len = 0;
1432 git_SHA1_Update(context, write_buffer, left);
1435 /* Flush first if not enough space for SHA1 signature */
1436 if (left + 20 > WRITE_BUFFER_SIZE) {
1437 if (write_in_full(fd, write_buffer, left) != left)
1438 return -1;
1439 left = 0;
1442 /* Append the SHA1 signature at the end */
1443 git_SHA1_Final(write_buffer + left, context);
1444 left += 20;
1445 return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0;
1448 static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
1451 * The only thing we care about in this function is to smudge the
1452 * falsely clean entry due to touch-update-touch race, so we leave
1453 * everything else as they are. We are called for entries whose
1454 * ce_mtime match the index file mtime.
1456 * Note that this actually does not do much for gitlinks, for
1457 * which ce_match_stat_basic() always goes to the actual
1458 * contents. The caller checks with is_racy_timestamp() which
1459 * always says "no" for gitlinks, so we are not called for them ;-)
1461 struct stat st;
1463 if (lstat(ce->name, &st) < 0)
1464 return;
1465 if (ce_match_stat_basic(ce, &st))
1466 return;
1467 if (ce_modified_check_fs(ce, &st)) {
1468 /* This is "racily clean"; smudge it. Note that this
1469 * is a tricky code. At first glance, it may appear
1470 * that it can break with this sequence:
1472 * $ echo xyzzy >frotz
1473 * $ git-update-index --add frotz
1474 * $ : >frotz
1475 * $ sleep 3
1476 * $ echo filfre >nitfol
1477 * $ git-update-index --add nitfol
1479 * but it does not. When the second update-index runs,
1480 * it notices that the entry "frotz" has the same timestamp
1481 * as index, and if we were to smudge it by resetting its
1482 * size to zero here, then the object name recorded
1483 * in index is the 6-byte file but the cached stat information
1484 * becomes zero --- which would then match what we would
1485 * obtain from the filesystem next time we stat("frotz").
1487 * However, the second update-index, before calling
1488 * this function, notices that the cached size is 6
1489 * bytes and what is on the filesystem is an empty
1490 * file, and never calls us, so the cached size information
1491 * for "frotz" stays 6 which does not match the filesystem.
1493 ce->ce_size = 0;
1497 static int ce_write_entry(git_SHA_CTX *c, int fd, struct cache_entry *ce)
1499 int size = ondisk_ce_size(ce);
1500 struct ondisk_cache_entry *ondisk = xcalloc(1, size);
1501 char *name;
1503 ondisk->ctime.sec = htonl(ce->ce_ctime.sec);
1504 ondisk->mtime.sec = htonl(ce->ce_mtime.sec);
1505 ondisk->ctime.nsec = htonl(ce->ce_ctime.nsec);
1506 ondisk->mtime.nsec = htonl(ce->ce_mtime.nsec);
1507 ondisk->dev = htonl(ce->ce_dev);
1508 ondisk->ino = htonl(ce->ce_ino);
1509 ondisk->mode = htonl(ce->ce_mode);
1510 ondisk->uid = htonl(ce->ce_uid);
1511 ondisk->gid = htonl(ce->ce_gid);
1512 ondisk->size = htonl(ce->ce_size);
1513 hashcpy(ondisk->sha1, ce->sha1);
1514 ondisk->flags = htons(ce->ce_flags);
1515 if (ce->ce_flags & CE_EXTENDED) {
1516 struct ondisk_cache_entry_extended *ondisk2;
1517 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
1518 ondisk2->flags2 = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
1519 name = ondisk2->name;
1521 else
1522 name = ondisk->name;
1523 memcpy(name, ce->name, ce_namelen(ce));
1525 return ce_write(c, fd, ondisk, size);
1528 int write_index(struct index_state *istate, int newfd)
1530 git_SHA_CTX c;
1531 struct cache_header hdr;
1532 int i, err, removed, extended;
1533 struct cache_entry **cache = istate->cache;
1534 int entries = istate->cache_nr;
1535 struct stat st;
1537 for (i = removed = extended = 0; i < entries; i++) {
1538 if (cache[i]->ce_flags & CE_REMOVE)
1539 removed++;
1541 /* reduce extended entries if possible */
1542 cache[i]->ce_flags &= ~CE_EXTENDED;
1543 if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
1544 extended++;
1545 cache[i]->ce_flags |= CE_EXTENDED;
1549 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
1550 /* for extended format, increase version so older git won't try to read it */
1551 hdr.hdr_version = htonl(extended ? 3 : 2);
1552 hdr.hdr_entries = htonl(entries - removed);
1554 git_SHA1_Init(&c);
1555 if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
1556 return -1;
1558 for (i = 0; i < entries; i++) {
1559 struct cache_entry *ce = cache[i];
1560 if (ce->ce_flags & CE_REMOVE)
1561 continue;
1562 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
1563 ce_smudge_racily_clean_entry(ce);
1564 if (ce_write_entry(&c, newfd, ce) < 0)
1565 return -1;
1568 /* Write extension data here */
1569 if (istate->cache_tree) {
1570 struct strbuf sb = STRBUF_INIT;
1572 cache_tree_write(&sb, istate->cache_tree);
1573 err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
1574 || ce_write(&c, newfd, sb.buf, sb.len) < 0;
1575 strbuf_release(&sb);
1576 if (err)
1577 return -1;
1580 if (ce_flush(&c, newfd) || fstat(newfd, &st))
1581 return -1;
1582 istate->timestamp.sec = (unsigned int)st.st_mtime;
1583 istate->timestamp.nsec = ST_MTIME_NSEC(st);
1584 return 0;
1588 * Read the index file that is potentially unmerged into given
1589 * index_state, dropping any unmerged entries. Returns true if
1590 * the index is unmerged. Callers who want to refuse to work
1591 * from an unmerged state can call this and check its return value,
1592 * instead of calling read_cache().
1594 int read_index_unmerged(struct index_state *istate)
1596 int i;
1597 int unmerged = 0;
1599 read_index(istate);
1600 for (i = 0; i < istate->cache_nr; i++) {
1601 struct cache_entry *ce = istate->cache[i];
1602 struct cache_entry *new_ce;
1603 int size, len;
1605 if (!ce_stage(ce))
1606 continue;
1607 unmerged = 1;
1608 len = strlen(ce->name);
1609 size = cache_entry_size(len);
1610 new_ce = xcalloc(1, size);
1611 hashcpy(new_ce->sha1, ce->sha1);
1612 memcpy(new_ce->name, ce->name, len);
1613 new_ce->ce_flags = create_ce_flags(len, 0);
1614 new_ce->ce_mode = ce->ce_mode;
1615 if (add_index_entry(istate, new_ce, 0))
1616 return error("%s: cannot drop to stage #0",
1617 ce->name);
1618 i = index_name_pos(istate, new_ce->name, len);
1620 return unmerged;
1623 struct update_callback_data
1625 int flags;
1626 int add_errors;
1629 static void update_callback(struct diff_queue_struct *q,
1630 struct diff_options *opt, void *cbdata)
1632 int i;
1633 struct update_callback_data *data = cbdata;
1635 for (i = 0; i < q->nr; i++) {
1636 struct diff_filepair *p = q->queue[i];
1637 const char *path = p->one->path;
1638 switch (p->status) {
1639 default:
1640 die("unexpected diff status %c", p->status);
1641 case DIFF_STATUS_UNMERGED:
1643 * ADD_CACHE_IGNORE_REMOVAL is unset if "git
1644 * add -u" is calling us, In such a case, a
1645 * missing work tree file needs to be removed
1646 * if there is an unmerged entry at stage #2,
1647 * but such a diff record is followed by
1648 * another with DIFF_STATUS_DELETED (and if
1649 * there is no stage #2, we won't see DELETED
1650 * nor MODIFIED). We can simply continue
1651 * either way.
1653 if (!(data->flags & ADD_CACHE_IGNORE_REMOVAL))
1654 continue;
1656 * Otherwise, it is "git add path" is asking
1657 * to explicitly add it; we fall through. A
1658 * missing work tree file is an error and is
1659 * caught by add_file_to_index() in such a
1660 * case.
1662 case DIFF_STATUS_MODIFIED:
1663 case DIFF_STATUS_TYPE_CHANGED:
1664 if (add_file_to_index(&the_index, path, data->flags)) {
1665 if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
1666 die("updating files failed");
1667 data->add_errors++;
1669 break;
1670 case DIFF_STATUS_DELETED:
1671 if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
1672 break;
1673 if (!(data->flags & ADD_CACHE_PRETEND))
1674 remove_file_from_index(&the_index, path);
1675 if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
1676 printf("remove '%s'\n", path);
1677 break;
1682 int add_files_to_cache(const char *prefix, const char **pathspec, int flags)
1684 struct update_callback_data data;
1685 struct rev_info rev;
1686 init_revisions(&rev, prefix);
1687 setup_revisions(0, NULL, &rev, NULL);
1688 rev.prune_data = pathspec;
1689 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1690 rev.diffopt.format_callback = update_callback;
1691 data.flags = flags;
1692 data.add_errors = 0;
1693 rev.diffopt.format_callback_data = &data;
1694 run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
1695 return !!data.add_errors;
1699 * Returns 1 if the path is an "other" path with respect to
1700 * the index; that is, the path is not mentioned in the index at all,
1701 * either as a file, a directory with some files in the index,
1702 * or as an unmerged entry.
1704 * We helpfully remove a trailing "/" from directories so that
1705 * the output of read_directory can be used as-is.
1707 int index_name_is_other(const struct index_state *istate, const char *name,
1708 int namelen)
1710 int pos;
1711 if (namelen && name[namelen - 1] == '/')
1712 namelen--;
1713 pos = index_name_pos(istate, name, namelen);
1714 if (0 <= pos)
1715 return 0; /* exact match */
1716 pos = -pos - 1;
1717 if (pos < istate->cache_nr) {
1718 struct cache_entry *ce = istate->cache[pos];
1719 if (ce_namelen(ce) == namelen &&
1720 !memcmp(ce->name, name, namelen))
1721 return 0; /* Yup, this one exists unmerged */
1723 return 1;