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