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