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