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