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