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