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