ref_transaction_verify(): new function to check a reference's value
[git/git.git] / refs.c
CommitLineData
95fc7512 1#include "cache.h"
697cc8ef 2#include "lockfile.h"
85023577 3#include "refs.h"
cf0adba7
JH
4#include "object.h"
5#include "tag.h"
7155b727 6#include "dir.h"
daebaa78 7#include "string-list.h"
95fc7512 8
3581d793
SB
9struct ref_lock {
10 char *ref_name;
11 char *orig_ref_name;
12 struct lock_file *lk;
13 unsigned char old_sha1[20];
14 int lock_fd;
15 int force_write;
16};
17
bc5fd6d3 18/*
dde8a902
DT
19 * How to handle various characters in refnames:
20 * 0: An acceptable character for refs
5e650228
JH
21 * 1: End-of-component
22 * 2: ., look for a preceding . to reject .. in refs
23 * 3: {, look for a preceding @ to reject @{ in refs
24 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
dde8a902
DT
25 */
26static unsigned char refname_disposition[256] = {
5e650228
JH
27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
dde8a902 31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5e650228
JH
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
dde8a902
DT
35};
36
581d4e0c
MH
37/*
38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
39 * refs (i.e., because the reference is about to be deleted anyway).
40 */
41#define REF_DELETING 0x02
42
029cdb4a 43/*
8df4e511 44 * Used as a flag in ref_update::flags when a loose ref is being
029cdb4a
RS
45 * pruned.
46 */
31e79f0a
MH
47#define REF_ISPRUNING 0x04
48
16180334
MH
49/*
50 * Used as a flag in ref_update::flags when the reference should be
51 * updated to new_sha1.
52 */
53#define REF_HAVE_NEW 0x08
54
8df4e511
MH
55/*
56 * Used as a flag in ref_update::flags when old_sha1 should be
57 * checked.
58 */
16180334 59#define REF_HAVE_OLD 0x10
8df4e511 60
dde8a902
DT
61/*
62 * Try to read one refname component from the front of refname.
63 * Return the length of the component found, or -1 if the component is
64 * not legal. It is legal if it is something reasonable to have under
65 * ".git/refs/"; We do not like it if:
bc5fd6d3
MH
66 *
67 * - any path component of it begins with ".", or
68 * - it has double dots "..", or
69 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
5e650228
JH
70 * - it ends with a "/".
71 * - it ends with ".lock"
bc5fd6d3
MH
72 * - it contains a "\" (backslash)
73 */
bc5fd6d3
MH
74static int check_refname_component(const char *refname, int flags)
75{
76 const char *cp;
77 char last = '\0';
78
79 for (cp = refname; ; cp++) {
dde8a902
DT
80 int ch = *cp & 255;
81 unsigned char disp = refname_disposition[ch];
82 switch (disp) {
5e650228 83 case 1:
dde8a902 84 goto out;
5e650228 85 case 2:
dde8a902
DT
86 if (last == '.')
87 return -1; /* Refname contains "..". */
88 break;
5e650228 89 case 3:
dde8a902
DT
90 if (last == '@')
91 return -1; /* Refname contains "@{". */
bc5fd6d3 92 break;
5e650228 93 case 4:
dde8a902
DT
94 return -1;
95 }
bc5fd6d3
MH
96 last = ch;
97 }
dde8a902 98out:
bc5fd6d3 99 if (cp == refname)
dac529e4 100 return 0; /* Component has zero length. */
f3cc52d8
JN
101 if (refname[0] == '.')
102 return -1; /* Component starts with '.'. */
7108ad23
MH
103 if (cp - refname >= LOCK_SUFFIX_LEN &&
104 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
bc5fd6d3
MH
105 return -1; /* Refname ends with ".lock". */
106 return cp - refname;
107}
108
5e650228 109int check_refname_format(const char *refname, int flags)
bc5fd6d3
MH
110{
111 int component_len, component_count = 0;
112
9ba89f48
FC
113 if (!strcmp(refname, "@"))
114 /* Refname is a single character '@'. */
115 return -1;
116
bc5fd6d3
MH
117 while (1) {
118 /* We are at the start of a path component. */
119 component_len = check_refname_component(refname, flags);
dac529e4 120 if (component_len <= 0) {
bc5fd6d3
MH
121 if ((flags & REFNAME_REFSPEC_PATTERN) &&
122 refname[0] == '*' &&
123 (refname[1] == '\0' || refname[1] == '/')) {
124 /* Accept one wildcard as a full refname component. */
125 flags &= ~REFNAME_REFSPEC_PATTERN;
126 component_len = 1;
127 } else {
128 return -1;
129 }
130 }
131 component_count++;
132 if (refname[component_len] == '\0')
133 break;
134 /* Skip to next component. */
135 refname += component_len + 1;
136 }
137
138 if (refname[component_len - 1] == '.')
139 return -1; /* Refname ends with '.'. */
140 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
141 return -1; /* Refname has only one component. */
142 return 0;
143}
144
145struct ref_entry;
e1e22e37 146
28e6a34e
MH
147/*
148 * Information used (along with the information in ref_entry) to
149 * describe a single cached reference. This data structure only
150 * occurs embedded in a union in struct ref_entry, and only when
151 * (ref_entry->flag & REF_DIR) is zero.
152 */
593f1bb8 153struct ref_value {
6c6f58df
MH
154 /*
155 * The name of the object to which this reference resolves
156 * (which may be a tag object). If REF_ISBROKEN, this is
157 * null. If REF_ISSYMREF, then this is the name of the object
158 * referred to by the last reference in the symlink chain.
159 */
593f1bb8 160 unsigned char sha1[20];
6c6f58df
MH
161
162 /*
163 * If REF_KNOWS_PEELED, then this field holds the peeled value
164 * of this reference, or null if the reference is known not to
2312a793
MH
165 * be peelable. See the documentation for peel_ref() for an
166 * exact definition of "peelable".
6c6f58df 167 */
593f1bb8
MH
168 unsigned char peeled[20];
169};
170
f006c42a
MH
171struct ref_cache;
172
28e6a34e
MH
173/*
174 * Information used (along with the information in ref_entry) to
175 * describe a level in the hierarchy of references. This data
176 * structure only occurs embedded in a union in struct ref_entry, and
177 * only when (ref_entry.flag & REF_DIR) is set. In that case,
178 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
179 * in the directory have already been read:
180 *
181 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
182 * or packed references, already read.
183 *
184 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
185 * references that hasn't been read yet (nor has any of its
186 * subdirectories).
187 *
188 * Entries within a directory are stored within a growable array of
189 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
190 * sorted are sorted by their component name in strcmp() order and the
191 * remaining entries are unsorted.
192 *
193 * Loose references are read lazily, one directory at a time. When a
194 * directory of loose references is read, then all of the references
195 * in that directory are stored, and REF_INCOMPLETE stubs are created
196 * for any subdirectories, but the subdirectories themselves are not
197 * read. The reading is triggered by get_ref_dir().
198 */
d3177275 199struct ref_dir {
e9c4c111 200 int nr, alloc;
e6ed3ca6
MH
201
202 /*
203 * Entries with index 0 <= i < sorted are sorted by name. New
204 * entries are appended to the list unsorted, and are sorted
205 * only when required; thus we avoid the need to sort the list
206 * after the addition of every reference.
207 */
208 int sorted;
209
f006c42a
MH
210 /* A pointer to the ref_cache that contains this ref_dir. */
211 struct ref_cache *ref_cache;
212
d3177275 213 struct ref_entry **entries;
e9c4c111
JP
214};
215
89df9c84
MH
216/*
217 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
d0f810f0
RS
218 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
219 * public values; see refs.h.
89df9c84
MH
220 */
221
222/*
223 * The field ref_entry->u.value.peeled of this value entry contains
224 * the correct peeled value for the reference, which might be
225 * null_sha1 if the reference is not a tag or if it is broken.
226 */
d0f810f0 227#define REF_KNOWS_PEELED 0x10
28e6a34e
MH
228
229/* ref_entry represents a directory of references */
d0f810f0 230#define REF_DIR 0x20
cf0adba7 231
28e6a34e
MH
232/*
233 * Entry has not yet been read from disk (used only for REF_DIR
234 * entries representing loose references)
235 */
d0f810f0 236#define REF_INCOMPLETE 0x40
28e6a34e 237
432ad41e
MH
238/*
239 * A ref_entry represents either a reference or a "subdirectory" of
28e6a34e
MH
240 * references.
241 *
242 * Each directory in the reference namespace is represented by a
243 * ref_entry with (flags & REF_DIR) set and containing a subdir member
244 * that holds the entries in that directory that have been read so
245 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
246 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
247 * used for loose reference directories.
248 *
249 * References are represented by a ref_entry with (flags & REF_DIR)
250 * unset and a value member that describes the reference's value. The
251 * flag member is at the ref_entry level, but it is also needed to
252 * interpret the contents of the value field (in other words, a
253 * ref_value object is not very much use without the enclosing
254 * ref_entry).
432ad41e
MH
255 *
256 * Reference names cannot end with slash and directories' names are
257 * always stored with a trailing slash (except for the top-level
258 * directory, which is always denoted by ""). This has two nice
259 * consequences: (1) when the entries in each subdir are sorted
260 * lexicographically by name (as they usually are), the references in
261 * a whole tree can be generated in lexicographic order by traversing
262 * the tree in left-to-right, depth-first order; (2) the names of
263 * references and subdirectories cannot conflict, and therefore the
264 * presence of an empty subdirectory does not block the creation of a
265 * similarly-named reference. (The fact that reference names with the
266 * same leading components can conflict *with each other* is a
267 * separate issue that is regulated by is_refname_available().)
268 *
269 * Please note that the name field contains the fully-qualified
270 * reference (or subdirectory) name. Space could be saved by only
271 * storing the relative names. But that would require the full names
272 * to be generated on the fly when iterating in do_for_each_ref(), and
273 * would break callback functions, who have always been able to assume
274 * that the name strings that they are passed will not be freed during
275 * the iteration.
276 */
bc5fd6d3
MH
277struct ref_entry {
278 unsigned char flag; /* ISSYMREF? ISPACKED? */
593f1bb8 279 union {
432ad41e
MH
280 struct ref_value value; /* if not (flags&REF_DIR) */
281 struct ref_dir subdir; /* if (flags&REF_DIR) */
593f1bb8 282 } u;
432ad41e
MH
283 /*
284 * The full name of the reference (e.g., "refs/heads/master")
285 * or the full name of the directory with a trailing slash
286 * (e.g., "refs/heads/"):
287 */
bc5fd6d3
MH
288 char name[FLEX_ARRAY];
289};
e1e22e37 290
28e6a34e
MH
291static void read_loose_refs(const char *dirname, struct ref_dir *dir);
292
d7826d54
MH
293static struct ref_dir *get_ref_dir(struct ref_entry *entry)
294{
28e6a34e 295 struct ref_dir *dir;
d7826d54 296 assert(entry->flag & REF_DIR);
28e6a34e
MH
297 dir = &entry->u.subdir;
298 if (entry->flag & REF_INCOMPLETE) {
299 read_loose_refs(entry->name, dir);
300 entry->flag &= ~REF_INCOMPLETE;
301 }
302 return dir;
d7826d54
MH
303}
304
d0f810f0
RS
305/*
306 * Check if a refname is safe.
307 * For refs that start with "refs/" we consider it safe as long they do
308 * not try to resolve to outside of refs/.
309 *
310 * For all other refs we only consider them safe iff they only contain
311 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
312 * "config").
313 */
314static int refname_is_safe(const char *refname)
315{
316 if (starts_with(refname, "refs/")) {
317 char *buf;
318 int result;
319
320 buf = xmalloc(strlen(refname) + 1);
321 /*
322 * Does the refname try to escape refs/?
323 * For example: refs/foo/../bar is safe but refs/foo/../../bar
324 * is not.
325 */
326 result = !normalize_path_copy(buf, refname + strlen("refs/"));
327 free(buf);
328 return result;
329 }
330 while (*refname) {
331 if (!isupper(*refname) && *refname != '_')
332 return 0;
333 refname++;
334 }
335 return 1;
336}
337
cddc4258
MH
338static struct ref_entry *create_ref_entry(const char *refname,
339 const unsigned char *sha1, int flag,
340 int check_name)
e1e22e37
LT
341{
342 int len;
cddc4258 343 struct ref_entry *ref;
e1e22e37 344
09116a1c 345 if (check_name &&
f3cc52d8 346 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
dfefa935 347 die("Reference has invalid format: '%s'", refname);
d0f810f0
RS
348 if (!check_name && !refname_is_safe(refname))
349 die("Reference has invalid name: '%s'", refname);
cddc4258
MH
350 len = strlen(refname) + 1;
351 ref = xmalloc(sizeof(struct ref_entry) + len);
593f1bb8
MH
352 hashcpy(ref->u.value.sha1, sha1);
353 hashclr(ref->u.value.peeled);
cddc4258
MH
354 memcpy(ref->name, refname, len);
355 ref->flag = flag;
356 return ref;
357}
358
432ad41e
MH
359static void clear_ref_dir(struct ref_dir *dir);
360
732134ed
MH
361static void free_ref_entry(struct ref_entry *entry)
362{
27b5587c
MH
363 if (entry->flag & REF_DIR) {
364 /*
365 * Do not use get_ref_dir() here, as that might
366 * trigger the reading of loose refs.
367 */
368 clear_ref_dir(&entry->u.subdir);
369 }
732134ed
MH
370 free(entry);
371}
372
432ad41e
MH
373/*
374 * Add a ref_entry to the end of dir (unsorted). Entry is always
375 * stored directly in dir; no recursion into subdirectories is
376 * done.
377 */
378static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
cddc4258 379{
432ad41e
MH
380 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
381 dir->entries[dir->nr++] = entry;
654ad400
MH
382 /* optimize for the case that entries are added in order */
383 if (dir->nr == 1 ||
384 (dir->nr == dir->sorted + 1 &&
385 strcmp(dir->entries[dir->nr - 2]->name,
386 dir->entries[dir->nr - 1]->name) < 0))
387 dir->sorted = dir->nr;
c774aab9
JP
388}
389
432ad41e
MH
390/*
391 * Clear and free all entries in dir, recursively.
392 */
d3177275 393static void clear_ref_dir(struct ref_dir *dir)
bc5fd6d3
MH
394{
395 int i;
d3177275
MH
396 for (i = 0; i < dir->nr; i++)
397 free_ref_entry(dir->entries[i]);
398 free(dir->entries);
399 dir->sorted = dir->nr = dir->alloc = 0;
400 dir->entries = NULL;
bc5fd6d3
MH
401}
402
432ad41e
MH
403/*
404 * Create a struct ref_entry object for the specified dirname.
405 * dirname is the name of the directory with a trailing slash (e.g.,
406 * "refs/heads/") or "" for the top-level directory.
407 */
f006c42a 408static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
b9146f51
RS
409 const char *dirname, size_t len,
410 int incomplete)
432ad41e
MH
411{
412 struct ref_entry *direntry;
432ad41e 413 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
b9146f51
RS
414 memcpy(direntry->name, dirname, len);
415 direntry->name[len] = '\0';
f006c42a 416 direntry->u.subdir.ref_cache = ref_cache;
28e6a34e 417 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
432ad41e
MH
418 return direntry;
419}
420
e9c4c111 421static int ref_entry_cmp(const void *a, const void *b)
c774aab9 422{
e9c4c111
JP
423 struct ref_entry *one = *(struct ref_entry **)a;
424 struct ref_entry *two = *(struct ref_entry **)b;
425 return strcmp(one->name, two->name);
426}
c774aab9 427
d3177275 428static void sort_ref_dir(struct ref_dir *dir);
bc5fd6d3 429
e1980c9d
JH
430struct string_slice {
431 size_t len;
432 const char *str;
433};
434
435static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
436{
c971ddfd
RS
437 const struct string_slice *key = key_;
438 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
439 int cmp = strncmp(key->str, ent->name, key->len);
e1980c9d
JH
440 if (cmp)
441 return cmp;
c971ddfd 442 return '\0' - (unsigned char)ent->name[key->len];
e1980c9d
JH
443}
444
432ad41e 445/*
9fc0a648
MH
446 * Return the index of the entry with the given refname from the
447 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
448 * no such entry is found. dir must already be complete.
432ad41e 449 */
9fc0a648 450static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
bc5fd6d3 451{
e1980c9d
JH
452 struct ref_entry **r;
453 struct string_slice key;
bc5fd6d3 454
432ad41e 455 if (refname == NULL || !dir->nr)
9fc0a648 456 return -1;
bc5fd6d3 457
d3177275 458 sort_ref_dir(dir);
e1980c9d
JH
459 key.len = len;
460 key.str = refname;
461 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
462 ref_entry_cmp_sslice);
bc5fd6d3
MH
463
464 if (r == NULL)
9fc0a648 465 return -1;
bc5fd6d3 466
9fc0a648 467 return r - dir->entries;
bc5fd6d3
MH
468}
469
f348ac92
MH
470/*
471 * Search for a directory entry directly within dir (without
472 * recursing). Sort dir if necessary. subdirname must be a directory
473 * name (i.e., end in '/'). If mkdir is set, then create the
474 * directory if it is missing; otherwise, return NULL if the desired
28e6a34e 475 * directory cannot be found. dir must already be complete.
f348ac92 476 */
3f3aa1bc 477static struct ref_dir *search_for_subdir(struct ref_dir *dir,
dd02e728
RS
478 const char *subdirname, size_t len,
479 int mkdir)
f348ac92 480{
9fc0a648
MH
481 int entry_index = search_ref_dir(dir, subdirname, len);
482 struct ref_entry *entry;
483 if (entry_index == -1) {
f348ac92
MH
484 if (!mkdir)
485 return NULL;
28e6a34e
MH
486 /*
487 * Since dir is complete, the absence of a subdir
488 * means that the subdir really doesn't exist;
489 * therefore, create an empty record for it but mark
490 * the record complete.
491 */
b9146f51 492 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
f348ac92 493 add_entry_to_dir(dir, entry);
9fc0a648
MH
494 } else {
495 entry = dir->entries[entry_index];
f348ac92 496 }
3f3aa1bc 497 return get_ref_dir(entry);
f348ac92
MH
498}
499
432ad41e
MH
500/*
501 * If refname is a reference name, find the ref_dir within the dir
502 * tree that should hold refname. If refname is a directory name
503 * (i.e., ends in '/'), then return that ref_dir itself. dir must
28e6a34e
MH
504 * represent the top-level directory and must already be complete.
505 * Sort ref_dirs and recurse into subdirectories as necessary. If
506 * mkdir is set, then create any missing directories; otherwise,
507 * return NULL if the desired directory cannot be found.
432ad41e
MH
508 */
509static struct ref_dir *find_containing_dir(struct ref_dir *dir,
510 const char *refname, int mkdir)
511{
5fa04418 512 const char *slash;
5fa04418 513 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
dd02e728 514 size_t dirnamelen = slash - refname + 1;
3f3aa1bc 515 struct ref_dir *subdir;
dd02e728 516 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
663c1295
JH
517 if (!subdir) {
518 dir = NULL;
f348ac92 519 break;
432ad41e 520 }
3f3aa1bc 521 dir = subdir;
432ad41e
MH
522 }
523
432ad41e
MH
524 return dir;
525}
526
527/*
528 * Find the value entry with the given name in dir, sorting ref_dirs
529 * and recursing into subdirectories as necessary. If the name is not
530 * found or it corresponds to a directory entry, return NULL.
531 */
532static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
533{
9fc0a648 534 int entry_index;
432ad41e
MH
535 struct ref_entry *entry;
536 dir = find_containing_dir(dir, refname, 0);
537 if (!dir)
538 return NULL;
9fc0a648
MH
539 entry_index = search_ref_dir(dir, refname, strlen(refname));
540 if (entry_index == -1)
541 return NULL;
542 entry = dir->entries[entry_index];
543 return (entry->flag & REF_DIR) ? NULL : entry;
432ad41e
MH
544}
545
506a760d
MH
546/*
547 * Remove the entry with the given name from dir, recursing into
548 * subdirectories as necessary. If refname is the name of a directory
549 * (i.e., ends with '/'), then remove the directory and its contents.
550 * If the removal was successful, return the number of entries
551 * remaining in the directory entry that contained the deleted entry.
552 * If the name was not found, return -1. Please note that this
553 * function only deletes the entry from the cache; it does not delete
554 * it from the filesystem or ensure that other cache entries (which
555 * might be symbolic references to the removed entry) are updated.
556 * Nor does it remove any containing dir entries that might be made
557 * empty by the removal. dir must represent the top-level directory
558 * and must already be complete.
559 */
560static int remove_entry(struct ref_dir *dir, const char *refname)
561{
562 int refname_len = strlen(refname);
563 int entry_index;
564 struct ref_entry *entry;
565 int is_dir = refname[refname_len - 1] == '/';
566 if (is_dir) {
567 /*
568 * refname represents a reference directory. Remove
569 * the trailing slash; otherwise we will get the
570 * directory *representing* refname rather than the
571 * one *containing* it.
572 */
573 char *dirname = xmemdupz(refname, refname_len - 1);
574 dir = find_containing_dir(dir, dirname, 0);
575 free(dirname);
576 } else {
577 dir = find_containing_dir(dir, refname, 0);
578 }
579 if (!dir)
580 return -1;
581 entry_index = search_ref_dir(dir, refname, refname_len);
582 if (entry_index == -1)
583 return -1;
584 entry = dir->entries[entry_index];
585
586 memmove(&dir->entries[entry_index],
587 &dir->entries[entry_index + 1],
588 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
589 );
590 dir->nr--;
591 if (dir->sorted > entry_index)
592 dir->sorted--;
593 free_ref_entry(entry);
594 return dir->nr;
432ad41e
MH
595}
596
597/*
598 * Add a ref_entry to the ref_dir (unsorted), recursing into
599 * subdirectories as necessary. dir must represent the top-level
600 * directory. Return 0 on success.
601 */
602static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
603{
604 dir = find_containing_dir(dir, ref->name, 1);
605 if (!dir)
606 return -1;
607 add_entry_to_dir(dir, ref);
608 return 0;
609}
610
202a56a9
MH
611/*
612 * Emit a warning and return true iff ref1 and ref2 have the same name
613 * and the same sha1. Die if they have the same name but different
614 * sha1s.
615 */
616static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
617{
432ad41e 618 if (strcmp(ref1->name, ref2->name))
202a56a9 619 return 0;
432ad41e
MH
620
621 /* Duplicate name; make sure that they don't conflict: */
622
623 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
624 /* This is impossible by construction */
625 die("Reference directory conflict: %s", ref1->name);
626
627 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
628 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
629
630 warning("Duplicated ref: %s", ref1->name);
631 return 1;
202a56a9
MH
632}
633
e6ed3ca6 634/*
432ad41e
MH
635 * Sort the entries in dir non-recursively (if they are not already
636 * sorted) and remove any duplicate entries.
e6ed3ca6 637 */
d3177275 638static void sort_ref_dir(struct ref_dir *dir)
e9c4c111 639{
202a56a9 640 int i, j;
81a79d8e 641 struct ref_entry *last = NULL;
c774aab9 642
e6ed3ca6
MH
643 /*
644 * This check also prevents passing a zero-length array to qsort(),
645 * which is a problem on some platforms.
646 */
d3177275 647 if (dir->sorted == dir->nr)
e9c4c111 648 return;
c774aab9 649
d3177275 650 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
c774aab9 651
81a79d8e
MH
652 /* Remove any duplicates: */
653 for (i = 0, j = 0; j < dir->nr; j++) {
654 struct ref_entry *entry = dir->entries[j];
655 if (last && is_dup_ref(last, entry))
656 free_ref_entry(entry);
657 else
658 last = dir->entries[i++] = entry;
e9c4c111 659 }
81a79d8e 660 dir->sorted = dir->nr = i;
e9c4c111 661}
c774aab9 662
fcce1703
MH
663/* Include broken references in a do_for_each_ref*() iteration: */
664#define DO_FOR_EACH_INCLUDE_BROKEN 0x01
c774aab9 665
662428f4
MH
666/*
667 * Return true iff the reference described by entry can be resolved to
668 * an object in the database. Emit a warning if the referred-to
669 * object does not exist.
670 */
671static int ref_resolves_to_object(struct ref_entry *entry)
672{
673 if (entry->flag & REF_ISBROKEN)
674 return 0;
675 if (!has_sha1_file(entry->u.value.sha1)) {
676 error("%s does not point to a valid object!", entry->name);
677 return 0;
678 }
679 return 1;
680}
c774aab9 681
7d76fdc8
MH
682/*
683 * current_ref is a performance hack: when iterating over references
684 * using the for_each_ref*() functions, current_ref is set to the
685 * current reference's entry before calling the callback function. If
686 * the callback function calls peel_ref(), then peel_ref() first
687 * checks whether the reference to be peeled is the current reference
688 * (it usually is) and if so, returns that reference's peeled version
689 * if it is available. This avoids a refname lookup in a common case.
690 */
bc5fd6d3 691static struct ref_entry *current_ref;
c774aab9 692
624cac35
MH
693typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
694
695struct ref_entry_cb {
696 const char *base;
697 int trim;
698 int flags;
699 each_ref_fn *fn;
700 void *cb_data;
701};
702
fcce1703 703/*
624cac35
MH
704 * Handle one reference in a do_for_each_ref*()-style iteration,
705 * calling an each_ref_fn for each entry.
fcce1703 706 */
624cac35 707static int do_one_ref(struct ref_entry *entry, void *cb_data)
bc5fd6d3 708{
624cac35 709 struct ref_entry_cb *data = cb_data;
d0cf51e9 710 struct ref_entry *old_current_ref;
429213e4 711 int retval;
d0cf51e9 712
59556548 713 if (!starts_with(entry->name, data->base))
bc5fd6d3 714 return 0;
c774aab9 715
624cac35 716 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
662428f4 717 !ref_resolves_to_object(entry))
bc5fd6d3 718 return 0;
c774aab9 719
d0cf51e9
MH
720 /* Store the old value, in case this is a recursive call: */
721 old_current_ref = current_ref;
bc5fd6d3 722 current_ref = entry;
624cac35
MH
723 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
724 entry->flag, data->cb_data);
d0cf51e9 725 current_ref = old_current_ref;
429213e4 726 return retval;
bc5fd6d3 727}
c774aab9 728
c36b5bc2 729/*
d3177275 730 * Call fn for each reference in dir that has index in the range
432ad41e
MH
731 * offset <= index < dir->nr. Recurse into subdirectories that are in
732 * that index range, sorting them before iterating. This function
624cac35
MH
733 * does not sort dir itself; it should be sorted beforehand. fn is
734 * called for all references, including broken ones.
c36b5bc2 735 */
624cac35
MH
736static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
737 each_ref_entry_fn fn, void *cb_data)
c36b5bc2
MH
738{
739 int i;
d3177275
MH
740 assert(dir->sorted == dir->nr);
741 for (i = offset; i < dir->nr; i++) {
432ad41e
MH
742 struct ref_entry *entry = dir->entries[i];
743 int retval;
744 if (entry->flag & REF_DIR) {
d7826d54
MH
745 struct ref_dir *subdir = get_ref_dir(entry);
746 sort_ref_dir(subdir);
624cac35 747 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
432ad41e 748 } else {
624cac35 749 retval = fn(entry, cb_data);
432ad41e 750 }
c36b5bc2
MH
751 if (retval)
752 return retval;
753 }
754 return 0;
755}
756
b3fd060f 757/*
d3177275 758 * Call fn for each reference in the union of dir1 and dir2, in order
432ad41e
MH
759 * by refname. Recurse into subdirectories. If a value entry appears
760 * in both dir1 and dir2, then only process the version that is in
761 * dir2. The input dirs must already be sorted, but subdirs will be
624cac35
MH
762 * sorted as needed. fn is called for all references, including
763 * broken ones.
b3fd060f 764 */
624cac35
MH
765static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
766 struct ref_dir *dir2,
767 each_ref_entry_fn fn, void *cb_data)
b3fd060f
MH
768{
769 int retval;
770 int i1 = 0, i2 = 0;
771
d3177275
MH
772 assert(dir1->sorted == dir1->nr);
773 assert(dir2->sorted == dir2->nr);
432ad41e
MH
774 while (1) {
775 struct ref_entry *e1, *e2;
776 int cmp;
777 if (i1 == dir1->nr) {
624cac35 778 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
432ad41e
MH
779 }
780 if (i2 == dir2->nr) {
624cac35 781 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
432ad41e
MH
782 }
783 e1 = dir1->entries[i1];
784 e2 = dir2->entries[i2];
785 cmp = strcmp(e1->name, e2->name);
786 if (cmp == 0) {
787 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
788 /* Both are directories; descend them in parallel. */
d7826d54
MH
789 struct ref_dir *subdir1 = get_ref_dir(e1);
790 struct ref_dir *subdir2 = get_ref_dir(e2);
791 sort_ref_dir(subdir1);
792 sort_ref_dir(subdir2);
624cac35
MH
793 retval = do_for_each_entry_in_dirs(
794 subdir1, subdir2, fn, cb_data);
432ad41e
MH
795 i1++;
796 i2++;
797 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
798 /* Both are references; ignore the one from dir1. */
624cac35 799 retval = fn(e2, cb_data);
432ad41e
MH
800 i1++;
801 i2++;
802 } else {
803 die("conflict between reference and directory: %s",
804 e1->name);
805 }
b3fd060f 806 } else {
432ad41e
MH
807 struct ref_entry *e;
808 if (cmp < 0) {
809 e = e1;
b3fd060f 810 i1++;
432ad41e
MH
811 } else {
812 e = e2;
813 i2++;
814 }
815 if (e->flag & REF_DIR) {
d7826d54
MH
816 struct ref_dir *subdir = get_ref_dir(e);
817 sort_ref_dir(subdir);
624cac35
MH
818 retval = do_for_each_entry_in_dir(
819 subdir, 0, fn, cb_data);
432ad41e 820 } else {
624cac35 821 retval = fn(e, cb_data);
b3fd060f
MH
822 }
823 }
824 if (retval)
825 return retval;
826 }
b3fd060f
MH
827}
828
98eeb09e
JK
829/*
830 * Load all of the refs from the dir into our in-memory cache. The hard work
831 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
832 * through all of the sub-directories. We do not even need to care about
833 * sorting, as traversal order does not matter to us.
834 */
835static void prime_ref_dir(struct ref_dir *dir)
836{
837 int i;
838 for (i = 0; i < dir->nr; i++) {
839 struct ref_entry *entry = dir->entries[i];
840 if (entry->flag & REF_DIR)
841 prime_ref_dir(get_ref_dir(entry));
842 }
843}
cbe73331 844
5fe7d825 845static int entry_matches(struct ref_entry *entry, const struct string_list *list)
d66da478 846{
5fe7d825 847 return list && string_list_has_string(list, entry->name);
5a4d4947
MH
848}
849
cbe73331 850struct nonmatching_ref_data {
5fe7d825 851 const struct string_list *skip;
cbe73331 852 struct ref_entry *found;
5a4d4947
MH
853};
854
cbe73331 855static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
5a4d4947 856{
cbe73331
JK
857 struct nonmatching_ref_data *data = vdata;
858
859 if (entry_matches(entry, data->skip))
5a4d4947 860 return 0;
cbe73331
JK
861
862 data->found = entry;
863 return 1;
864}
865
866static void report_refname_conflict(struct ref_entry *entry,
867 const char *refname)
868{
869 error("'%s' exists; cannot create '%s'", entry->name, refname);
d66da478
MH
870}
871
bc5fd6d3
MH
872/*
873 * Return true iff a reference named refname could be created without
624cac35 874 * conflicting with the name of an existing reference in dir. If
5fe7d825
RS
875 * skip is non-NULL, ignore potential conflicts with refs in skip
876 * (e.g., because they are scheduled for deletion in the same
bc5fd6d3 877 * operation).
cbe73331
JK
878 *
879 * Two reference names conflict if one of them exactly matches the
880 * leading components of the other; e.g., "foo/bar" conflicts with
881 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
882 * "foo/barbados".
5fe7d825
RS
883 *
884 * skip must be sorted.
bc5fd6d3 885 */
5fe7d825
RS
886static int is_refname_available(const char *refname,
887 const struct string_list *skip,
d3177275 888 struct ref_dir *dir)
bc5fd6d3 889{
cbe73331
JK
890 const char *slash;
891 size_t len;
892 int pos;
893 char *dirname;
5a4d4947 894
cbe73331
JK
895 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
896 /*
897 * We are still at a leading dir of the refname; we are
898 * looking for a conflict with a leaf entry.
899 *
900 * If we find one, we still must make sure it is
5fe7d825 901 * not in "skip".
cbe73331
JK
902 */
903 pos = search_ref_dir(dir, refname, slash - refname);
904 if (pos >= 0) {
905 struct ref_entry *entry = dir->entries[pos];
5fe7d825 906 if (entry_matches(entry, skip))
cbe73331
JK
907 return 1;
908 report_refname_conflict(entry, refname);
909 return 0;
910 }
911
912
913 /*
914 * Otherwise, we can try to continue our search with
915 * the next component; if we come up empty, we know
916 * there is nothing under this whole prefix.
917 */
918 pos = search_ref_dir(dir, refname, slash + 1 - refname);
919 if (pos < 0)
920 return 1;
921
922 dir = get_ref_dir(dir->entries[pos]);
923 }
924
925 /*
926 * We are at the leaf of our refname; we want to
927 * make sure there are no directories which match it.
928 */
929 len = strlen(refname);
930 dirname = xmallocz(len + 1);
931 sprintf(dirname, "%s/", refname);
932 pos = search_ref_dir(dir, dirname, len + 1);
933 free(dirname);
934
935 if (pos >= 0) {
936 /*
937 * We found a directory named "refname". It is a
938 * problem iff it contains any ref that is not
5fe7d825 939 * in "skip".
cbe73331
JK
940 */
941 struct ref_entry *entry = dir->entries[pos];
942 struct ref_dir *dir = get_ref_dir(entry);
943 struct nonmatching_ref_data data;
944
5fe7d825 945 data.skip = skip;
cbe73331
JK
946 sort_ref_dir(dir);
947 if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data))
948 return 1;
949
950 report_refname_conflict(data.found, refname);
5a4d4947 951 return 0;
bc5fd6d3 952 }
cbe73331
JK
953
954 /*
955 * There is no point in searching for another leaf
956 * node which matches it; such an entry would be the
957 * ref we are looking for, not a conflict.
958 */
bc5fd6d3 959 return 1;
e1e22e37
LT
960}
961
2fff7812
MH
962struct packed_ref_cache {
963 struct ref_entry *root;
9f69d297 964
5f5e2a88
MH
965 /*
966 * Count of references to the data structure in this instance,
967 * including the pointer from ref_cache::packed if any. The
968 * data will not be freed as long as the reference count is
969 * nonzero.
970 */
971 unsigned int referrers;
972
9f69d297
MH
973 /*
974 * Iff the packed-refs file associated with this instance is
975 * currently locked for writing, this points at the associated
4f6b83e3
MH
976 * lock (which is owned by somebody else). The referrer count
977 * is also incremented when the file is locked and decremented
978 * when it is unlocked.
9f69d297
MH
979 */
980 struct lock_file *lock;
ca919930
JK
981
982 /* The metadata from when this packed-refs cache was read */
983 struct stat_validity validity;
2fff7812
MH
984};
985
5e290ff7
JH
986/*
987 * Future: need to be in "struct repository"
988 * when doing a full libification.
989 */
79c7ca54
MH
990static struct ref_cache {
991 struct ref_cache *next;
d12229f5 992 struct ref_entry *loose;
2fff7812 993 struct packed_ref_cache *packed;
9da31cb0
MH
994 /*
995 * The submodule name, or "" for the main repo. We allocate
996 * length 1 rather than FLEX_ARRAY so that the main ref_cache
997 * is initialized correctly.
998 */
999 char name[1];
1000} ref_cache, *submodule_ref_caches;
0e88c130 1001
9f69d297
MH
1002/* Lock used for the main packed-refs file: */
1003static struct lock_file packlock;
1004
5f5e2a88
MH
1005/*
1006 * Increment the reference count of *packed_refs.
1007 */
1008static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1009{
1010 packed_refs->referrers++;
1011}
1012
1013/*
1014 * Decrease the reference count of *packed_refs. If it goes to zero,
1015 * free *packed_refs and return true; otherwise return false.
1016 */
1017static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1018{
1019 if (!--packed_refs->referrers) {
1020 free_ref_entry(packed_refs->root);
ca919930 1021 stat_validity_clear(&packed_refs->validity);
5f5e2a88
MH
1022 free(packed_refs);
1023 return 1;
1024 } else {
1025 return 0;
1026 }
1027}
1028
760c4512 1029static void clear_packed_ref_cache(struct ref_cache *refs)
e1e22e37 1030{
d12229f5 1031 if (refs->packed) {
5f5e2a88
MH
1032 struct packed_ref_cache *packed_refs = refs->packed;
1033
1034 if (packed_refs->lock)
9f69d297 1035 die("internal error: packed-ref cache cleared while locked");
d12229f5 1036 refs->packed = NULL;
5f5e2a88 1037 release_packed_ref_cache(packed_refs);
d12229f5 1038 }
5e290ff7 1039}
e1e22e37 1040
760c4512
MH
1041static void clear_loose_ref_cache(struct ref_cache *refs)
1042{
d12229f5
MH
1043 if (refs->loose) {
1044 free_ref_entry(refs->loose);
1045 refs->loose = NULL;
1046 }
760c4512
MH
1047}
1048
79c7ca54 1049static struct ref_cache *create_ref_cache(const char *submodule)
e5dbf605 1050{
ce40979c 1051 int len;
79c7ca54 1052 struct ref_cache *refs;
ce40979c
MH
1053 if (!submodule)
1054 submodule = "";
1055 len = strlen(submodule) + 1;
79c7ca54 1056 refs = xcalloc(1, sizeof(struct ref_cache) + len);
ce40979c 1057 memcpy(refs->name, submodule, len);
e5dbf605
MH
1058 return refs;
1059}
1060
4349a668 1061/*
79c7ca54 1062 * Return a pointer to a ref_cache for the specified submodule. For
4349a668
MH
1063 * the main repository, use submodule==NULL. The returned structure
1064 * will be allocated and initialized but not necessarily populated; it
1065 * should not be freed.
1066 */
79c7ca54 1067static struct ref_cache *get_ref_cache(const char *submodule)
4349a668 1068{
9da31cb0
MH
1069 struct ref_cache *refs;
1070
1071 if (!submodule || !*submodule)
1072 return &ref_cache;
1073
1074 for (refs = submodule_ref_caches; refs; refs = refs->next)
0e88c130
MH
1075 if (!strcmp(submodule, refs->name))
1076 return refs;
0e88c130 1077
79c7ca54 1078 refs = create_ref_cache(submodule);
9da31cb0
MH
1079 refs->next = submodule_ref_caches;
1080 submodule_ref_caches = refs;
0e88c130 1081 return refs;
4349a668
MH
1082}
1083
3feb4f0c
MH
1084/* The length of a peeled reference line in packed-refs, including EOL: */
1085#define PEELED_LINE_LENGTH 42
1086
694b7a19
MH
1087/*
1088 * The packed-refs header line that we write out. Perhaps other
1089 * traits will be added later. The trailing space is required.
1090 */
1091static const char PACKED_REFS_HEADER[] =
1092 "# pack-refs with: peeled fully-peeled \n";
1093
bc5fd6d3
MH
1094/*
1095 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1096 * Return a pointer to the refname within the line (null-terminated),
1097 * or NULL if there was a problem.
1098 */
6a49870a 1099static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
bc5fd6d3 1100{
6a49870a
JK
1101 const char *ref;
1102
bc5fd6d3
MH
1103 /*
1104 * 42: the answer to everything.
1105 *
1106 * In this case, it happens to be the answer to
1107 * 40 (length of sha1 hex representation)
1108 * +1 (space in between hex and name)
1109 * +1 (newline at the end of the line)
1110 */
6a49870a 1111 if (line->len <= 42)
bc5fd6d3 1112 return NULL;
6a49870a
JK
1113
1114 if (get_sha1_hex(line->buf, sha1) < 0)
bc5fd6d3 1115 return NULL;
6a49870a 1116 if (!isspace(line->buf[40]))
bc5fd6d3 1117 return NULL;
6a49870a
JK
1118
1119 ref = line->buf + 41;
1120 if (isspace(*ref))
bc5fd6d3 1121 return NULL;
6a49870a
JK
1122
1123 if (line->buf[line->len - 1] != '\n')
bc5fd6d3 1124 return NULL;
6a49870a 1125 line->buf[--line->len] = 0;
bc5fd6d3 1126
6a49870a 1127 return ref;
bc5fd6d3
MH
1128}
1129
c29c46fa
MH
1130/*
1131 * Read f, which is a packed-refs file, into dir.
1132 *
1133 * A comment line of the form "# pack-refs with: " may contain zero or
1134 * more traits. We interpret the traits as follows:
1135 *
1136 * No traits:
1137 *
1138 * Probably no references are peeled. But if the file contains a
1139 * peeled value for a reference, we will use it.
1140 *
1141 * peeled:
1142 *
1143 * References under "refs/tags/", if they *can* be peeled, *are*
1144 * peeled in this file. References outside of "refs/tags/" are
1145 * probably not peeled even if they could have been, but if we find
1146 * a peeled value for such a reference we will use it.
1147 *
1148 * fully-peeled:
1149 *
1150 * All references in the file that can be peeled are peeled.
1151 * Inversely (and this is more important), any references in the
1152 * file for which no peeled value is recorded is not peelable. This
1153 * trait should typically be written alongside "peeled" for
1154 * compatibility with older clients, but we do not require it
1155 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1156 */
d3177275 1157static void read_packed_refs(FILE *f, struct ref_dir *dir)
f4204ab9 1158{
e9c4c111 1159 struct ref_entry *last = NULL;
10c497aa 1160 struct strbuf line = STRBUF_INIT;
c29c46fa 1161 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
f4204ab9 1162
10c497aa 1163 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
f4204ab9 1164 unsigned char sha1[20];
dfefa935 1165 const char *refname;
ea417833 1166 const char *traits;
f4204ab9 1167
ea417833 1168 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
c29c46fa
MH
1169 if (strstr(traits, " fully-peeled "))
1170 peeled = PEELED_FULLY;
1171 else if (strstr(traits, " peeled "))
1172 peeled = PEELED_TAGS;
f4204ab9
JH
1173 /* perhaps other traits later as well */
1174 continue;
1175 }
1176
6a49870a 1177 refname = parse_ref_line(&line, sha1);
dfefa935 1178 if (refname) {
d0f810f0
RS
1179 int flag = REF_ISPACKED;
1180
1181 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1182 hashclr(sha1);
1183 flag |= REF_BAD_NAME | REF_ISBROKEN;
1184 }
1185 last = create_ref_entry(refname, sha1, flag, 0);
c29c46fa 1186 if (peeled == PEELED_FULLY ||
59556548 1187 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
c29c46fa 1188 last->flag |= REF_KNOWS_PEELED;
d3177275 1189 add_ref(dir, last);
f4204ab9
JH
1190 continue;
1191 }
1192 if (last &&
10c497aa
JK
1193 line.buf[0] == '^' &&
1194 line.len == PEELED_LINE_LENGTH &&
1195 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1196 !get_sha1_hex(line.buf + 1, sha1)) {
593f1bb8 1197 hashcpy(last->u.value.peeled, sha1);
c29c46fa
MH
1198 /*
1199 * Regardless of what the file header said,
1200 * we definitely know the value of *this*
1201 * reference:
1202 */
1203 last->flag |= REF_KNOWS_PEELED;
1204 }
f4204ab9 1205 }
10c497aa
JK
1206
1207 strbuf_release(&line);
f4204ab9
JH
1208}
1209
2fff7812
MH
1210/*
1211 * Get the packed_ref_cache for the specified ref_cache, creating it
1212 * if necessary.
1213 */
1214static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
5e290ff7 1215{
ca919930
JK
1216 const char *packed_refs_file;
1217
1218 if (*refs->name)
1219 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1220 else
1221 packed_refs_file = git_path("packed-refs");
1222
1223 if (refs->packed &&
1224 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1225 clear_packed_ref_cache(refs);
1226
d12229f5 1227 if (!refs->packed) {
4349a668 1228 FILE *f;
0bad611b 1229
2fff7812 1230 refs->packed = xcalloc(1, sizeof(*refs->packed));
5f5e2a88 1231 acquire_packed_ref_cache(refs->packed);
2fff7812 1232 refs->packed->root = create_dir_entry(refs, "", 0, 0);
4349a668 1233 f = fopen(packed_refs_file, "r");
e1e22e37 1234 if (f) {
ca919930 1235 stat_validity_update(&refs->packed->validity, fileno(f));
2fff7812 1236 read_packed_refs(f, get_ref_dir(refs->packed->root));
e1e22e37 1237 fclose(f);
e1e22e37 1238 }
e1e22e37 1239 }
2fff7812
MH
1240 return refs->packed;
1241}
1242
1243static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1244{
1245 return get_ref_dir(packed_ref_cache->root);
1246}
1247
1248static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1249{
1250 return get_packed_ref_dir(get_packed_ref_cache(refs));
e1e22e37
LT
1251}
1252
30249ee6
MH
1253void add_packed_ref(const char *refname, const unsigned char *sha1)
1254{
9f69d297
MH
1255 struct packed_ref_cache *packed_ref_cache =
1256 get_packed_ref_cache(&ref_cache);
1257
1258 if (!packed_ref_cache->lock)
1259 die("internal error: packed refs not locked");
1260 add_ref(get_packed_ref_dir(packed_ref_cache),
9da31cb0 1261 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
30249ee6
MH
1262}
1263
abc39098 1264/*
28e6a34e
MH
1265 * Read the loose references from the namespace dirname into dir
1266 * (without recursing). dirname must end with '/'. dir must be the
1267 * directory entry corresponding to dirname.
abc39098 1268 */
423a1afc 1269static void read_loose_refs(const char *dirname, struct ref_dir *dir)
e1e22e37 1270{
423a1afc 1271 struct ref_cache *refs = dir->ref_cache;
d3177275 1272 DIR *d;
0bad611b 1273 const char *path;
d5fdae67 1274 struct dirent *de;
abc39098 1275 int dirnamelen = strlen(dirname);
72b64b44 1276 struct strbuf refname;
0bad611b 1277
3b124823 1278 if (*refs->name)
66a3d20b 1279 path = git_path_submodule(refs->name, "%s", dirname);
0bad611b 1280 else
66a3d20b 1281 path = git_path("%s", dirname);
0bad611b 1282
d3177275 1283 d = opendir(path);
d5fdae67
MH
1284 if (!d)
1285 return;
1286
66a3d20b
MH
1287 strbuf_init(&refname, dirnamelen + 257);
1288 strbuf_add(&refname, dirname, dirnamelen);
d5fdae67
MH
1289
1290 while ((de = readdir(d)) != NULL) {
1291 unsigned char sha1[20];
1292 struct stat st;
1293 int flag;
d5fdae67
MH
1294 const char *refdir;
1295
1296 if (de->d_name[0] == '.')
1297 continue;
2975c770 1298 if (ends_with(de->d_name, ".lock"))
d5fdae67 1299 continue;
72b64b44 1300 strbuf_addstr(&refname, de->d_name);
d5fdae67 1301 refdir = *refs->name
72b64b44
MH
1302 ? git_path_submodule(refs->name, "%s", refname.buf)
1303 : git_path("%s", refname.buf);
1304 if (stat(refdir, &st) < 0) {
1305 ; /* silently ignore */
1306 } else if (S_ISDIR(st.st_mode)) {
abc39098 1307 strbuf_addch(&refname, '/');
28e6a34e 1308 add_entry_to_dir(dir,
b9146f51
RS
1309 create_dir_entry(refs, refname.buf,
1310 refname.len, 1));
72b64b44 1311 } else {
3b124823 1312 if (*refs->name) {
f8948e2f 1313 hashclr(sha1);
0bad611b 1314 flag = 0;
72b64b44 1315 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
0bad611b 1316 hashclr(sha1);
98ac34b2 1317 flag |= REF_ISBROKEN;
0bad611b 1318 }
7695d118
RS
1319 } else if (read_ref_full(refname.buf,
1320 RESOLVE_REF_READING,
1321 sha1, &flag)) {
09116a1c
JH
1322 hashclr(sha1);
1323 flag |= REF_ISBROKEN;
1324 }
d0f810f0
RS
1325 if (check_refname_format(refname.buf,
1326 REFNAME_ALLOW_ONELEVEL)) {
1327 hashclr(sha1);
1328 flag |= REF_BAD_NAME | REF_ISBROKEN;
1329 }
9f2fb4a3 1330 add_entry_to_dir(dir,
d0f810f0 1331 create_ref_entry(refname.buf, sha1, flag, 0));
e1e22e37 1332 }
66a3d20b 1333 strbuf_setlen(&refname, dirnamelen);
e1e22e37 1334 }
72b64b44 1335 strbuf_release(&refname);
d5fdae67 1336 closedir(d);
e1e22e37
LT
1337}
1338
d3177275 1339static struct ref_dir *get_loose_refs(struct ref_cache *refs)
e1e22e37 1340{
d12229f5 1341 if (!refs->loose) {
28e6a34e
MH
1342 /*
1343 * Mark the top-level directory complete because we
1344 * are about to read the only subdirectory that can
1345 * hold references:
1346 */
b9146f51 1347 refs->loose = create_dir_entry(refs, "", 0, 0);
28e6a34e
MH
1348 /*
1349 * Create an incomplete entry for "refs/":
1350 */
1351 add_entry_to_dir(get_ref_dir(refs->loose),
b9146f51 1352 create_dir_entry(refs, "refs/", 5, 1));
e1e22e37 1353 }
d7826d54 1354 return get_ref_dir(refs->loose);
e1e22e37
LT
1355}
1356
ca8db142
LT
1357/* We allow "recursive" symbolic refs. Only within reason, though */
1358#define MAXDEPTH 5
0ebde32c
LT
1359#define MAXREFLEN (1024)
1360
e5fa45c1
JH
1361/*
1362 * Called by resolve_gitlink_ref_recursive() after it failed to read
b0626608
MH
1363 * from the loose refs in ref_cache refs. Find <refname> in the
1364 * packed-refs file for the submodule.
e5fa45c1 1365 */
b0626608 1366static int resolve_gitlink_packed_ref(struct ref_cache *refs,
85be1fe3 1367 const char *refname, unsigned char *sha1)
0ebde32c 1368{
2c5c66be 1369 struct ref_entry *ref;
d3177275 1370 struct ref_dir *dir = get_packed_refs(refs);
0ebde32c 1371
432ad41e 1372 ref = find_ref(dir, refname);
b0626608
MH
1373 if (ref == NULL)
1374 return -1;
1375
50546b15 1376 hashcpy(sha1, ref->u.value.sha1);
b0626608 1377 return 0;
0ebde32c
LT
1378}
1379
b0626608 1380static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
85be1fe3 1381 const char *refname, unsigned char *sha1,
dfefa935 1382 int recursion)
0ebde32c 1383{
064d51dc 1384 int fd, len;
0ebde32c 1385 char buffer[128], *p;
064d51dc 1386 char *path;
0ebde32c 1387
064d51dc 1388 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
0ebde32c 1389 return -1;
064d51dc
MH
1390 path = *refs->name
1391 ? git_path_submodule(refs->name, "%s", refname)
1392 : git_path("%s", refname);
1393 fd = open(path, O_RDONLY);
0ebde32c 1394 if (fd < 0)
b0626608 1395 return resolve_gitlink_packed_ref(refs, refname, sha1);
0ebde32c
LT
1396
1397 len = read(fd, buffer, sizeof(buffer)-1);
1398 close(fd);
1399 if (len < 0)
1400 return -1;
1401 while (len && isspace(buffer[len-1]))
1402 len--;
1403 buffer[len] = 0;
1404
1405 /* Was it a detached head or an old-fashioned symlink? */
85be1fe3 1406 if (!get_sha1_hex(buffer, sha1))
0ebde32c
LT
1407 return 0;
1408
1409 /* Symref? */
1410 if (strncmp(buffer, "ref:", 4))
1411 return -1;
1412 p = buffer + 4;
1413 while (isspace(*p))
1414 p++;
1415
064d51dc 1416 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
0ebde32c
LT
1417}
1418
85be1fe3 1419int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
0ebde32c
LT
1420{
1421 int len = strlen(path), retval;
064d51dc 1422 char *submodule;
b0626608 1423 struct ref_cache *refs;
0ebde32c
LT
1424
1425 while (len && path[len-1] == '/')
1426 len--;
1427 if (!len)
1428 return -1;
b0626608
MH
1429 submodule = xstrndup(path, len);
1430 refs = get_ref_cache(submodule);
1431 free(submodule);
1432
064d51dc 1433 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
0ebde32c
LT
1434 return retval;
1435}
ca8db142 1436
4886b89f 1437/*
63331581
MH
1438 * Return the ref_entry for the given refname from the packed
1439 * references. If it does not exist, return NULL.
4886b89f 1440 */
63331581 1441static struct ref_entry *get_packed_ref(const char *refname)
c224ca7f 1442{
9da31cb0 1443 return find_ref(get_packed_refs(&ref_cache), refname);
c224ca7f
MH
1444}
1445
47f534bf
MH
1446/*
1447 * A loose ref file doesn't exist; check for a packed ref. The
1448 * options are forwarded from resolve_safe_unsafe().
1449 */
d0f810f0
RS
1450static int resolve_missing_loose_ref(const char *refname,
1451 int resolve_flags,
1452 unsigned char *sha1,
1453 int *flags)
47f534bf
MH
1454{
1455 struct ref_entry *entry;
1456
1457 /*
1458 * The loose reference file does not exist; check for a packed
1459 * reference.
1460 */
1461 entry = get_packed_ref(refname);
1462 if (entry) {
1463 hashcpy(sha1, entry->u.value.sha1);
7695d118
RS
1464 if (flags)
1465 *flags |= REF_ISPACKED;
d0f810f0 1466 return 0;
47f534bf
MH
1467 }
1468 /* The reference is not a packed reference, either. */
7695d118 1469 if (resolve_flags & RESOLVE_REF_READING) {
d0f810f0
RS
1470 errno = ENOENT;
1471 return -1;
47f534bf
MH
1472 } else {
1473 hashclr(sha1);
d0f810f0 1474 return 0;
47f534bf
MH
1475 }
1476}
1477
76d70dc0 1478/* This function needs to return a meaningful errno on failure */
7695d118 1479const char *resolve_ref_unsafe(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
8a65ff76 1480{
0104ca09
HO
1481 int depth = MAXDEPTH;
1482 ssize_t len;
a876ed83 1483 char buffer[256];
dfefa935 1484 static char refname_buffer[256];
d0f810f0 1485 int bad_name = 0;
ca8db142 1486
7695d118
RS
1487 if (flags)
1488 *flags = 0;
8da19775 1489
76d70dc0 1490 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
d0f810f0
RS
1491 if (flags)
1492 *flags |= REF_BAD_NAME;
1493
1494 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1495 !refname_is_safe(refname)) {
1496 errno = EINVAL;
1497 return NULL;
1498 }
1499 /*
1500 * dwim_ref() uses REF_ISBROKEN to distinguish between
1501 * missing refs and refs that were present but invalid,
1502 * to complain about the latter to stderr.
1503 *
1504 * We don't know whether the ref exists, so don't set
1505 * REF_ISBROKEN yet.
1506 */
1507 bad_name = 1;
76d70dc0 1508 }
a876ed83 1509 for (;;) {
55956350 1510 char path[PATH_MAX];
a876ed83
JH
1511 struct stat st;
1512 char *buf;
1513 int fd;
8a65ff76 1514
76d70dc0
RS
1515 if (--depth < 0) {
1516 errno = ELOOP;
a876ed83 1517 return NULL;
76d70dc0 1518 }
ca8db142 1519
dfefa935 1520 git_snpath(path, sizeof(path), "%s", refname);
c224ca7f 1521
fcb7c762
MH
1522 /*
1523 * We might have to loop back here to avoid a race
1524 * condition: first we lstat() the file, then we try
1525 * to read it as a link or as a file. But if somebody
1526 * changes the type of the file (file <-> directory
1527 * <-> symlink) between the lstat() and reading, then
1528 * we don't want to report that as an error but rather
1529 * try again starting with the lstat().
1530 */
1531 stat_ref:
a876ed83 1532 if (lstat(path, &st) < 0) {
d0f810f0
RS
1533 if (errno != ENOENT)
1534 return NULL;
1535 if (resolve_missing_loose_ref(refname, resolve_flags,
1536 sha1, flags))
a876ed83 1537 return NULL;
d0f810f0
RS
1538 if (bad_name) {
1539 hashclr(sha1);
1540 if (flags)
1541 *flags |= REF_ISBROKEN;
1542 }
1543 return refname;
a876ed83 1544 }
ca8db142 1545
a876ed83
JH
1546 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1547 if (S_ISLNK(st.st_mode)) {
1548 len = readlink(path, buffer, sizeof(buffer)-1);
fcb7c762
MH
1549 if (len < 0) {
1550 if (errno == ENOENT || errno == EINVAL)
1551 /* inconsistent with lstat; retry */
1552 goto stat_ref;
1553 else
1554 return NULL;
1555 }
b54cb795 1556 buffer[len] = 0;
59556548 1557 if (starts_with(buffer, "refs/") &&
1f58a038 1558 !check_refname_format(buffer, 0)) {
dfefa935
MH
1559 strcpy(refname_buffer, buffer);
1560 refname = refname_buffer;
7695d118
RS
1561 if (flags)
1562 *flags |= REF_ISSYMREF;
62a2d525
JN
1563 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1564 hashclr(sha1);
1565 return refname;
1566 }
a876ed83
JH
1567 continue;
1568 }
ca8db142 1569 }
a876ed83 1570
7a21632f
DS
1571 /* Is it a directory? */
1572 if (S_ISDIR(st.st_mode)) {
1573 errno = EISDIR;
1574 return NULL;
1575 }
1576
a876ed83
JH
1577 /*
1578 * Anything else, just open it and try to use it as
1579 * a ref
1580 */
1581 fd = open(path, O_RDONLY);
fcb7c762
MH
1582 if (fd < 0) {
1583 if (errno == ENOENT)
1584 /* inconsistent with lstat; retry */
1585 goto stat_ref;
1586 else
1587 return NULL;
1588 }
93d26e4c 1589 len = read_in_full(fd, buffer, sizeof(buffer)-1);
76d70dc0
RS
1590 if (len < 0) {
1591 int save_errno = errno;
1592 close(fd);
1593 errno = save_errno;
28775050 1594 return NULL;
76d70dc0
RS
1595 }
1596 close(fd);
28775050
MH
1597 while (len && isspace(buffer[len-1]))
1598 len--;
1599 buffer[len] = '\0';
a876ed83
JH
1600
1601 /*
1602 * Is it a symbolic ref?
1603 */
59556548 1604 if (!starts_with(buffer, "ref:")) {
2884c06a
MH
1605 /*
1606 * Please note that FETCH_HEAD has a second
1607 * line containing other data.
1608 */
1609 if (get_sha1_hex(buffer, sha1) ||
1610 (buffer[40] != '\0' && !isspace(buffer[40]))) {
7695d118
RS
1611 if (flags)
1612 *flags |= REF_ISBROKEN;
76d70dc0 1613 errno = EINVAL;
2884c06a
MH
1614 return NULL;
1615 }
d0f810f0
RS
1616 if (bad_name) {
1617 hashclr(sha1);
1618 if (flags)
1619 *flags |= REF_ISBROKEN;
1620 }
2884c06a
MH
1621 return refname;
1622 }
7695d118
RS
1623 if (flags)
1624 *flags |= REF_ISSYMREF;
a876ed83 1625 buf = buffer + 4;
28775050
MH
1626 while (isspace(*buf))
1627 buf++;
62a2d525
JN
1628 refname = strcpy(refname_buffer, buf);
1629 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1630 hashclr(sha1);
1631 return refname;
1632 }
313fb010 1633 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
7695d118
RS
1634 if (flags)
1635 *flags |= REF_ISBROKEN;
d0f810f0
RS
1636
1637 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1638 !refname_is_safe(buf)) {
1639 errno = EINVAL;
1640 return NULL;
1641 }
1642 bad_name = 1;
313fb010 1643 }
8a65ff76 1644 }
a876ed83
JH
1645}
1646
7695d118 1647char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)
96ec7b1e 1648{
092c4be7 1649 return xstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));
96ec7b1e
NTND
1650}
1651
d08bae7e
IL
1652/* The argument to filter_refs */
1653struct ref_filter {
1654 const char *pattern;
1655 each_ref_fn *fn;
1656 void *cb_data;
1657};
1658
7695d118 1659int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
a876ed83 1660{
7695d118 1661 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
a876ed83
JH
1662 return 0;
1663 return -1;
8a65ff76
LT
1664}
1665
dfefa935 1666int read_ref(const char *refname, unsigned char *sha1)
c6893323 1667{
7695d118 1668 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
c6893323
NTND
1669}
1670
bc5fd6d3 1671int ref_exists(const char *refname)
ef06b918 1672{
bc5fd6d3 1673 unsigned char sha1[20];
7695d118 1674 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
ef06b918
JH
1675}
1676
85be1fe3 1677static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
dfefa935 1678 void *data)
d08bae7e
IL
1679{
1680 struct ref_filter *filter = (struct ref_filter *)data;
eb07894f 1681 if (wildmatch(filter->pattern, refname, 0, NULL))
d08bae7e 1682 return 0;
85be1fe3 1683 return filter->fn(refname, sha1, flags, filter->cb_data);
d08bae7e
IL
1684}
1685
68cf8703
MH
1686enum peel_status {
1687 /* object was peeled successfully: */
1688 PEEL_PEELED = 0,
1689
1690 /*
1691 * object cannot be peeled because the named object (or an
1692 * object referred to by a tag in the peel chain), does not
1693 * exist.
1694 */
1695 PEEL_INVALID = -1,
1696
1697 /* object cannot be peeled because it is not a tag: */
9a489f3c
MH
1698 PEEL_NON_TAG = -2,
1699
1700 /* ref_entry contains no peeled value because it is a symref: */
1701 PEEL_IS_SYMREF = -3,
1702
1703 /*
1704 * ref_entry cannot be peeled because it is broken (i.e., the
1705 * symbolic reference cannot even be resolved to an object
1706 * name):
1707 */
1708 PEEL_BROKEN = -4
68cf8703
MH
1709};
1710
cb2ae1c4
MH
1711/*
1712 * Peel the named object; i.e., if the object is a tag, resolve the
68cf8703
MH
1713 * tag recursively until a non-tag is found. If successful, store the
1714 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1715 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1716 * and leave sha1 unchanged.
cb2ae1c4 1717 */
68cf8703 1718static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
cb2ae1c4
MH
1719{
1720 struct object *o = lookup_unknown_object(name);
1721
1722 if (o->type == OBJ_NONE) {
1723 int type = sha1_object_info(name, NULL);
8ff226a9 1724 if (type < 0 || !object_as_type(o, type, 0))
68cf8703 1725 return PEEL_INVALID;
cb2ae1c4
MH
1726 }
1727
1728 if (o->type != OBJ_TAG)
68cf8703 1729 return PEEL_NON_TAG;
cb2ae1c4
MH
1730
1731 o = deref_tag_noverify(o);
1732 if (!o)
68cf8703 1733 return PEEL_INVALID;
cb2ae1c4
MH
1734
1735 hashcpy(sha1, o->sha1);
68cf8703 1736 return PEEL_PEELED;
cb2ae1c4
MH
1737}
1738
9a489f3c 1739/*
f85354b5
MH
1740 * Peel the entry (if possible) and return its new peel_status. If
1741 * repeel is true, re-peel the entry even if there is an old peeled
1742 * value that is already stored in it.
694b7a19
MH
1743 *
1744 * It is OK to call this function with a packed reference entry that
1745 * might be stale and might even refer to an object that has since
1746 * been garbage-collected. In such a case, if the entry has
1747 * REF_KNOWS_PEELED then leave the status unchanged and return
1748 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
9a489f3c 1749 */
f85354b5 1750static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
9a489f3c
MH
1751{
1752 enum peel_status status;
1753
f85354b5
MH
1754 if (entry->flag & REF_KNOWS_PEELED) {
1755 if (repeel) {
1756 entry->flag &= ~REF_KNOWS_PEELED;
1757 hashclr(entry->u.value.peeled);
1758 } else {
1759 return is_null_sha1(entry->u.value.peeled) ?
1760 PEEL_NON_TAG : PEEL_PEELED;
1761 }
1762 }
9a489f3c
MH
1763 if (entry->flag & REF_ISBROKEN)
1764 return PEEL_BROKEN;
1765 if (entry->flag & REF_ISSYMREF)
1766 return PEEL_IS_SYMREF;
1767
1768 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1769 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1770 entry->flag |= REF_KNOWS_PEELED;
1771 return status;
1772}
1773
dfefa935 1774int peel_ref(const char *refname, unsigned char *sha1)
cf0adba7
JH
1775{
1776 int flag;
1777 unsigned char base[20];
cf0adba7 1778
dfefa935 1779 if (current_ref && (current_ref->name == refname
9a489f3c 1780 || !strcmp(current_ref->name, refname))) {
f85354b5 1781 if (peel_entry(current_ref, 0))
9a489f3c
MH
1782 return -1;
1783 hashcpy(sha1, current_ref->u.value.peeled);
1784 return 0;
0ae91be0
SP
1785 }
1786
7695d118 1787 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
cf0adba7
JH
1788 return -1;
1789
9a489f3c
MH
1790 /*
1791 * If the reference is packed, read its ref_entry from the
1792 * cache in the hope that we already know its peeled value.
1793 * We only try this optimization on packed references because
1794 * (a) forcing the filling of the loose reference cache could
1795 * be expensive and (b) loose references anyway usually do not
1796 * have REF_KNOWS_PEELED.
1797 */
1798 if (flag & REF_ISPACKED) {
f361baeb 1799 struct ref_entry *r = get_packed_ref(refname);
9a489f3c 1800 if (r) {
f85354b5 1801 if (peel_entry(r, 0))
9a489f3c 1802 return -1;
593f1bb8 1803 hashcpy(sha1, r->u.value.peeled);
e9c4c111 1804 return 0;
cf0adba7 1805 }
cf0adba7
JH
1806 }
1807
cb2ae1c4 1808 return peel_object(base, sha1);
cf0adba7
JH
1809}
1810
bc5fd6d3
MH
1811struct warn_if_dangling_data {
1812 FILE *fp;
1813 const char *refname;
e6bea66d 1814 const struct string_list *refnames;
bc5fd6d3
MH
1815 const char *msg_fmt;
1816};
1817
1818static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1819 int flags, void *cb_data)
1820{
1821 struct warn_if_dangling_data *d = cb_data;
1822 const char *resolves_to;
1823 unsigned char junk[20];
1824
1825 if (!(flags & REF_ISSYMREF))
1826 return 0;
1827
7695d118 1828 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);
e6bea66d
JL
1829 if (!resolves_to
1830 || (d->refname
1831 ? strcmp(resolves_to, d->refname)
1832 : !string_list_has_string(d->refnames, resolves_to))) {
bc5fd6d3 1833 return 0;
e6bea66d 1834 }
bc5fd6d3
MH
1835
1836 fprintf(d->fp, d->msg_fmt, refname);
1be65eda 1837 fputc('\n', d->fp);
bc5fd6d3
MH
1838 return 0;
1839}
1840
1841void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1842{
1843 struct warn_if_dangling_data data;
1844
1845 data.fp = fp;
1846 data.refname = refname;
e6bea66d
JL
1847 data.refnames = NULL;
1848 data.msg_fmt = msg_fmt;
1849 for_each_rawref(warn_if_dangling_symref, &data);
1850}
1851
1852void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1853{
1854 struct warn_if_dangling_data data;
1855
1856 data.fp = fp;
1857 data.refname = NULL;
1858 data.refnames = refnames;
bc5fd6d3
MH
1859 data.msg_fmt = msg_fmt;
1860 for_each_rawref(warn_if_dangling_symref, &data);
1861}
1862
fcce1703 1863/*
65cf102b 1864 * Call fn for each reference in the specified ref_cache, omitting
624cac35
MH
1865 * references not in the containing_dir of base. fn is called for all
1866 * references, including broken ones. If fn ever returns a non-zero
fcce1703
MH
1867 * value, stop the iteration and return that value; otherwise, return
1868 * 0.
1869 */
65cf102b 1870static int do_for_each_entry(struct ref_cache *refs, const char *base,
624cac35 1871 each_ref_entry_fn fn, void *cb_data)
8a65ff76 1872{
98eeb09e
JK
1873 struct packed_ref_cache *packed_ref_cache;
1874 struct ref_dir *loose_dir;
1875 struct ref_dir *packed_dir;
933ac036
MH
1876 int retval = 0;
1877
98eeb09e
JK
1878 /*
1879 * We must make sure that all loose refs are read before accessing the
1880 * packed-refs file; this avoids a race condition in which loose refs
1881 * are migrated to the packed-refs file by a simultaneous process, but
1882 * our in-memory view is from before the migration. get_packed_ref_cache()
1883 * takes care of making sure our view is up to date with what is on
1884 * disk.
1885 */
1886 loose_dir = get_loose_refs(refs);
933ac036 1887 if (base && *base) {
933ac036
MH
1888 loose_dir = find_containing_dir(loose_dir, base, 0);
1889 }
98eeb09e
JK
1890 if (loose_dir)
1891 prime_ref_dir(loose_dir);
1892
1893 packed_ref_cache = get_packed_ref_cache(refs);
8baf2bb9 1894 acquire_packed_ref_cache(packed_ref_cache);
98eeb09e 1895 packed_dir = get_packed_ref_dir(packed_ref_cache);
933ac036
MH
1896 if (base && *base) {
1897 packed_dir = find_containing_dir(packed_dir, base, 0);
933ac036
MH
1898 }
1899
1900 if (packed_dir && loose_dir) {
1901 sort_ref_dir(packed_dir);
1902 sort_ref_dir(loose_dir);
624cac35
MH
1903 retval = do_for_each_entry_in_dirs(
1904 packed_dir, loose_dir, fn, cb_data);
933ac036
MH
1905 } else if (packed_dir) {
1906 sort_ref_dir(packed_dir);
624cac35
MH
1907 retval = do_for_each_entry_in_dir(
1908 packed_dir, 0, fn, cb_data);
933ac036
MH
1909 } else if (loose_dir) {
1910 sort_ref_dir(loose_dir);
624cac35
MH
1911 retval = do_for_each_entry_in_dir(
1912 loose_dir, 0, fn, cb_data);
933ac036
MH
1913 }
1914
8baf2bb9 1915 release_packed_ref_cache(packed_ref_cache);
933ac036 1916 return retval;
8a65ff76
LT
1917}
1918
624cac35 1919/*
65cf102b 1920 * Call fn for each reference in the specified ref_cache for which the
624cac35
MH
1921 * refname begins with base. If trim is non-zero, then trim that many
1922 * characters off the beginning of each refname before passing the
1923 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1924 * broken references in the iteration. If fn ever returns a non-zero
1925 * value, stop the iteration and return that value; otherwise, return
1926 * 0.
1927 */
65cf102b
MH
1928static int do_for_each_ref(struct ref_cache *refs, const char *base,
1929 each_ref_fn fn, int trim, int flags, void *cb_data)
624cac35
MH
1930{
1931 struct ref_entry_cb data;
1932 data.base = base;
1933 data.trim = trim;
1934 data.flags = flags;
1935 data.fn = fn;
1936 data.cb_data = cb_data;
1937
65cf102b 1938 return do_for_each_entry(refs, base, do_one_ref, &data);
624cac35
MH
1939}
1940
0bad611b 1941static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
723c31fe
LT
1942{
1943 unsigned char sha1[20];
8da19775
JH
1944 int flag;
1945
0bad611b
HV
1946 if (submodule) {
1947 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1948 return fn("HEAD", sha1, 0, cb_data);
1949
1950 return 0;
1951 }
1952
7695d118 1953 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))
8da19775 1954 return fn("HEAD", sha1, flag, cb_data);
0bad611b 1955
2f34ba32 1956 return 0;
723c31fe
LT
1957}
1958
0bad611b
HV
1959int head_ref(each_ref_fn fn, void *cb_data)
1960{
1961 return do_head_ref(NULL, fn, cb_data);
1962}
1963
9ef6aeb0
HV
1964int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1965{
1966 return do_head_ref(submodule, fn, cb_data);
1967}
1968
cb5d709f 1969int for_each_ref(each_ref_fn fn, void *cb_data)
8a65ff76 1970{
9da31cb0 1971 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
a62be77f
SE
1972}
1973
9ef6aeb0
HV
1974int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1975{
65cf102b 1976 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
a62be77f
SE
1977}
1978
2a8177b6
CC
1979int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1980{
9da31cb0 1981 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2a8177b6
CC
1982}
1983
9ef6aeb0
HV
1984int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1985 each_ref_fn fn, void *cb_data)
1986{
65cf102b 1987 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2a8177b6
CC
1988}
1989
cb5d709f 1990int for_each_tag_ref(each_ref_fn fn, void *cb_data)
a62be77f 1991{
2a8177b6 1992 return for_each_ref_in("refs/tags/", fn, cb_data);
a62be77f
SE
1993}
1994
9ef6aeb0
HV
1995int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1996{
1997 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1998}
1999
cb5d709f 2000int for_each_branch_ref(each_ref_fn fn, void *cb_data)
a62be77f 2001{
2a8177b6 2002 return for_each_ref_in("refs/heads/", fn, cb_data);
a62be77f
SE
2003}
2004
9ef6aeb0
HV
2005int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2006{
2007 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2008}
2009
cb5d709f 2010int for_each_remote_ref(each_ref_fn fn, void *cb_data)
a62be77f 2011{
2a8177b6 2012 return for_each_ref_in("refs/remotes/", fn, cb_data);
f8948e2f
JH
2013}
2014
9ef6aeb0
HV
2015int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2016{
2017 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2018}
2019
29268700
CC
2020int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2021{
9da31cb0 2022 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
29268700
CC
2023}
2024
a1bea2c1
JT
2025int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2026{
2027 struct strbuf buf = STRBUF_INIT;
2028 int ret = 0;
2029 unsigned char sha1[20];
2030 int flag;
2031
2032 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
7695d118 2033 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))
a1bea2c1
JT
2034 ret = fn(buf.buf, sha1, flag, cb_data);
2035 strbuf_release(&buf);
2036
2037 return ret;
2038}
2039
2040int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2041{
2042 struct strbuf buf = STRBUF_INIT;
2043 int ret;
2044 strbuf_addf(&buf, "%srefs/", get_git_namespace());
9da31cb0 2045 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
a1bea2c1
JT
2046 strbuf_release(&buf);
2047 return ret;
2048}
2049
b09fe971
IL
2050int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2051 const char *prefix, void *cb_data)
d08bae7e
IL
2052{
2053 struct strbuf real_pattern = STRBUF_INIT;
2054 struct ref_filter filter;
d08bae7e
IL
2055 int ret;
2056
59556548 2057 if (!prefix && !starts_with(pattern, "refs/"))
d08bae7e 2058 strbuf_addstr(&real_pattern, "refs/");
b09fe971
IL
2059 else if (prefix)
2060 strbuf_addstr(&real_pattern, prefix);
d08bae7e
IL
2061 strbuf_addstr(&real_pattern, pattern);
2062
894a9d33 2063 if (!has_glob_specials(pattern)) {
9517e6b8 2064 /* Append implied '/' '*' if not present. */
d08bae7e
IL
2065 if (real_pattern.buf[real_pattern.len - 1] != '/')
2066 strbuf_addch(&real_pattern, '/');
2067 /* No need to check for '*', there is none. */
2068 strbuf_addch(&real_pattern, '*');
2069 }
2070
2071 filter.pattern = real_pattern.buf;
2072 filter.fn = fn;
2073 filter.cb_data = cb_data;
2074 ret = for_each_ref(filter_refs, &filter);
2075
2076 strbuf_release(&real_pattern);
2077 return ret;
2078}
2079
b09fe971
IL
2080int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2081{
2082 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2083}
2084
f8948e2f
JH
2085int for_each_rawref(each_ref_fn fn, void *cb_data)
2086{
9da31cb0 2087 return do_for_each_ref(&ref_cache, "", fn, 0,
f8948e2f 2088 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
8a65ff76
LT
2089}
2090
4577e483 2091const char *prettify_refname(const char *name)
a9c37a72 2092{
a9c37a72 2093 return name + (
59556548
CC
2094 starts_with(name, "refs/heads/") ? 11 :
2095 starts_with(name, "refs/tags/") ? 10 :
2096 starts_with(name, "refs/remotes/") ? 13 :
a9c37a72
DB
2097 0);
2098}
2099
54457fe5 2100static const char *ref_rev_parse_rules[] = {
79803322
SP
2101 "%.*s",
2102 "refs/%.*s",
2103 "refs/tags/%.*s",
2104 "refs/heads/%.*s",
2105 "refs/remotes/%.*s",
2106 "refs/remotes/%.*s/HEAD",
2107 NULL
2108};
2109
54457fe5 2110int refname_match(const char *abbrev_name, const char *full_name)
79803322
SP
2111{
2112 const char **p;
2113 const int abbrev_name_len = strlen(abbrev_name);
2114
54457fe5 2115 for (p = ref_rev_parse_rules; *p; p++) {
79803322
SP
2116 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2117 return 1;
2118 }
2119 }
2120
2121 return 0;
2122}
2123
0b1e6548
RS
2124static void unlock_ref(struct ref_lock *lock)
2125{
2126 /* Do not free lock->lk -- atexit() still looks at them */
2127 if (lock->lk)
2128 rollback_lock_file(lock->lk);
2129 free(lock->ref_name);
2130 free(lock->orig_ref_name);
2131 free(lock);
2132}
2133
835e3c99 2134/* This function should make sure errno is meaningful on error */
e5f38ec3 2135static struct ref_lock *verify_lock(struct ref_lock *lock,
4bd18c43
SP
2136 const unsigned char *old_sha1, int mustexist)
2137{
7695d118
RS
2138 if (read_ref_full(lock->ref_name,
2139 mustexist ? RESOLVE_REF_READING : 0,
2140 lock->old_sha1, NULL)) {
835e3c99 2141 int save_errno = errno;
434cd0cd 2142 error("Can't verify ref %s", lock->ref_name);
4bd18c43 2143 unlock_ref(lock);
835e3c99 2144 errno = save_errno;
4bd18c43
SP
2145 return NULL;
2146 }
a89fccd2 2147 if (hashcmp(lock->old_sha1, old_sha1)) {
434cd0cd 2148 error("Ref %s is at %s but expected %s", lock->ref_name,
4bd18c43
SP
2149 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2150 unlock_ref(lock);
835e3c99 2151 errno = EBUSY;
4bd18c43
SP
2152 return NULL;
2153 }
2154 return lock;
2155}
2156
7155b727 2157static int remove_empty_directories(const char *file)
bc7127ef
JH
2158{
2159 /* we want to create a file but there is a directory there;
2160 * if that is an empty directory (or a directory that contains
2161 * only empty directories), remove them.
2162 */
7155b727 2163 struct strbuf path;
470a91ef 2164 int result, save_errno;
bc7127ef 2165
7155b727
JS
2166 strbuf_init(&path, 20);
2167 strbuf_addstr(&path, file);
2168
a0f4afbe 2169 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
470a91ef 2170 save_errno = errno;
7155b727
JS
2171
2172 strbuf_release(&path);
470a91ef 2173 errno = save_errno;
7155b727
JS
2174
2175 return result;
bc7127ef
JH
2176}
2177
ff74f7f1
JH
2178/*
2179 * *string and *len will only be substituted, and *string returned (for
2180 * later free()ing) if the string passed in is a magic short-hand form
2181 * to name a branch.
2182 */
2183static char *substitute_branch_name(const char **string, int *len)
2184{
2185 struct strbuf buf = STRBUF_INIT;
cf99a761 2186 int ret = interpret_branch_name(*string, *len, &buf);
ff74f7f1
JH
2187
2188 if (ret == *len) {
2189 size_t size;
2190 *string = strbuf_detach(&buf, &size);
2191 *len = size;
2192 return (char *)*string;
2193 }
2194
2195 return NULL;
2196}
2197
2198int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2199{
2200 char *last_branch = substitute_branch_name(&str, &len);
2201 const char **p, *r;
2202 int refs_found = 0;
2203
2204 *ref = NULL;
2205 for (p = ref_rev_parse_rules; *p; p++) {
2206 char fullref[PATH_MAX];
2207 unsigned char sha1_from_ref[20];
2208 unsigned char *this_result;
2209 int flag;
2210
2211 this_result = refs_found ? sha1_from_ref : sha1;
2212 mksnpath(fullref, sizeof(fullref), *p, len, str);
7695d118
RS
2213 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2214 this_result, &flag);
ff74f7f1
JH
2215 if (r) {
2216 if (!refs_found++)
2217 *ref = xstrdup(r);
2218 if (!warn_ambiguous_refs)
2219 break;
55956350 2220 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
ff74f7f1 2221 warning("ignoring dangling symref %s.", fullref);
55956350
JH
2222 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2223 warning("ignoring broken ref %s.", fullref);
2224 }
ff74f7f1
JH
2225 }
2226 free(last_branch);
2227 return refs_found;
2228}
2229
2230int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2231{
2232 char *last_branch = substitute_branch_name(&str, &len);
2233 const char **p;
2234 int logs_found = 0;
2235
2236 *log = NULL;
2237 for (p = ref_rev_parse_rules; *p; p++) {
ff74f7f1
JH
2238 unsigned char hash[20];
2239 char path[PATH_MAX];
2240 const char *ref, *it;
2241
2242 mksnpath(path, sizeof(path), *p, len, str);
7695d118
RS
2243 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2244 hash, NULL);
ff74f7f1
JH
2245 if (!ref)
2246 continue;
4da58835 2247 if (reflog_exists(path))
ff74f7f1 2248 it = path;
4da58835 2249 else if (strcmp(ref, path) && reflog_exists(ref))
ff74f7f1
JH
2250 it = ref;
2251 else
2252 continue;
2253 if (!logs_found++) {
2254 *log = xstrdup(it);
2255 hashcpy(sha1, hash);
2256 }
2257 if (!warn_ambiguous_refs)
2258 break;
2259 }
2260 free(last_branch);
2261 return logs_found;
2262}
2263
88b680ae 2264/*
3c93c847 2265 * Locks a ref returning the lock on success and NULL on failure.
88b680ae
RS
2266 * On failure errno is set to something meaningful.
2267 */
dfefa935
MH
2268static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2269 const unsigned char *old_sha1,
5fe7d825 2270 const struct string_list *skip,
fec14ec3 2271 unsigned int flags, int *type_p)
4bd18c43 2272{
434cd0cd 2273 char *ref_file;
dfefa935 2274 const char *orig_refname = refname;
4bd18c43 2275 struct ref_lock *lock;
5cc3cef9 2276 int last_errno = 0;
acd3b9ec 2277 int type, lflags;
4431fcc4 2278 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
7695d118 2279 int resolve_flags = 0;
5bdd8d4a 2280 int missing = 0;
c4c61c76 2281 int attempts_remaining = 3;
4bd18c43
SP
2282
2283 lock = xcalloc(1, sizeof(struct ref_lock));
2284 lock->lock_fd = -1;
2285
7695d118
RS
2286 if (mustexist)
2287 resolve_flags |= RESOLVE_REF_READING;
d0f810f0
RS
2288 if (flags & REF_DELETING) {
2289 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2290 if (flags & REF_NODEREF)
2291 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2292 }
7695d118
RS
2293
2294 refname = resolve_ref_unsafe(refname, resolve_flags,
2295 lock->old_sha1, &type);
dfefa935 2296 if (!refname && errno == EISDIR) {
bc7127ef
JH
2297 /* we are trying to lock foo but we used to
2298 * have foo/bar which now does not exist;
2299 * it is normal for the empty directory 'foo'
2300 * to remain.
2301 */
dfefa935 2302 ref_file = git_path("%s", orig_refname);
5cc3cef9
JH
2303 if (remove_empty_directories(ref_file)) {
2304 last_errno = errno;
dfefa935 2305 error("there are still refs under '%s'", orig_refname);
5cc3cef9
JH
2306 goto error_return;
2307 }
7695d118
RS
2308 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2309 lock->old_sha1, &type);
bc7127ef 2310 }
68db31cc
SV
2311 if (type_p)
2312 *type_p = type;
dfefa935 2313 if (!refname) {
5cc3cef9 2314 last_errno = errno;
818f477c 2315 error("unable to resolve reference %s: %s",
dfefa935 2316 orig_refname, strerror(errno));
5cc3cef9 2317 goto error_return;
4bd18c43 2318 }
5bdd8d4a 2319 missing = is_null_sha1(lock->old_sha1);
c976d415
LH
2320 /* When the ref did not exist and we are creating it,
2321 * make sure there is no existing ref that is packed
2322 * whose name begins with our refname, nor a ref whose
2323 * name is a proper prefix of our refname.
2324 */
5bdd8d4a 2325 if (missing &&
5fe7d825 2326 !is_refname_available(refname, skip, get_packed_refs(&ref_cache))) {
f475e08e 2327 last_errno = ENOTDIR;
c976d415 2328 goto error_return;
f475e08e 2329 }
22a3844e 2330
c33d5174 2331 lock->lk = xcalloc(1, sizeof(struct lock_file));
4bd18c43 2332
e5c223e9 2333 lflags = 0;
acd3b9ec 2334 if (flags & REF_NODEREF) {
dfefa935 2335 refname = orig_refname;
47ba4662 2336 lflags |= LOCK_NO_DEREF;
acd3b9ec 2337 }
dfefa935
MH
2338 lock->ref_name = xstrdup(refname);
2339 lock->orig_ref_name = xstrdup(orig_refname);
2340 ref_file = git_path("%s", refname);
5bdd8d4a 2341 if (missing)
68db31cc
SV
2342 lock->force_write = 1;
2343 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2344 lock->force_write = 1;
4bd18c43 2345
c4c61c76
MH
2346 retry:
2347 switch (safe_create_leading_directories(ref_file)) {
2348 case SCLD_OK:
2349 break; /* success */
2350 case SCLD_VANISHED:
2351 if (--attempts_remaining > 0)
2352 goto retry;
2353 /* fall through */
2354 default:
5cc3cef9
JH
2355 last_errno = errno;
2356 error("unable to create directory for %s", ref_file);
2357 goto error_return;
2358 }
4bd18c43 2359
acd3b9ec 2360 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
e5c223e9 2361 if (lock->lock_fd < 0) {
06839515 2362 last_errno = errno;
e5c223e9
MH
2363 if (errno == ENOENT && --attempts_remaining > 0)
2364 /*
2365 * Maybe somebody just deleted one of the
2366 * directories leading to ref_file. Try
2367 * again:
2368 */
2369 goto retry;
06839515
RS
2370 else {
2371 struct strbuf err = STRBUF_INIT;
2372 unable_to_lock_message(ref_file, errno, &err);
2373 error("%s", err.buf);
33adc83d 2374 strbuf_release(&err);
06839515
RS
2375 goto error_return;
2376 }
e5c223e9 2377 }
4bd18c43 2378 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
5cc3cef9
JH
2379
2380 error_return:
2381 unlock_ref(lock);
2382 errno = last_errno;
2383 return NULL;
4bd18c43
SP
2384}
2385
fec3137f
MH
2386/*
2387 * Write an entry to the packed-refs file for the specified refname.
2388 * If peeled is non-NULL, write it as the entry's peeled value.
2389 */
9540ce50 2390static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
fec3137f 2391 unsigned char *peeled)
d66da478 2392{
9540ce50
JK
2393 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2394 if (peeled)
2395 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
fec3137f
MH
2396}
2397
7b40d396
MH
2398/*
2399 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2400 */
2401static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2402{
7b40d396
MH
2403 enum peel_status peel_status = peel_entry(entry, 0);
2404
2405 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2406 error("internal error: %s is not a valid packed reference!",
2407 entry->name);
9540ce50 2408 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,
7b40d396
MH
2409 peel_status == PEEL_PEELED ?
2410 entry->u.value.peeled : NULL);
2411 return 0;
2412}
2413
447ff1bf 2414/* This should return a meaningful errno on failure */
9f69d297
MH
2415int lock_packed_refs(int flags)
2416{
2417 struct packed_ref_cache *packed_ref_cache;
2418
9f69d297
MH
2419 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2420 return -1;
5d478f5c
MH
2421 /*
2422 * Get the current packed-refs while holding the lock. If the
2423 * packed-refs file has been modified since we last read it,
2424 * this will automatically invalidate the cache and re-read
2425 * the packed-refs file.
2426 */
9f69d297
MH
2427 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2428 packed_ref_cache->lock = &packlock;
4f6b83e3
MH
2429 /* Increment the reference count to prevent it from being freed: */
2430 acquire_packed_ref_cache(packed_ref_cache);
9f69d297
MH
2431 return 0;
2432}
2433
d3f66555
RS
2434/*
2435 * Commit the packed refs changes.
2436 * On error we must make sure that errno contains a meaningful value.
2437 */
9f69d297
MH
2438int commit_packed_refs(void)
2439{
2440 struct packed_ref_cache *packed_ref_cache =
2441 get_packed_ref_cache(&ref_cache);
2442 int error = 0;
d3f66555 2443 int save_errno = 0;
9540ce50 2444 FILE *out;
9f69d297
MH
2445
2446 if (!packed_ref_cache->lock)
2447 die("internal error: packed-refs not locked");
9f69d297 2448
6e578a31 2449 out = fdopen_lock_file(packed_ref_cache->lock, "w");
9540ce50
JK
2450 if (!out)
2451 die_errno("unable to fdopen packed-refs descriptor");
2452
2453 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
9f69d297 2454 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
9540ce50 2455 0, write_packed_entry_fn, out);
9540ce50 2456
d3f66555
RS
2457 if (commit_lock_file(packed_ref_cache->lock)) {
2458 save_errno = errno;
9f69d297 2459 error = -1;
d3f66555 2460 }
9f69d297 2461 packed_ref_cache->lock = NULL;
4f6b83e3 2462 release_packed_ref_cache(packed_ref_cache);
d3f66555 2463 errno = save_errno;
9f69d297
MH
2464 return error;
2465}
2466
2467void rollback_packed_refs(void)
2468{
2469 struct packed_ref_cache *packed_ref_cache =
2470 get_packed_ref_cache(&ref_cache);
2471
2472 if (!packed_ref_cache->lock)
2473 die("internal error: packed-refs not locked");
2474 rollback_lock_file(packed_ref_cache->lock);
2475 packed_ref_cache->lock = NULL;
4f6b83e3 2476 release_packed_ref_cache(packed_ref_cache);
9f69d297
MH
2477 clear_packed_ref_cache(&ref_cache);
2478}
2479
32d462ce
MH
2480struct ref_to_prune {
2481 struct ref_to_prune *next;
2482 unsigned char sha1[20];
2483 char name[FLEX_ARRAY];
2484};
2485
2486struct pack_refs_cb_data {
2487 unsigned int flags;
267f9a8c 2488 struct ref_dir *packed_refs;
32d462ce 2489 struct ref_to_prune *ref_to_prune;
32d462ce
MH
2490};
2491
267f9a8c
MH
2492/*
2493 * An each_ref_entry_fn that is run over loose references only. If
2494 * the loose reference can be packed, add an entry in the packed ref
2495 * cache. If the reference should be pruned, also add it to
2496 * ref_to_prune in the pack_refs_cb_data.
2497 */
2498static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
32d462ce
MH
2499{
2500 struct pack_refs_cb_data *cb = cb_data;
f85354b5 2501 enum peel_status peel_status;
267f9a8c 2502 struct ref_entry *packed_entry;
59556548 2503 int is_tag_ref = starts_with(entry->name, "refs/tags/");
32d462ce 2504
267f9a8c
MH
2505 /* ALWAYS pack tags */
2506 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
32d462ce
MH
2507 return 0;
2508
b2a8226d
MH
2509 /* Do not pack symbolic or broken refs: */
2510 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2511 return 0;
2512
267f9a8c 2513 /* Add a packed ref cache entry equivalent to the loose entry. */
f85354b5 2514 peel_status = peel_entry(entry, 1);
0f29920f 2515 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
f85354b5
MH
2516 die("internal error peeling reference %s (%s)",
2517 entry->name, sha1_to_hex(entry->u.value.sha1));
267f9a8c
MH
2518 packed_entry = find_ref(cb->packed_refs, entry->name);
2519 if (packed_entry) {
2520 /* Overwrite existing packed entry with info from loose entry */
2521 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2522 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2523 } else {
2524 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2525 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2526 add_ref(cb->packed_refs, packed_entry);
2527 }
2528 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
32d462ce 2529
267f9a8c
MH
2530 /* Schedule the loose reference for pruning if requested. */
2531 if ((cb->flags & PACK_REFS_PRUNE)) {
12e77559 2532 int namelen = strlen(entry->name) + 1;
32d462ce 2533 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
12e77559
MH
2534 hashcpy(n->sha1, entry->u.value.sha1);
2535 strcpy(n->name, entry->name);
32d462ce
MH
2536 n->next = cb->ref_to_prune;
2537 cb->ref_to_prune = n;
2538 }
d66da478
MH
2539 return 0;
2540}
2541
32d462ce
MH
2542/*
2543 * Remove empty parents, but spare refs/ and immediate subdirs.
2544 * Note: munges *name.
2545 */
2546static void try_remove_empty_parents(char *name)
2547{
2548 char *p, *q;
2549 int i;
2550 p = name;
2551 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2552 while (*p && *p != '/')
2553 p++;
2554 /* tolerate duplicate slashes; see check_refname_format() */
2555 while (*p == '/')
2556 p++;
2557 }
2558 for (q = p; *q; q++)
2559 ;
2560 while (1) {
2561 while (q > p && *q != '/')
2562 q--;
2563 while (q > p && *(q-1) == '/')
2564 q--;
2565 if (q == p)
2566 break;
2567 *q = '\0';
2568 if (rmdir(git_path("%s", name)))
2569 break;
2570 }
2571}
2572
2573/* make sure nobody touched the ref, and unlink */
2574static void prune_ref(struct ref_to_prune *r)
2575{
029cdb4a
RS
2576 struct ref_transaction *transaction;
2577 struct strbuf err = STRBUF_INIT;
32d462ce 2578
88e7dff9 2579 if (check_refname_format(r->name, 0))
cba12021 2580 return;
32d462ce 2581
029cdb4a
RS
2582 transaction = ref_transaction_begin(&err);
2583 if (!transaction ||
2584 ref_transaction_delete(transaction, r->name, r->sha1,
fb5a6bb6 2585 REF_ISPRUNING, NULL, &err) ||
db7516ab 2586 ref_transaction_commit(transaction, &err)) {
029cdb4a
RS
2587 ref_transaction_free(transaction);
2588 error("%s", err.buf);
2589 strbuf_release(&err);
2590 return;
32d462ce 2591 }
029cdb4a
RS
2592 ref_transaction_free(transaction);
2593 strbuf_release(&err);
2594 try_remove_empty_parents(r->name);
32d462ce
MH
2595}
2596
2597static void prune_refs(struct ref_to_prune *r)
2598{
2599 while (r) {
2600 prune_ref(r);
2601 r = r->next;
2602 }
2603}
2604
32d462ce
MH
2605int pack_refs(unsigned int flags)
2606{
32d462ce
MH
2607 struct pack_refs_cb_data cbdata;
2608
2609 memset(&cbdata, 0, sizeof(cbdata));
2610 cbdata.flags = flags;
2611
9f69d297 2612 lock_packed_refs(LOCK_DIE_ON_ERROR);
267f9a8c 2613 cbdata.packed_refs = get_packed_refs(&ref_cache);
32d462ce 2614
267f9a8c
MH
2615 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2616 pack_if_possible_fn, &cbdata);
32d462ce 2617
9f69d297 2618 if (commit_packed_refs())
32d462ce 2619 die_errno("unable to overwrite old ref-pack file");
9f69d297 2620
32d462ce
MH
2621 prune_refs(cbdata.ref_to_prune);
2622 return 0;
2623}
2624
7b40d396
MH
2625/*
2626 * If entry is no longer needed in packed-refs, add it to the string
2627 * list pointed to by cb_data. Reasons for deleting entries:
2628 *
2629 * - Entry is broken.
2630 * - Entry is overridden by a loose ref.
2631 * - Entry does not point at a valid object.
2632 *
2633 * In the first and third cases, also emit an error message because these
2634 * are indications of repository corruption.
2635 */
2636static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
c0277d15 2637{
7b40d396 2638 struct string_list *refs_to_delete = cb_data;
fec3137f 2639
ab292bc4
MH
2640 if (entry->flag & REF_ISBROKEN) {
2641 /* This shouldn't happen to packed refs. */
2642 error("%s is broken!", entry->name);
7b40d396 2643 string_list_append(refs_to_delete, entry->name);
c0277d15 2644 return 0;
ab292bc4
MH
2645 }
2646 if (!has_sha1_file(entry->u.value.sha1)) {
2647 unsigned char sha1[20];
2648 int flags;
2649
7695d118 2650 if (read_ref_full(entry->name, 0, sha1, &flags))
ab292bc4
MH
2651 /* We should at least have found the packed ref. */
2652 die("Internal error");
7b40d396 2653 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
ab292bc4
MH
2654 /*
2655 * This packed reference is overridden by a
2656 * loose reference, so it is OK that its value
2657 * is no longer valid; for example, it might
2658 * refer to an object that has been garbage
2659 * collected. For this purpose we don't even
2660 * care whether the loose reference itself is
2661 * invalid, broken, symbolic, etc. Silently
7b40d396 2662 * remove the packed reference.
ab292bc4 2663 */
7b40d396 2664 string_list_append(refs_to_delete, entry->name);
ab292bc4 2665 return 0;
7b40d396 2666 }
ab292bc4
MH
2667 /*
2668 * There is no overriding loose reference, so the fact
2669 * that this reference doesn't refer to a valid object
2670 * indicates some kind of repository corruption.
2671 * Report the problem, then omit the reference from
2672 * the output.
2673 */
2674 error("%s does not point to a valid object!", entry->name);
7b40d396 2675 string_list_append(refs_to_delete, entry->name);
ab292bc4
MH
2676 return 0;
2677 }
2678
d66da478
MH
2679 return 0;
2680}
2681
4a45b2f3 2682int repack_without_refs(struct string_list *refnames, struct strbuf *err)
c0277d15 2683{
7618fd80 2684 struct ref_dir *packed;
7b40d396 2685 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
4a45b2f3
MH
2686 struct string_list_item *refname, *ref_to_delete;
2687 int ret, needs_repacking = 0, removed = 0;
61cee0db 2688
5a603b04
JN
2689 assert(err);
2690
61cee0db 2691 /* Look for a packed ref */
4a45b2f3
MH
2692 for_each_string_list_item(refname, refnames) {
2693 if (get_packed_ref(refname->string)) {
2694 needs_repacking = 1;
61cee0db 2695 break;
4a45b2f3
MH
2696 }
2697 }
7618fd80 2698
61cee0db 2699 /* Avoid locking if we have nothing to do */
4a45b2f3 2700 if (!needs_repacking)
61cee0db 2701 return 0; /* no refname exists in packed refs */
7618fd80 2702
9f69d297 2703 if (lock_packed_refs(0)) {
5a603b04
JN
2704 unable_to_lock_message(git_path("packed-refs"), errno, err);
2705 return -1;
1b018fd9 2706 }
9da31cb0 2707 packed = get_packed_refs(&ref_cache);
7b40d396 2708
61cee0db 2709 /* Remove refnames from the cache */
4a45b2f3
MH
2710 for_each_string_list_item(refname, refnames)
2711 if (remove_entry(packed, refname->string) != -1)
61cee0db
BK
2712 removed = 1;
2713 if (!removed) {
506a760d 2714 /*
61cee0db 2715 * All packed entries disappeared while we were
506a760d
MH
2716 * acquiring the lock.
2717 */
9f69d297 2718 rollback_packed_refs();
506a760d
MH
2719 return 0;
2720 }
7b40d396 2721
61cee0db 2722 /* Remove any other accumulated cruft */
7b40d396
MH
2723 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2724 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2725 if (remove_entry(packed, ref_to_delete->string) == -1)
2726 die("internal error");
2727 }
2728
61cee0db 2729 /* Write what remains */
60bca085 2730 ret = commit_packed_refs();
5a603b04 2731 if (ret)
60bca085
RS
2732 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2733 strerror(errno));
2734 return ret;
c0277d15
JH
2735}
2736
dbdcac7d 2737static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2ddb5d17 2738{
5a603b04
JN
2739 assert(err);
2740
045a476f 2741 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
91f1f191
MH
2742 /*
2743 * loose. The loose file name is the same as the
2744 * lockfile name, minus ".lock":
2745 */
ec38b4e4 2746 char *loose_filename = get_locked_file_path(lock->lk);
dbdcac7d 2747 int res = unlink_or_msg(loose_filename, err);
91f1f191 2748 free(loose_filename);
dbdcac7d 2749 if (res)
2ddb5d17 2750 return 1;
c0277d15 2751 }
2ddb5d17
BK
2752 return 0;
2753}
2754
fec14ec3 2755int delete_ref(const char *refname, const unsigned char *sha1, unsigned int flags)
c0277d15 2756{
7521cc46
RS
2757 struct ref_transaction *transaction;
2758 struct strbuf err = STRBUF_INIT;
c0277d15 2759
7521cc46
RS
2760 transaction = ref_transaction_begin(&err);
2761 if (!transaction ||
fb5a6bb6
MH
2762 ref_transaction_delete(transaction, refname,
2763 (sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,
2764 flags, NULL, &err) ||
db7516ab 2765 ref_transaction_commit(transaction, &err)) {
7521cc46
RS
2766 error("%s", err.buf);
2767 ref_transaction_free(transaction);
2768 strbuf_release(&err);
c0277d15 2769 return 1;
7521cc46
RS
2770 }
2771 ref_transaction_free(transaction);
2772 strbuf_release(&err);
2773 return 0;
4bd18c43
SP
2774}
2775
765c2258
PH
2776/*
2777 * People using contrib's git-new-workdir have .git/logs/refs ->
2778 * /some/other/path/.git/logs/refs, and that may live on another device.
2779 *
2780 * IOW, to avoid cross device rename errors, the temporary renamed log must
2781 * live into logs/refs.
2782 */
2783#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2784
fa59ae79
MH
2785static int rename_tmp_log(const char *newrefname)
2786{
f1e9e9a4 2787 int attempts_remaining = 4;
ae4a283e
MH
2788
2789 retry:
08f555cb
MH
2790 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2791 case SCLD_OK:
2792 break; /* success */
2793 case SCLD_VANISHED:
2794 if (--attempts_remaining > 0)
2795 goto retry;
2796 /* fall through */
2797 default:
fa59ae79
MH
2798 error("unable to create directory for %s", newrefname);
2799 return -1;
2800 }
2801
fa59ae79 2802 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
f1e9e9a4 2803 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
fa59ae79
MH
2804 /*
2805 * rename(a, b) when b is an existing
2806 * directory ought to result in ISDIR, but
2807 * Solaris 5.8 gives ENOTDIR. Sheesh.
2808 */
2809 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2810 error("Directory not empty: logs/%s", newrefname);
2811 return -1;
2812 }
2813 goto retry;
ae4a283e
MH
2814 } else if (errno == ENOENT && --attempts_remaining > 0) {
2815 /*
2816 * Maybe another process just deleted one of
2817 * the directories in the path to newrefname.
2818 * Try again from the beginning.
2819 */
2820 goto retry;
fa59ae79
MH
2821 } else {
2822 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2823 newrefname, strerror(errno));
2824 return -1;
2825 }
2826 }
2827 return 0;
2828}
2829
5fe7d825
RS
2830static int rename_ref_available(const char *oldname, const char *newname)
2831{
2832 struct string_list skip = STRING_LIST_INIT_NODUP;
2833 int ret;
2834
2835 string_list_insert(&skip, oldname);
2836 ret = is_refname_available(newname, &skip, get_packed_refs(&ref_cache))
2837 && is_refname_available(newname, &skip, get_loose_refs(&ref_cache));
2838 string_list_clear(&skip, 0);
2839 return ret;
2840}
2841
aae383db
RS
2842static int write_ref_sha1(struct ref_lock *lock, const unsigned char *sha1,
2843 const char *logmsg);
2844
dfefa935 2845int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
c976d415 2846{
c976d415
LH
2847 unsigned char sha1[20], orig_sha1[20];
2848 int flag = 0, logmoved = 0;
2849 struct ref_lock *lock;
c976d415 2850 struct stat loginfo;
dfefa935 2851 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
eca35a25 2852 const char *symref = NULL;
c976d415 2853
450d4c0f 2854 if (log && S_ISLNK(loginfo.st_mode))
dfefa935 2855 return error("reflog for %s is a symlink", oldrefname);
c976d415 2856
7695d118
RS
2857 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2858 orig_sha1, &flag);
eca35a25 2859 if (flag & REF_ISSYMREF)
fa58186c 2860 return error("refname %s is a symbolic ref, renaming it is not supported",
dfefa935 2861 oldrefname);
eca35a25 2862 if (!symref)
dfefa935 2863 return error("refname %s not found", oldrefname);
c976d415 2864
5fe7d825 2865 if (!rename_ref_available(oldrefname, newrefname))
c976d415
LH
2866 return 1;
2867
dfefa935 2868 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
765c2258 2869 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
dfefa935 2870 oldrefname, strerror(errno));
c976d415 2871
dfefa935
MH
2872 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2873 error("unable to delete old %s", oldrefname);
c976d415
LH
2874 goto rollback;
2875 }
2876
7695d118 2877 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
dfefa935 2878 delete_ref(newrefname, sha1, REF_NODEREF)) {
c976d415 2879 if (errno==EISDIR) {
dfefa935
MH
2880 if (remove_empty_directories(git_path("%s", newrefname))) {
2881 error("Directory not empty: %s", newrefname);
c976d415
LH
2882 goto rollback;
2883 }
2884 } else {
dfefa935 2885 error("unable to delete existing %s", newrefname);
c976d415
LH
2886 goto rollback;
2887 }
2888 }
2889
fa59ae79 2890 if (log && rename_tmp_log(newrefname))
c976d415 2891 goto rollback;
c976d415 2892
c976d415
LH
2893 logmoved = log;
2894
5fe7d825 2895 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, 0, NULL);
c976d415 2896 if (!lock) {
dfefa935 2897 error("unable to lock %s for update", newrefname);
c976d415
LH
2898 goto rollback;
2899 }
c976d415
LH
2900 lock->force_write = 1;
2901 hashcpy(lock->old_sha1, orig_sha1);
678d0f4c 2902 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
dfefa935 2903 error("unable to write current sha1 into %s", newrefname);
c976d415
LH
2904 goto rollback;
2905 }
2906
2907 return 0;
2908
2909 rollback:
5fe7d825 2910 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, 0, NULL);
c976d415 2911 if (!lock) {
dfefa935 2912 error("unable to lock %s for rollback", oldrefname);
c976d415
LH
2913 goto rollbacklog;
2914 }
2915
2916 lock->force_write = 1;
2917 flag = log_all_ref_updates;
2918 log_all_ref_updates = 0;
2919 if (write_ref_sha1(lock, orig_sha1, NULL))
dfefa935 2920 error("unable to write current sha1 into %s", oldrefname);
c976d415
LH
2921 log_all_ref_updates = flag;
2922
2923 rollbacklog:
dfefa935 2924 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
c976d415 2925 error("unable to restore logfile %s from %s: %s",
dfefa935 2926 oldrefname, newrefname, strerror(errno));
c976d415 2927 if (!logmoved && log &&
dfefa935 2928 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
765c2258 2929 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
dfefa935 2930 oldrefname, strerror(errno));
c976d415
LH
2931
2932 return 1;
2933}
2934
0b1e6548 2935static int close_ref(struct ref_lock *lock)
b531394d
BC
2936{
2937 if (close_lock_file(lock->lk))
2938 return -1;
2939 lock->lock_fd = -1;
2940 return 0;
2941}
2942
0b1e6548 2943static int commit_ref(struct ref_lock *lock)
b531394d
BC
2944{
2945 if (commit_lock_file(lock->lk))
2946 return -1;
2947 lock->lock_fd = -1;
2948 return 0;
2949}
2950
0ec29a47
JH
2951/*
2952 * copy the reflog message msg to buf, which has been allocated sufficiently
2953 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2954 * because reflog file is one line per entry.
2955 */
2956static int copy_msg(char *buf, const char *msg)
2957{
2958 char *cp = buf;
2959 char c;
2960 int wasspace = 1;
2961
2962 *cp++ = '\t';
2963 while ((c = *msg++)) {
2964 if (wasspace && isspace(c))
2965 continue;
2966 wasspace = isspace(c);
2967 if (wasspace)
2968 c = ' ';
2969 *cp++ = c;
2970 }
2971 while (buf < cp && isspace(cp[-1]))
2972 cp--;
2973 *cp++ = '\n';
2974 return cp - buf;
2975}
2976
bd3b02da 2977/* This function must set a meaningful errno on failure */
dfefa935 2978int log_ref_setup(const char *refname, char *logfile, int bufsize)
6de08ae6 2979{
859c3017 2980 int logfd, oflags = O_APPEND | O_WRONLY;
9a13f0b7 2981
dfefa935 2982 git_snpath(logfile, bufsize, "logs/%s", refname);
4057deb5 2983 if (log_all_ref_updates &&
59556548
CC
2984 (starts_with(refname, "refs/heads/") ||
2985 starts_with(refname, "refs/remotes/") ||
2986 starts_with(refname, "refs/notes/") ||
dfefa935 2987 !strcmp(refname, "HEAD"))) {
bd3b02da
RS
2988 if (safe_create_leading_directories(logfile) < 0) {
2989 int save_errno = errno;
2990 error("unable to create directory for %s", logfile);
2991 errno = save_errno;
2992 return -1;
2993 }
6de08ae6
SP
2994 oflags |= O_CREAT;
2995 }
2996
157aaea5 2997 logfd = open(logfile, oflags, 0666);
6de08ae6 2998 if (logfd < 0) {
9233887c 2999 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
6de08ae6 3000 return 0;
3b463c3f 3001
9233887c 3002 if (errno == EISDIR) {
157aaea5 3003 if (remove_empty_directories(logfile)) {
bd3b02da
RS
3004 int save_errno = errno;
3005 error("There are still logs under '%s'",
3006 logfile);
3007 errno = save_errno;
3008 return -1;
3b463c3f 3009 }
157aaea5 3010 logfd = open(logfile, oflags, 0666);
3b463c3f
JH
3011 }
3012
bd3b02da
RS
3013 if (logfd < 0) {
3014 int save_errno = errno;
3015 error("Unable to append to %s: %s", logfile,
3016 strerror(errno));
3017 errno = save_errno;
3018 return -1;
3019 }
6de08ae6
SP
3020 }
3021
157aaea5 3022 adjust_shared_perm(logfile);
859c3017
EM
3023 close(logfd);
3024 return 0;
3025}
443b92b6 3026
2c6207ab
RS
3027static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3028 const unsigned char *new_sha1,
3029 const char *committer, const char *msg)
3030{
3031 int msglen, written;
3032 unsigned maxlen, len;
3033 char *logrec;
3034
3035 msglen = msg ? strlen(msg) : 0;
3036 maxlen = strlen(committer) + msglen + 100;
3037 logrec = xmalloc(maxlen);
3038 len = sprintf(logrec, "%s %s %s\n",
3039 sha1_to_hex(old_sha1),
3040 sha1_to_hex(new_sha1),
3041 committer);
3042 if (msglen)
3043 len += copy_msg(logrec + len - 1, msg) - 1;
3044
3045 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3046 free(logrec);
3047 if (written != len)
3048 return -1;
3049
3050 return 0;
3051}
3052
dfefa935 3053static int log_ref_write(const char *refname, const unsigned char *old_sha1,
859c3017
EM
3054 const unsigned char *new_sha1, const char *msg)
3055{
2c6207ab 3056 int logfd, result, oflags = O_APPEND | O_WRONLY;
157aaea5 3057 char log_file[PATH_MAX];
859c3017
EM
3058
3059 if (log_all_ref_updates < 0)
3060 log_all_ref_updates = !is_bare_repository();
3061
dfefa935 3062 result = log_ref_setup(refname, log_file, sizeof(log_file));
859c3017
EM
3063 if (result)
3064 return result;
3065
3066 logfd = open(log_file, oflags);
3067 if (logfd < 0)
3068 return 0;
2c6207ab
RS
3069 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3070 git_committer_info(0), msg);
3071 if (result) {
dc615de8
RS
3072 int save_errno = errno;
3073 close(logfd);
3074 error("Unable to append to %s", log_file);
3075 errno = save_errno;
3076 return -1;
3077 }
3078 if (close(logfd)) {
3079 int save_errno = errno;
3080 error("Unable to append to %s", log_file);
3081 errno = save_errno;
3082 return -1;
3083 }
6de08ae6
SP
3084 return 0;
3085}
3086
e7e0f26e 3087int is_branch(const char *refname)
c3b0dec5 3088{
59556548 3089 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
c3b0dec5
LT
3090}
3091
aae383db
RS
3092/*
3093 * Write sha1 into the ref specified by the lock. Make sure that errno
3094 * is sane on error.
3095 */
3096static int write_ref_sha1(struct ref_lock *lock,
4bd18c43
SP
3097 const unsigned char *sha1, const char *logmsg)
3098{
3099 static char term = '\n';
c3b0dec5 3100 struct object *o;
4bd18c43 3101
dc615de8
RS
3102 if (!lock) {
3103 errno = EINVAL;
95fc7512 3104 return -1;
dc615de8 3105 }
a89fccd2 3106 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
4bd18c43
SP
3107 unlock_ref(lock);
3108 return 0;
95fc7512 3109 }
c3b0dec5
LT
3110 o = parse_object(sha1);
3111 if (!o) {
7be8b3ba 3112 error("Trying to write ref %s with nonexistent object %s",
c3b0dec5
LT
3113 lock->ref_name, sha1_to_hex(sha1));
3114 unlock_ref(lock);
dc615de8 3115 errno = EINVAL;
c3b0dec5
LT
3116 return -1;
3117 }
3118 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3119 error("Trying to write non-commit object %s to branch %s",
3120 sha1_to_hex(sha1), lock->ref_name);
3121 unlock_ref(lock);
dc615de8 3122 errno = EINVAL;
c3b0dec5
LT
3123 return -1;
3124 }
93822c22 3125 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
dc615de8
RS
3126 write_in_full(lock->lock_fd, &term, 1) != 1 ||
3127 close_ref(lock) < 0) {
3128 int save_errno = errno;
cf6950d3 3129 error("Couldn't write %s", lock->lk->filename.buf);
4bd18c43 3130 unlock_ref(lock);
dc615de8 3131 errno = save_errno;
4bd18c43
SP
3132 return -1;
3133 }
9da31cb0 3134 clear_loose_ref_cache(&ref_cache);
bd104db1
NP
3135 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
3136 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3137 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
6de08ae6
SP
3138 unlock_ref(lock);
3139 return -1;
3140 }
605fac8b
NP
3141 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3142 /*
3143 * Special hack: If a branch is updated directly and HEAD
3144 * points to it (may happen on the remote side of a push
3145 * for example) then logically the HEAD reflog should be
3146 * updated too.
3147 * A generic solution implies reverse symref information,
3148 * but finding all symrefs pointing to the given branch
3149 * would be rather costly for this rare event (the direct
3150 * update of a branch) to be worth it. So let's cheat and
3151 * check with HEAD only which should cover 99% of all usage
3152 * scenarios (even 100% of the default ones).
3153 */
3154 unsigned char head_sha1[20];
3155 int head_flag;
3156 const char *head_ref;
7695d118
RS
3157 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3158 head_sha1, &head_flag);
605fac8b
NP
3159 if (head_ref && (head_flag & REF_ISSYMREF) &&
3160 !strcmp(head_ref, lock->ref_name))
3161 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3162 }
b531394d 3163 if (commit_ref(lock)) {
434cd0cd 3164 error("Couldn't set %s", lock->ref_name);
4bd18c43
SP
3165 unlock_ref(lock);
3166 return -1;
3167 }
4bd18c43
SP
3168 unlock_ref(lock);
3169 return 0;
95fc7512 3170}
d556fae2 3171
8b5157e4
NP
3172int create_symref(const char *ref_target, const char *refs_heads_master,
3173 const char *logmsg)
41b625b0
NP
3174{
3175 const char *lockpath;
3176 char ref[1000];
3177 int fd, len, written;
a4f34cbb 3178 char *git_HEAD = git_pathdup("%s", ref_target);
8b5157e4
NP
3179 unsigned char old_sha1[20], new_sha1[20];
3180
3181 if (logmsg && read_ref(ref_target, old_sha1))
3182 hashclr(old_sha1);
41b625b0 3183
d48744d1
JH
3184 if (safe_create_leading_directories(git_HEAD) < 0)
3185 return error("unable to create directory for %s", git_HEAD);
3186
41b625b0
NP
3187#ifndef NO_SYMLINK_HEAD
3188 if (prefer_symlink_refs) {
3189 unlink(git_HEAD);
3190 if (!symlink(refs_heads_master, git_HEAD))
8b5157e4 3191 goto done;
41b625b0
NP
3192 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3193 }
3194#endif
3195
3196 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3197 if (sizeof(ref) <= len) {
3198 error("refname too long: %s", refs_heads_master);
47fc52e2 3199 goto error_free_return;
41b625b0
NP
3200 }
3201 lockpath = mkpath("%s.lock", git_HEAD);
3202 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3203 if (fd < 0) {
3204 error("Unable to open %s for writing", lockpath);
47fc52e2 3205 goto error_free_return;
41b625b0
NP
3206 }
3207 written = write_in_full(fd, ref, len);
91c8d590 3208 if (close(fd) != 0 || written != len) {
41b625b0 3209 error("Unable to write to %s", lockpath);
47fc52e2 3210 goto error_unlink_return;
41b625b0
NP
3211 }
3212 if (rename(lockpath, git_HEAD) < 0) {
41b625b0 3213 error("Unable to create %s", git_HEAD);
47fc52e2 3214 goto error_unlink_return;
41b625b0
NP
3215 }
3216 if (adjust_shared_perm(git_HEAD)) {
41b625b0 3217 error("Unable to fix permissions on %s", lockpath);
47fc52e2 3218 error_unlink_return:
691f1a28 3219 unlink_or_warn(lockpath);
47fc52e2
JH
3220 error_free_return:
3221 free(git_HEAD);
3222 return -1;
41b625b0 3223 }
8b5157e4 3224
ee96d11b 3225#ifndef NO_SYMLINK_HEAD
8b5157e4 3226 done:
ee96d11b 3227#endif
8b5157e4
NP
3228 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3229 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3230
47fc52e2 3231 free(git_HEAD);
41b625b0
NP
3232 return 0;
3233}
3234
4207ed28
RS
3235struct read_ref_at_cb {
3236 const char *refname;
3237 unsigned long at_time;
3238 int cnt;
3239 int reccnt;
3240 unsigned char *sha1;
3241 int found_it;
3242
3243 unsigned char osha1[20];
3244 unsigned char nsha1[20];
3245 int tz;
3246 unsigned long date;
3247 char **msg;
3248 unsigned long *cutoff_time;
3249 int *cutoff_tz;
3250 int *cutoff_cnt;
3251};
3252
3253static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3254 const char *email, unsigned long timestamp, int tz,
3255 const char *message, void *cb_data)
3256{
3257 struct read_ref_at_cb *cb = cb_data;
3258
3259 cb->reccnt++;
3260 cb->tz = tz;
3261 cb->date = timestamp;
3262
3263 if (timestamp <= cb->at_time || cb->cnt == 0) {
3264 if (cb->msg)
3265 *cb->msg = xstrdup(message);
3266 if (cb->cutoff_time)
3267 *cb->cutoff_time = timestamp;
3268 if (cb->cutoff_tz)
3269 *cb->cutoff_tz = tz;
3270 if (cb->cutoff_cnt)
3271 *cb->cutoff_cnt = cb->reccnt - 1;
3272 /*
3273 * we have not yet updated cb->[n|o]sha1 so they still
3274 * hold the values for the previous record.
3275 */
3276 if (!is_null_sha1(cb->osha1)) {
3277 hashcpy(cb->sha1, nsha1);
3278 if (hashcmp(cb->osha1, nsha1))
3279 warning("Log for ref %s has gap after %s.",
3280 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3281 }
3282 else if (cb->date == cb->at_time)
3283 hashcpy(cb->sha1, nsha1);
3284 else if (hashcmp(nsha1, cb->sha1))
3285 warning("Log for ref %s unexpectedly ended on %s.",
3286 cb->refname, show_date(cb->date, cb->tz,
3287 DATE_RFC2822));
3288 hashcpy(cb->osha1, osha1);
3289 hashcpy(cb->nsha1, nsha1);
3290 cb->found_it = 1;
3291 return 1;
3292 }
3293 hashcpy(cb->osha1, osha1);
3294 hashcpy(cb->nsha1, nsha1);
3295 if (cb->cnt > 0)
3296 cb->cnt--;
3297 return 0;
3298}
3299
3300static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3301 const char *email, unsigned long timestamp,
3302 int tz, const char *message, void *cb_data)
3303{
3304 struct read_ref_at_cb *cb = cb_data;
3305
3306 if (cb->msg)
3307 *cb->msg = xstrdup(message);
3308 if (cb->cutoff_time)
3309 *cb->cutoff_time = timestamp;
3310 if (cb->cutoff_tz)
3311 *cb->cutoff_tz = tz;
3312 if (cb->cutoff_cnt)
3313 *cb->cutoff_cnt = cb->reccnt;
3314 hashcpy(cb->sha1, osha1);
3315 if (is_null_sha1(cb->sha1))
3316 hashcpy(cb->sha1, nsha1);
3317 /* We just want the first entry */
3318 return 1;
16d7cc90
JH
3319}
3320
c41a87dd 3321int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
dfefa935
MH
3322 unsigned char *sha1, char **msg,
3323 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
d556fae2 3324{
4207ed28 3325 struct read_ref_at_cb cb;
d556fae2 3326
4207ed28
RS
3327 memset(&cb, 0, sizeof(cb));
3328 cb.refname = refname;
3329 cb.at_time = at_time;
3330 cb.cnt = cnt;
3331 cb.msg = msg;
3332 cb.cutoff_time = cutoff_time;
3333 cb.cutoff_tz = cutoff_tz;
3334 cb.cutoff_cnt = cutoff_cnt;
3335 cb.sha1 = sha1;
3336
3337 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3338
c41a87dd
DA
3339 if (!cb.reccnt) {
3340 if (flags & GET_SHA1_QUIETLY)
3341 exit(128);
3342 else
3343 die("Log for %s is empty.", refname);
3344 }
4207ed28
RS
3345 if (cb.found_it)
3346 return 0;
3347
3348 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
d556fae2 3349
16d7cc90 3350 return 1;
d556fae2 3351}
2ff81662 3352
4da58835
RS
3353int reflog_exists(const char *refname)
3354{
3355 struct stat st;
3356
3357 return !lstat(git_path("logs/%s", refname), &st) &&
3358 S_ISREG(st.st_mode);
3359}
3360
3361int delete_reflog(const char *refname)
3362{
3363 return remove_path(git_path("logs/%s", refname));
3364}
3365
9a7a183b
JH
3366static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3367{
3368 unsigned char osha1[20], nsha1[20];
3369 char *email_end, *message;
3370 unsigned long timestamp;
3371 int tz;
3372
3373 /* old SP new SP name <email> SP time TAB msg LF */
3374 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3375 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3376 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3377 !(email_end = strchr(sb->buf + 82, '>')) ||
3378 email_end[1] != ' ' ||
3379 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3380 !message || message[0] != ' ' ||
3381 (message[1] != '+' && message[1] != '-') ||
3382 !isdigit(message[2]) || !isdigit(message[3]) ||
3383 !isdigit(message[4]) || !isdigit(message[5]))
3384 return 0; /* corrupt? */
3385 email_end[1] = '\0';
3386 tz = strtol(message + 1, NULL, 10);
3387 if (message[6] != '\t')
3388 message += 6;
3389 else
3390 message += 7;
3391 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3392}
3393
98f85ff4
JH
3394static char *find_beginning_of_line(char *bob, char *scan)
3395{
3396 while (bob < scan && *(--scan) != '\n')
3397 ; /* keep scanning backwards */
3398 /*
3399 * Return either beginning of the buffer, or LF at the end of
3400 * the previous line.
3401 */
3402 return scan;
3403}
3404
3405int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2ff81662 3406{
8ca78803 3407 struct strbuf sb = STRBUF_INIT;
98f85ff4
JH
3408 FILE *logfp;
3409 long pos;
3410 int ret = 0, at_tail = 1;
2ff81662 3411
7ae07c1b 3412 logfp = fopen(git_path("logs/%s", refname), "r");
2ff81662 3413 if (!logfp)
883d60fa 3414 return -1;
101d15e0 3415
98f85ff4
JH
3416 /* Jump to the end */
3417 if (fseek(logfp, 0, SEEK_END) < 0)
3418 return error("cannot seek back reflog for %s: %s",
3419 refname, strerror(errno));
3420 pos = ftell(logfp);
3421 while (!ret && 0 < pos) {
3422 int cnt;
3423 size_t nread;
3424 char buf[BUFSIZ];
3425 char *endp, *scanp;
3426
3427 /* Fill next block from the end */
3428 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3429 if (fseek(logfp, pos - cnt, SEEK_SET))
3430 return error("cannot seek back reflog for %s: %s",
3431 refname, strerror(errno));
3432 nread = fread(buf, cnt, 1, logfp);
e4ca819a 3433 if (nread != 1)
98f85ff4
JH
3434 return error("cannot read %d bytes from reflog for %s: %s",
3435 cnt, refname, strerror(errno));
3436 pos -= cnt;
3437
3438 scanp = endp = buf + cnt;
3439 if (at_tail && scanp[-1] == '\n')
3440 /* Looking at the final LF at the end of the file */
3441 scanp--;
3442 at_tail = 0;
3443
3444 while (buf < scanp) {
3445 /*
3446 * terminating LF of the previous line, or the beginning
3447 * of the buffer.
3448 */
3449 char *bp;
3450
3451 bp = find_beginning_of_line(buf, scanp);
3452
e5e73ff2 3453 if (*bp == '\n') {
98f85ff4 3454 /*
e5e73ff2
JK
3455 * The newline is the end of the previous line,
3456 * so we know we have complete line starting
3457 * at (bp + 1). Prefix it onto any prior data
3458 * we collected for the line and process it.
98f85ff4
JH
3459 */
3460 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3461 scanp = bp;
3462 endp = bp + 1;
e5e73ff2
JK
3463 ret = show_one_reflog_ent(&sb, fn, cb_data);
3464 strbuf_reset(&sb);
3465 if (ret)
3466 break;
3467 } else if (!pos) {
3468 /*
3469 * We are at the start of the buffer, and the
3470 * start of the file; there is no previous
3471 * line, and we have everything for this one.
3472 * Process it, and we can end the loop.
3473 */
3474 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3475 ret = show_one_reflog_ent(&sb, fn, cb_data);
3476 strbuf_reset(&sb);
3477 break;
98f85ff4 3478 }
e5e73ff2
JK
3479
3480 if (bp == buf) {
3481 /*
3482 * We are at the start of the buffer, and there
3483 * is more file to read backwards. Which means
3484 * we are in the middle of a line. Note that we
3485 * may get here even if *bp was a newline; that
3486 * just means we are at the exact end of the
3487 * previous line, rather than some spot in the
3488 * middle.
3489 *
3490 * Save away what we have to be combined with
3491 * the data from the next read.
3492 */
3493 strbuf_splice(&sb, 0, 0, buf, endp - buf);
98f85ff4 3494 break;
e5e73ff2 3495 }
9d33f7c2 3496 }
101d15e0 3497
2ff81662 3498 }
98f85ff4 3499 if (!ret && sb.len)
69216bf7 3500 die("BUG: reverse reflog parser had leftover data");
98f85ff4 3501
2ff81662 3502 fclose(logfp);
8ca78803 3503 strbuf_release(&sb);
2266bf27 3504 return ret;
2ff81662 3505}
e29cb53a 3506
dfefa935 3507int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
101d15e0 3508{
98f85ff4
JH
3509 FILE *logfp;
3510 struct strbuf sb = STRBUF_INIT;
3511 int ret = 0;
3512
3513 logfp = fopen(git_path("logs/%s", refname), "r");
3514 if (!logfp)
3515 return -1;
101d15e0 3516
98f85ff4
JH
3517 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3518 ret = show_one_reflog_ent(&sb, fn, cb_data);
3519 fclose(logfp);
3520 strbuf_release(&sb);
3521 return ret;
3522}
989c0e5d
MH
3523/*
3524 * Call fn for each reflog in the namespace indicated by name. name
3525 * must be empty or end with '/'. Name will be used as a scratch
3526 * space, but its contents will be restored before return.
3527 */
3528static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
eb8381c8 3529{
989c0e5d 3530 DIR *d = opendir(git_path("logs/%s", name->buf));
fcee5a14 3531 int retval = 0;
93c603fc 3532 struct dirent *de;
989c0e5d 3533 int oldlen = name->len;
eb8381c8 3534
93c603fc 3535 if (!d)
989c0e5d 3536 return name->len ? errno : 0;
eb8381c8 3537
93c603fc
MH
3538 while ((de = readdir(d)) != NULL) {
3539 struct stat st;
eb8381c8 3540
93c603fc
MH
3541 if (de->d_name[0] == '.')
3542 continue;
2975c770 3543 if (ends_with(de->d_name, ".lock"))
93c603fc 3544 continue;
989c0e5d
MH
3545 strbuf_addstr(name, de->d_name);
3546 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3547 ; /* silently ignore */
93c603fc 3548 } else {
eb8381c8 3549 if (S_ISDIR(st.st_mode)) {
989c0e5d
MH
3550 strbuf_addch(name, '/');
3551 retval = do_for_each_reflog(name, fn, cb_data);
eb8381c8
NP
3552 } else {
3553 unsigned char sha1[20];
7695d118 3554 if (read_ref_full(name->buf, 0, sha1, NULL))
989c0e5d 3555 retval = error("bad ref for %s", name->buf);
eb8381c8 3556 else
989c0e5d 3557 retval = fn(name->buf, sha1, 0, cb_data);
eb8381c8
NP
3558 }
3559 if (retval)
3560 break;
3561 }
989c0e5d 3562 strbuf_setlen(name, oldlen);
eb8381c8 3563 }
93c603fc 3564 closedir(d);
eb8381c8
NP
3565 return retval;
3566}
3567
3568int for_each_reflog(each_ref_fn fn, void *cb_data)
3569{
989c0e5d
MH
3570 int retval;
3571 struct strbuf name;
3572 strbuf_init(&name, PATH_MAX);
3573 retval = do_for_each_reflog(&name, fn, cb_data);
3574 strbuf_release(&name);
3575 return retval;
eb8381c8 3576}
3d9f037c 3577
b5c8ea2a 3578/**
8df4e511
MH
3579 * Information needed for a single ref update. Set new_sha1 to the new
3580 * value or to null_sha1 to delete the ref. To check the old value
3581 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3582 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3583 * not exist before update.
b5c8ea2a
MH
3584 */
3585struct ref_update {
16180334
MH
3586 /*
3587 * If (flags & REF_HAVE_NEW), set the reference to this value:
3588 */
b5c8ea2a 3589 unsigned char new_sha1[20];
16180334
MH
3590 /*
3591 * If (flags & REF_HAVE_OLD), check that the reference
3592 * previously had this value:
3593 */
b5c8ea2a 3594 unsigned char old_sha1[20];