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