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