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