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