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