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