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