]> git.ipfire.org Git - thirdparty/git.git/blame - refs.c
refs: read loose references lazily
[thirdparty/git.git] / refs.c
CommitLineData
95fc7512 1#include "cache.h"
85023577 2#include "refs.h"
cf0adba7
JH
3#include "object.h"
4#include "tag.h"
7155b727 5#include "dir.h"
95fc7512 6
bc5fd6d3
MH
7/*
8 * Make sure "ref" is something reasonable to have under ".git/refs/";
9 * We do not like it if:
10 *
11 * - any path component of it begins with ".", or
12 * - it has double dots "..", or
13 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
14 * - it ends with a "/".
15 * - it ends with ".lock"
16 * - it contains a "\" (backslash)
17 */
f4204ab9 18
bc5fd6d3
MH
19/* Return true iff ch is not allowed in reference names. */
20static inline int bad_ref_char(int ch)
21{
22 if (((unsigned) ch) <= ' ' || ch == 0x7f ||
23 ch == '~' || ch == '^' || ch == ':' || ch == '\\')
24 return 1;
25 /* 2.13 Pattern Matching Notation */
26 if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
27 return 1;
28 return 0;
29}
30
31/*
32 * Try to read one refname component from the front of refname. Return
33 * the length of the component found, or -1 if the component is not
34 * legal.
35 */
36static int check_refname_component(const char *refname, int flags)
37{
38 const char *cp;
39 char last = '\0';
40
41 for (cp = refname; ; cp++) {
42 char ch = *cp;
43 if (ch == '\0' || ch == '/')
44 break;
45 if (bad_ref_char(ch))
46 return -1; /* Illegal character in refname. */
47 if (last == '.' && ch == '.')
48 return -1; /* Refname contains "..". */
49 if (last == '@' && ch == '{')
50 return -1; /* Refname contains "@{". */
51 last = ch;
52 }
53 if (cp == refname)
dac529e4 54 return 0; /* Component has zero length. */
bc5fd6d3
MH
55 if (refname[0] == '.') {
56 if (!(flags & REFNAME_DOT_COMPONENT))
57 return -1; /* Component starts with '.'. */
58 /*
59 * Even if leading dots are allowed, don't allow "."
60 * as a component (".." is prevented by a rule above).
61 */
62 if (refname[1] == '\0')
63 return -1; /* Component equals ".". */
64 }
65 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
66 return -1; /* Refname ends with ".lock". */
67 return cp - refname;
68}
69
70int check_refname_format(const char *refname, int flags)
71{
72 int component_len, component_count = 0;
73
74 while (1) {
75 /* We are at the start of a path component. */
76 component_len = check_refname_component(refname, flags);
dac529e4 77 if (component_len <= 0) {
bc5fd6d3
MH
78 if ((flags & REFNAME_REFSPEC_PATTERN) &&
79 refname[0] == '*' &&
80 (refname[1] == '\0' || refname[1] == '/')) {
81 /* Accept one wildcard as a full refname component. */
82 flags &= ~REFNAME_REFSPEC_PATTERN;
83 component_len = 1;
84 } else {
85 return -1;
86 }
87 }
88 component_count++;
89 if (refname[component_len] == '\0')
90 break;
91 /* Skip to next component. */
92 refname += component_len + 1;
93 }
94
95 if (refname[component_len - 1] == '.')
96 return -1; /* Refname ends with '.'. */
97 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
98 return -1; /* Refname has only one component. */
99 return 0;
100}
101
102struct ref_entry;
e1e22e37 103
28e6a34e
MH
104/*
105 * Information used (along with the information in ref_entry) to
106 * describe a single cached reference. This data structure only
107 * occurs embedded in a union in struct ref_entry, and only when
108 * (ref_entry->flag & REF_DIR) is zero.
109 */
593f1bb8
MH
110struct ref_value {
111 unsigned char sha1[20];
112 unsigned char peeled[20];
113};
114
f006c42a
MH
115struct ref_cache;
116
28e6a34e
MH
117/*
118 * Information used (along with the information in ref_entry) to
119 * describe a level in the hierarchy of references. This data
120 * structure only occurs embedded in a union in struct ref_entry, and
121 * only when (ref_entry.flag & REF_DIR) is set. In that case,
122 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
123 * in the directory have already been read:
124 *
125 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
126 * or packed references, already read.
127 *
128 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
129 * references that hasn't been read yet (nor has any of its
130 * subdirectories).
131 *
132 * Entries within a directory are stored within a growable array of
133 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
134 * sorted are sorted by their component name in strcmp() order and the
135 * remaining entries are unsorted.
136 *
137 * Loose references are read lazily, one directory at a time. When a
138 * directory of loose references is read, then all of the references
139 * in that directory are stored, and REF_INCOMPLETE stubs are created
140 * for any subdirectories, but the subdirectories themselves are not
141 * read. The reading is triggered by get_ref_dir().
142 */
d3177275 143struct ref_dir {
e9c4c111 144 int nr, alloc;
e6ed3ca6
MH
145
146 /*
147 * Entries with index 0 <= i < sorted are sorted by name. New
148 * entries are appended to the list unsorted, and are sorted
149 * only when required; thus we avoid the need to sort the list
150 * after the addition of every reference.
151 */
152 int sorted;
153
f006c42a
MH
154 /* A pointer to the ref_cache that contains this ref_dir. */
155 struct ref_cache *ref_cache;
156
d3177275 157 struct ref_entry **entries;
e9c4c111
JP
158};
159
432ad41e
MH
160/* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */
161#define REF_KNOWS_PEELED 0x08
28e6a34e
MH
162
163/* ref_entry represents a directory of references */
432ad41e 164#define REF_DIR 0x10
cf0adba7 165
28e6a34e
MH
166/*
167 * Entry has not yet been read from disk (used only for REF_DIR
168 * entries representing loose references)
169 */
170#define REF_INCOMPLETE 0x20
171
432ad41e
MH
172/*
173 * A ref_entry represents either a reference or a "subdirectory" of
28e6a34e
MH
174 * references.
175 *
176 * Each directory in the reference namespace is represented by a
177 * ref_entry with (flags & REF_DIR) set and containing a subdir member
178 * that holds the entries in that directory that have been read so
179 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
180 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
181 * used for loose reference directories.
182 *
183 * References are represented by a ref_entry with (flags & REF_DIR)
184 * unset and a value member that describes the reference's value. The
185 * flag member is at the ref_entry level, but it is also needed to
186 * interpret the contents of the value field (in other words, a
187 * ref_value object is not very much use without the enclosing
188 * ref_entry).
432ad41e
MH
189 *
190 * Reference names cannot end with slash and directories' names are
191 * always stored with a trailing slash (except for the top-level
192 * directory, which is always denoted by ""). This has two nice
193 * consequences: (1) when the entries in each subdir are sorted
194 * lexicographically by name (as they usually are), the references in
195 * a whole tree can be generated in lexicographic order by traversing
196 * the tree in left-to-right, depth-first order; (2) the names of
197 * references and subdirectories cannot conflict, and therefore the
198 * presence of an empty subdirectory does not block the creation of a
199 * similarly-named reference. (The fact that reference names with the
200 * same leading components can conflict *with each other* is a
201 * separate issue that is regulated by is_refname_available().)
202 *
203 * Please note that the name field contains the fully-qualified
204 * reference (or subdirectory) name. Space could be saved by only
205 * storing the relative names. But that would require the full names
206 * to be generated on the fly when iterating in do_for_each_ref(), and
207 * would break callback functions, who have always been able to assume
208 * that the name strings that they are passed will not be freed during
209 * the iteration.
210 */
bc5fd6d3
MH
211struct ref_entry {
212 unsigned char flag; /* ISSYMREF? ISPACKED? */
593f1bb8 213 union {
432ad41e
MH
214 struct ref_value value; /* if not (flags&REF_DIR) */
215 struct ref_dir subdir; /* if (flags&REF_DIR) */
593f1bb8 216 } u;
432ad41e
MH
217 /*
218 * The full name of the reference (e.g., "refs/heads/master")
219 * or the full name of the directory with a trailing slash
220 * (e.g., "refs/heads/"):
221 */
bc5fd6d3
MH
222 char name[FLEX_ARRAY];
223};
e1e22e37 224
28e6a34e
MH
225static void read_loose_refs(const char *dirname, struct ref_dir *dir);
226
d7826d54
MH
227static struct ref_dir *get_ref_dir(struct ref_entry *entry)
228{
28e6a34e 229 struct ref_dir *dir;
d7826d54 230 assert(entry->flag & REF_DIR);
28e6a34e
MH
231 dir = &entry->u.subdir;
232 if (entry->flag & REF_INCOMPLETE) {
233 read_loose_refs(entry->name, dir);
234 entry->flag &= ~REF_INCOMPLETE;
235 }
236 return dir;
d7826d54
MH
237}
238
cddc4258
MH
239static struct ref_entry *create_ref_entry(const char *refname,
240 const unsigned char *sha1, int flag,
241 int check_name)
e1e22e37
LT
242{
243 int len;
cddc4258 244 struct ref_entry *ref;
e1e22e37 245
09116a1c 246 if (check_name &&
dfefa935
MH
247 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
248 die("Reference has invalid format: '%s'", refname);
cddc4258
MH
249 len = strlen(refname) + 1;
250 ref = xmalloc(sizeof(struct ref_entry) + len);
593f1bb8
MH
251 hashcpy(ref->u.value.sha1, sha1);
252 hashclr(ref->u.value.peeled);
cddc4258
MH
253 memcpy(ref->name, refname, len);
254 ref->flag = flag;
255 return ref;
256}
257
432ad41e
MH
258static void clear_ref_dir(struct ref_dir *dir);
259
732134ed
MH
260static void free_ref_entry(struct ref_entry *entry)
261{
432ad41e 262 if (entry->flag & REF_DIR)
d7826d54 263 clear_ref_dir(get_ref_dir(entry));
732134ed
MH
264 free(entry);
265}
266
432ad41e
MH
267/*
268 * Add a ref_entry to the end of dir (unsorted). Entry is always
269 * stored directly in dir; no recursion into subdirectories is
270 * done.
271 */
272static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
cddc4258 273{
432ad41e
MH
274 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
275 dir->entries[dir->nr++] = entry;
c774aab9
JP
276}
277
432ad41e
MH
278/*
279 * Clear and free all entries in dir, recursively.
280 */
d3177275 281static void clear_ref_dir(struct ref_dir *dir)
bc5fd6d3
MH
282{
283 int i;
d3177275
MH
284 for (i = 0; i < dir->nr; i++)
285 free_ref_entry(dir->entries[i]);
286 free(dir->entries);
287 dir->sorted = dir->nr = dir->alloc = 0;
288 dir->entries = NULL;
bc5fd6d3
MH
289}
290
432ad41e
MH
291/*
292 * Create a struct ref_entry object for the specified dirname.
293 * dirname is the name of the directory with a trailing slash (e.g.,
294 * "refs/heads/") or "" for the top-level directory.
295 */
f006c42a 296static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
28e6a34e 297 const char *dirname, int incomplete)
432ad41e
MH
298{
299 struct ref_entry *direntry;
300 int len = strlen(dirname);
301 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
302 memcpy(direntry->name, dirname, len + 1);
f006c42a 303 direntry->u.subdir.ref_cache = ref_cache;
28e6a34e 304 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
432ad41e
MH
305 return direntry;
306}
307
e9c4c111 308static int ref_entry_cmp(const void *a, const void *b)
c774aab9 309{
e9c4c111
JP
310 struct ref_entry *one = *(struct ref_entry **)a;
311 struct ref_entry *two = *(struct ref_entry **)b;
312 return strcmp(one->name, two->name);
313}
c774aab9 314
d3177275 315static void sort_ref_dir(struct ref_dir *dir);
bc5fd6d3 316
432ad41e
MH
317/*
318 * Return the entry with the given refname from the ref_dir
319 * (non-recursively), sorting dir if necessary. Return NULL if no
28e6a34e 320 * such entry is found. dir must already be complete.
432ad41e 321 */
d3177275 322static struct ref_entry *search_ref_dir(struct ref_dir *dir, const char *refname)
bc5fd6d3
MH
323{
324 struct ref_entry *e, **r;
325 int len;
326
432ad41e 327 if (refname == NULL || !dir->nr)
bc5fd6d3
MH
328 return NULL;
329
d3177275 330 sort_ref_dir(dir);
432ad41e 331
bc5fd6d3
MH
332 len = strlen(refname) + 1;
333 e = xmalloc(sizeof(struct ref_entry) + len);
334 memcpy(e->name, refname, len);
335
d3177275 336 r = bsearch(&e, dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
bc5fd6d3
MH
337
338 free(e);
339
340 if (r == NULL)
341 return NULL;
342
343 return *r;
344}
345
f348ac92
MH
346/*
347 * Search for a directory entry directly within dir (without
348 * recursing). Sort dir if necessary. subdirname must be a directory
349 * name (i.e., end in '/'). If mkdir is set, then create the
350 * directory if it is missing; otherwise, return NULL if the desired
28e6a34e 351 * directory cannot be found. dir must already be complete.
f348ac92 352 */
3f3aa1bc
MH
353static struct ref_dir *search_for_subdir(struct ref_dir *dir,
354 const char *subdirname, int mkdir)
f348ac92
MH
355{
356 struct ref_entry *entry = search_ref_dir(dir, subdirname);
357 if (!entry) {
358 if (!mkdir)
359 return NULL;
28e6a34e
MH
360 /*
361 * Since dir is complete, the absence of a subdir
362 * means that the subdir really doesn't exist;
363 * therefore, create an empty record for it but mark
364 * the record complete.
365 */
366 entry = create_dir_entry(dir->ref_cache, subdirname, 0);
f348ac92
MH
367 add_entry_to_dir(dir, entry);
368 }
3f3aa1bc 369 return get_ref_dir(entry);
f348ac92
MH
370}
371
432ad41e
MH
372/*
373 * If refname is a reference name, find the ref_dir within the dir
374 * tree that should hold refname. If refname is a directory name
375 * (i.e., ends in '/'), then return that ref_dir itself. dir must
28e6a34e
MH
376 * represent the top-level directory and must already be complete.
377 * Sort ref_dirs and recurse into subdirectories as necessary. If
378 * mkdir is set, then create any missing directories; otherwise,
379 * return NULL if the desired directory cannot be found.
432ad41e
MH
380 */
381static struct ref_dir *find_containing_dir(struct ref_dir *dir,
382 const char *refname, int mkdir)
383{
5fa04418
MH
384 struct strbuf dirname;
385 const char *slash;
386 strbuf_init(&dirname, PATH_MAX);
387 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
3f3aa1bc 388 struct ref_dir *subdir;
5fa04418
MH
389 strbuf_add(&dirname,
390 refname + dirname.len,
391 (slash + 1) - (refname + dirname.len));
3f3aa1bc
MH
392 subdir = search_for_subdir(dir, dirname.buf, mkdir);
393 if (!subdir)
f348ac92 394 break;
3f3aa1bc 395 dir = subdir;
432ad41e
MH
396 }
397
5fa04418 398 strbuf_release(&dirname);
432ad41e
MH
399 return dir;
400}
401
402/*
403 * Find the value entry with the given name in dir, sorting ref_dirs
404 * and recursing into subdirectories as necessary. If the name is not
405 * found or it corresponds to a directory entry, return NULL.
406 */
407static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
408{
409 struct ref_entry *entry;
410 dir = find_containing_dir(dir, refname, 0);
411 if (!dir)
412 return NULL;
413 entry = search_ref_dir(dir, refname);
414 return (entry && !(entry->flag & REF_DIR)) ? entry : NULL;
415}
416
417/*
418 * Add a ref_entry to the ref_dir (unsorted), recursing into
419 * subdirectories as necessary. dir must represent the top-level
420 * directory. Return 0 on success.
421 */
422static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
423{
424 dir = find_containing_dir(dir, ref->name, 1);
425 if (!dir)
426 return -1;
427 add_entry_to_dir(dir, ref);
428 return 0;
429}
430
202a56a9
MH
431/*
432 * Emit a warning and return true iff ref1 and ref2 have the same name
433 * and the same sha1. Die if they have the same name but different
434 * sha1s.
435 */
436static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
437{
432ad41e 438 if (strcmp(ref1->name, ref2->name))
202a56a9 439 return 0;
432ad41e
MH
440
441 /* Duplicate name; make sure that they don't conflict: */
442
443 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
444 /* This is impossible by construction */
445 die("Reference directory conflict: %s", ref1->name);
446
447 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
448 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
449
450 warning("Duplicated ref: %s", ref1->name);
451 return 1;
202a56a9
MH
452}
453
e6ed3ca6 454/*
432ad41e
MH
455 * Sort the entries in dir non-recursively (if they are not already
456 * sorted) and remove any duplicate entries.
e6ed3ca6 457 */
d3177275 458static void sort_ref_dir(struct ref_dir *dir)
e9c4c111 459{
202a56a9 460 int i, j;
81a79d8e 461 struct ref_entry *last = NULL;
c774aab9 462
e6ed3ca6
MH
463 /*
464 * This check also prevents passing a zero-length array to qsort(),
465 * which is a problem on some platforms.
466 */
d3177275 467 if (dir->sorted == dir->nr)
e9c4c111 468 return;
c774aab9 469
d3177275 470 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
c774aab9 471
81a79d8e
MH
472 /* Remove any duplicates: */
473 for (i = 0, j = 0; j < dir->nr; j++) {
474 struct ref_entry *entry = dir->entries[j];
475 if (last && is_dup_ref(last, entry))
476 free_ref_entry(entry);
477 else
478 last = dir->entries[i++] = entry;
e9c4c111 479 }
81a79d8e 480 dir->sorted = dir->nr = i;
e9c4c111 481}
c774aab9 482
bc5fd6d3 483#define DO_FOR_EACH_INCLUDE_BROKEN 01
c774aab9 484
bc5fd6d3 485static struct ref_entry *current_ref;
c774aab9 486
bc5fd6d3
MH
487static int do_one_ref(const char *base, each_ref_fn fn, int trim,
488 int flags, void *cb_data, struct ref_entry *entry)
489{
429213e4 490 int retval;
bc5fd6d3
MH
491 if (prefixcmp(entry->name, base))
492 return 0;
c774aab9 493
bc5fd6d3
MH
494 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
495 if (entry->flag & REF_ISBROKEN)
496 return 0; /* ignore broken refs e.g. dangling symref */
593f1bb8 497 if (!has_sha1_file(entry->u.value.sha1)) {
bc5fd6d3
MH
498 error("%s does not point to a valid object!", entry->name);
499 return 0;
500 }
501 }
502 current_ref = entry;
593f1bb8 503 retval = fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data);
429213e4
MH
504 current_ref = NULL;
505 return retval;
bc5fd6d3 506}
c774aab9 507
c36b5bc2 508/*
d3177275 509 * Call fn for each reference in dir that has index in the range
432ad41e
MH
510 * offset <= index < dir->nr. Recurse into subdirectories that are in
511 * that index range, sorting them before iterating. This function
512 * does not sort dir itself; it should be sorted beforehand.
c36b5bc2 513 */
d3177275
MH
514static int do_for_each_ref_in_dir(struct ref_dir *dir, int offset,
515 const char *base,
516 each_ref_fn fn, int trim, int flags, void *cb_data)
c36b5bc2
MH
517{
518 int i;
d3177275
MH
519 assert(dir->sorted == dir->nr);
520 for (i = offset; i < dir->nr; i++) {
432ad41e
MH
521 struct ref_entry *entry = dir->entries[i];
522 int retval;
523 if (entry->flag & REF_DIR) {
d7826d54
MH
524 struct ref_dir *subdir = get_ref_dir(entry);
525 sort_ref_dir(subdir);
526 retval = do_for_each_ref_in_dir(subdir, 0,
432ad41e
MH
527 base, fn, trim, flags, cb_data);
528 } else {
529 retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
530 }
c36b5bc2
MH
531 if (retval)
532 return retval;
533 }
534 return 0;
535}
536
b3fd060f 537/*
d3177275 538 * Call fn for each reference in the union of dir1 and dir2, in order
432ad41e
MH
539 * by refname. Recurse into subdirectories. If a value entry appears
540 * in both dir1 and dir2, then only process the version that is in
541 * dir2. The input dirs must already be sorted, but subdirs will be
542 * sorted as needed.
b3fd060f 543 */
d3177275
MH
544static int do_for_each_ref_in_dirs(struct ref_dir *dir1,
545 struct ref_dir *dir2,
546 const char *base, each_ref_fn fn, int trim,
547 int flags, void *cb_data)
b3fd060f
MH
548{
549 int retval;
550 int i1 = 0, i2 = 0;
551
d3177275
MH
552 assert(dir1->sorted == dir1->nr);
553 assert(dir2->sorted == dir2->nr);
432ad41e
MH
554 while (1) {
555 struct ref_entry *e1, *e2;
556 int cmp;
557 if (i1 == dir1->nr) {
558 return do_for_each_ref_in_dir(dir2, i2,
559 base, fn, trim, flags, cb_data);
560 }
561 if (i2 == dir2->nr) {
562 return do_for_each_ref_in_dir(dir1, i1,
563 base, fn, trim, flags, cb_data);
564 }
565 e1 = dir1->entries[i1];
566 e2 = dir2->entries[i2];
567 cmp = strcmp(e1->name, e2->name);
568 if (cmp == 0) {
569 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
570 /* Both are directories; descend them in parallel. */
d7826d54
MH
571 struct ref_dir *subdir1 = get_ref_dir(e1);
572 struct ref_dir *subdir2 = get_ref_dir(e2);
573 sort_ref_dir(subdir1);
574 sort_ref_dir(subdir2);
432ad41e 575 retval = do_for_each_ref_in_dirs(
d7826d54 576 subdir1, subdir2,
432ad41e
MH
577 base, fn, trim, flags, cb_data);
578 i1++;
579 i2++;
580 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
581 /* Both are references; ignore the one from dir1. */
582 retval = do_one_ref(base, fn, trim, flags, cb_data, e2);
583 i1++;
584 i2++;
585 } else {
586 die("conflict between reference and directory: %s",
587 e1->name);
588 }
b3fd060f 589 } else {
432ad41e
MH
590 struct ref_entry *e;
591 if (cmp < 0) {
592 e = e1;
b3fd060f 593 i1++;
432ad41e
MH
594 } else {
595 e = e2;
596 i2++;
597 }
598 if (e->flag & REF_DIR) {
d7826d54
MH
599 struct ref_dir *subdir = get_ref_dir(e);
600 sort_ref_dir(subdir);
432ad41e 601 retval = do_for_each_ref_in_dir(
d7826d54 602 subdir, 0,
432ad41e
MH
603 base, fn, trim, flags, cb_data);
604 } else {
605 retval = do_one_ref(base, fn, trim, flags, cb_data, e);
b3fd060f
MH
606 }
607 }
608 if (retval)
609 return retval;
610 }
d3177275
MH
611 if (i1 < dir1->nr)
612 return do_for_each_ref_in_dir(dir1, i1,
613 base, fn, trim, flags, cb_data);
614 if (i2 < dir2->nr)
615 return do_for_each_ref_in_dir(dir2, i2,
616 base, fn, trim, flags, cb_data);
b3fd060f
MH
617 return 0;
618}
619
d66da478
MH
620/*
621 * Return true iff refname1 and refname2 conflict with each other.
622 * Two reference names conflict if one of them exactly matches the
623 * leading components of the other; e.g., "foo/bar" conflicts with
624 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
625 * "foo/barbados".
626 */
627static int names_conflict(const char *refname1, const char *refname2)
628{
5a4d4947
MH
629 for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
630 ;
631 return (*refname1 == '\0' && *refname2 == '/')
632 || (*refname1 == '/' && *refname2 == '\0');
633}
634
635struct name_conflict_cb {
636 const char *refname;
637 const char *oldrefname;
638 const char *conflicting_refname;
639};
640
641static int name_conflict_fn(const char *existingrefname, const unsigned char *sha1,
642 int flags, void *cb_data)
643{
644 struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
645 if (data->oldrefname && !strcmp(data->oldrefname, existingrefname))
646 return 0;
647 if (names_conflict(data->refname, existingrefname)) {
648 data->conflicting_refname = existingrefname;
649 return 1;
d66da478 650 }
5a4d4947 651 return 0;
d66da478
MH
652}
653
bc5fd6d3
MH
654/*
655 * Return true iff a reference named refname could be created without
5a4d4947
MH
656 * conflicting with the name of an existing reference in array. If
657 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
658 * (e.g., because oldrefname is scheduled for deletion in the same
bc5fd6d3
MH
659 * operation).
660 */
661static int is_refname_available(const char *refname, const char *oldrefname,
d3177275 662 struct ref_dir *dir)
bc5fd6d3 663{
5a4d4947
MH
664 struct name_conflict_cb data;
665 data.refname = refname;
666 data.oldrefname = oldrefname;
667 data.conflicting_refname = NULL;
668
d3177275
MH
669 sort_ref_dir(dir);
670 if (do_for_each_ref_in_dir(dir, 0, "", name_conflict_fn,
671 0, DO_FOR_EACH_INCLUDE_BROKEN,
672 &data)) {
5a4d4947
MH
673 error("'%s' exists; cannot create '%s'",
674 data.conflicting_refname, refname);
675 return 0;
bc5fd6d3
MH
676 }
677 return 1;
e1e22e37
LT
678}
679
5e290ff7
JH
680/*
681 * Future: need to be in "struct repository"
682 * when doing a full libification.
683 */
79c7ca54
MH
684static struct ref_cache {
685 struct ref_cache *next;
d12229f5
MH
686 struct ref_entry *loose;
687 struct ref_entry *packed;
ce40979c
MH
688 /* The submodule name, or "" for the main repo. */
689 char name[FLEX_ARRAY];
79c7ca54 690} *ref_cache;
0e88c130 691
760c4512 692static void clear_packed_ref_cache(struct ref_cache *refs)
e1e22e37 693{
d12229f5
MH
694 if (refs->packed) {
695 free_ref_entry(refs->packed);
696 refs->packed = NULL;
697 }
5e290ff7 698}
e1e22e37 699
760c4512
MH
700static void clear_loose_ref_cache(struct ref_cache *refs)
701{
d12229f5
MH
702 if (refs->loose) {
703 free_ref_entry(refs->loose);
704 refs->loose = NULL;
705 }
760c4512
MH
706}
707
79c7ca54 708static struct ref_cache *create_ref_cache(const char *submodule)
e5dbf605 709{
ce40979c 710 int len;
79c7ca54 711 struct ref_cache *refs;
ce40979c
MH
712 if (!submodule)
713 submodule = "";
714 len = strlen(submodule) + 1;
79c7ca54 715 refs = xcalloc(1, sizeof(struct ref_cache) + len);
ce40979c 716 memcpy(refs->name, submodule, len);
e5dbf605
MH
717 return refs;
718}
719
4349a668 720/*
79c7ca54 721 * Return a pointer to a ref_cache for the specified submodule. For
4349a668
MH
722 * the main repository, use submodule==NULL. The returned structure
723 * will be allocated and initialized but not necessarily populated; it
724 * should not be freed.
725 */
79c7ca54 726static struct ref_cache *get_ref_cache(const char *submodule)
4349a668 727{
79c7ca54 728 struct ref_cache *refs = ref_cache;
0e88c130
MH
729 if (!submodule)
730 submodule = "";
731 while (refs) {
732 if (!strcmp(submodule, refs->name))
733 return refs;
734 refs = refs->next;
4349a668 735 }
0e88c130 736
79c7ca54
MH
737 refs = create_ref_cache(submodule);
738 refs->next = ref_cache;
739 ref_cache = refs;
0e88c130 740 return refs;
4349a668
MH
741}
742
8be8bde7 743void invalidate_ref_cache(const char *submodule)
f130b116 744{
c5f29abd
MH
745 struct ref_cache *refs = get_ref_cache(submodule);
746 clear_packed_ref_cache(refs);
747 clear_loose_ref_cache(refs);
5e290ff7 748}
e1e22e37 749
bc5fd6d3
MH
750/*
751 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
752 * Return a pointer to the refname within the line (null-terminated),
753 * or NULL if there was a problem.
754 */
755static const char *parse_ref_line(char *line, unsigned char *sha1)
756{
757 /*
758 * 42: the answer to everything.
759 *
760 * In this case, it happens to be the answer to
761 * 40 (length of sha1 hex representation)
762 * +1 (space in between hex and name)
763 * +1 (newline at the end of the line)
764 */
765 int len = strlen(line) - 42;
766
767 if (len <= 0)
768 return NULL;
769 if (get_sha1_hex(line, sha1) < 0)
770 return NULL;
771 if (!isspace(line[40]))
772 return NULL;
773 line += 41;
774 if (isspace(*line))
775 return NULL;
776 if (line[len] != '\n')
777 return NULL;
778 line[len] = 0;
779
780 return line;
781}
782
d3177275 783static void read_packed_refs(FILE *f, struct ref_dir *dir)
f4204ab9 784{
e9c4c111 785 struct ref_entry *last = NULL;
f4204ab9
JH
786 char refline[PATH_MAX];
787 int flag = REF_ISPACKED;
788
789 while (fgets(refline, sizeof(refline), f)) {
790 unsigned char sha1[20];
dfefa935 791 const char *refname;
f4204ab9
JH
792 static const char header[] = "# pack-refs with:";
793
794 if (!strncmp(refline, header, sizeof(header)-1)) {
795 const char *traits = refline + sizeof(header) - 1;
796 if (strstr(traits, " peeled "))
797 flag |= REF_KNOWS_PEELED;
798 /* perhaps other traits later as well */
799 continue;
800 }
801
dfefa935
MH
802 refname = parse_ref_line(refline, sha1);
803 if (refname) {
dd73ecd1 804 last = create_ref_entry(refname, sha1, flag, 1);
d3177275 805 add_ref(dir, last);
f4204ab9
JH
806 continue;
807 }
808 if (last &&
809 refline[0] == '^' &&
810 strlen(refline) == 42 &&
811 refline[41] == '\n' &&
812 !get_sha1_hex(refline + 1, sha1))
593f1bb8 813 hashcpy(last->u.value.peeled, sha1);
f4204ab9 814 }
f4204ab9
JH
815}
816
d3177275 817static struct ref_dir *get_packed_refs(struct ref_cache *refs)
5e290ff7 818{
d12229f5 819 if (!refs->packed) {
4349a668
MH
820 const char *packed_refs_file;
821 FILE *f;
0bad611b 822
28e6a34e 823 refs->packed = create_dir_entry(refs, "", 0);
316b097a
MH
824 if (*refs->name)
825 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
4349a668
MH
826 else
827 packed_refs_file = git_path("packed-refs");
828 f = fopen(packed_refs_file, "r");
e1e22e37 829 if (f) {
d7826d54 830 read_packed_refs(f, get_ref_dir(refs->packed));
e1e22e37 831 fclose(f);
e1e22e37 832 }
e1e22e37 833 }
d7826d54 834 return get_ref_dir(refs->packed);
e1e22e37
LT
835}
836
30249ee6
MH
837void add_packed_ref(const char *refname, const unsigned char *sha1)
838{
839 add_ref(get_packed_refs(get_ref_cache(NULL)),
840 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
841}
842
abc39098 843/*
28e6a34e
MH
844 * Read the loose references from the namespace dirname into dir
845 * (without recursing). dirname must end with '/'. dir must be the
846 * directory entry corresponding to dirname.
abc39098 847 */
423a1afc 848static void read_loose_refs(const char *dirname, struct ref_dir *dir)
e1e22e37 849{
423a1afc 850 struct ref_cache *refs = dir->ref_cache;
d3177275 851 DIR *d;
0bad611b 852 const char *path;
d5fdae67 853 struct dirent *de;
abc39098 854 int dirnamelen = strlen(dirname);
72b64b44 855 struct strbuf refname;
0bad611b 856
3b124823 857 if (*refs->name)
66a3d20b 858 path = git_path_submodule(refs->name, "%s", dirname);
0bad611b 859 else
66a3d20b 860 path = git_path("%s", dirname);
0bad611b 861
d3177275 862 d = opendir(path);
d5fdae67
MH
863 if (!d)
864 return;
865
66a3d20b
MH
866 strbuf_init(&refname, dirnamelen + 257);
867 strbuf_add(&refname, dirname, dirnamelen);
d5fdae67
MH
868
869 while ((de = readdir(d)) != NULL) {
870 unsigned char sha1[20];
871 struct stat st;
872 int flag;
d5fdae67
MH
873 const char *refdir;
874
875 if (de->d_name[0] == '.')
876 continue;
d5fdae67
MH
877 if (has_extension(de->d_name, ".lock"))
878 continue;
72b64b44 879 strbuf_addstr(&refname, de->d_name);
d5fdae67 880 refdir = *refs->name
72b64b44
MH
881 ? git_path_submodule(refs->name, "%s", refname.buf)
882 : git_path("%s", refname.buf);
883 if (stat(refdir, &st) < 0) {
884 ; /* silently ignore */
885 } else if (S_ISDIR(st.st_mode)) {
abc39098 886 strbuf_addch(&refname, '/');
28e6a34e
MH
887 add_entry_to_dir(dir,
888 create_dir_entry(refs, refname.buf, 1));
72b64b44
MH
889 } else {
890 if (*refs->name) {
891 hashclr(sha1);
892 flag = 0;
893 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
894 hashclr(sha1);
895 flag |= REF_ISBROKEN;
896 }
897 } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
09116a1c
JH
898 hashclr(sha1);
899 flag |= REF_ISBROKEN;
900 }
9f2fb4a3
MH
901 add_entry_to_dir(dir,
902 create_ref_entry(refname.buf, sha1, flag, 1));
e1e22e37 903 }
66a3d20b 904 strbuf_setlen(&refname, dirnamelen);
e1e22e37 905 }
72b64b44 906 strbuf_release(&refname);
d5fdae67 907 closedir(d);
e1e22e37
LT
908}
909
d3177275 910static struct ref_dir *get_loose_refs(struct ref_cache *refs)
e1e22e37 911{
d12229f5 912 if (!refs->loose) {
28e6a34e
MH
913 /*
914 * Mark the top-level directory complete because we
915 * are about to read the only subdirectory that can
916 * hold references:
917 */
918 refs->loose = create_dir_entry(refs, "", 0);
919 /*
920 * Create an incomplete entry for "refs/":
921 */
922 add_entry_to_dir(get_ref_dir(refs->loose),
923 create_dir_entry(refs, "refs/", 1));
e1e22e37 924 }
d7826d54 925 return get_ref_dir(refs->loose);
e1e22e37
LT
926}
927
ca8db142
LT
928/* We allow "recursive" symbolic refs. Only within reason, though */
929#define MAXDEPTH 5
0ebde32c
LT
930#define MAXREFLEN (1024)
931
e5fa45c1
JH
932/*
933 * Called by resolve_gitlink_ref_recursive() after it failed to read
b0626608
MH
934 * from the loose refs in ref_cache refs. Find <refname> in the
935 * packed-refs file for the submodule.
e5fa45c1 936 */
b0626608 937static int resolve_gitlink_packed_ref(struct ref_cache *refs,
85be1fe3 938 const char *refname, unsigned char *sha1)
0ebde32c 939{
2c5c66be 940 struct ref_entry *ref;
d3177275 941 struct ref_dir *dir = get_packed_refs(refs);
0ebde32c 942
432ad41e 943 ref = find_ref(dir, refname);
b0626608
MH
944 if (ref == NULL)
945 return -1;
946
593f1bb8 947 memcpy(sha1, ref->u.value.sha1, 20);
b0626608 948 return 0;
0ebde32c
LT
949}
950
b0626608 951static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
85be1fe3 952 const char *refname, unsigned char *sha1,
dfefa935 953 int recursion)
0ebde32c 954{
064d51dc 955 int fd, len;
0ebde32c 956 char buffer[128], *p;
064d51dc 957 char *path;
0ebde32c 958
064d51dc 959 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
0ebde32c 960 return -1;
064d51dc
MH
961 path = *refs->name
962 ? git_path_submodule(refs->name, "%s", refname)
963 : git_path("%s", refname);
964 fd = open(path, O_RDONLY);
0ebde32c 965 if (fd < 0)
b0626608 966 return resolve_gitlink_packed_ref(refs, refname, sha1);
0ebde32c
LT
967
968 len = read(fd, buffer, sizeof(buffer)-1);
969 close(fd);
970 if (len < 0)
971 return -1;
972 while (len && isspace(buffer[len-1]))
973 len--;
974 buffer[len] = 0;
975
976 /* Was it a detached head or an old-fashioned symlink? */
85be1fe3 977 if (!get_sha1_hex(buffer, sha1))
0ebde32c
LT
978 return 0;
979
980 /* Symref? */
981 if (strncmp(buffer, "ref:", 4))
982 return -1;
983 p = buffer + 4;
984 while (isspace(*p))
985 p++;
986
064d51dc 987 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
0ebde32c
LT
988}
989
85be1fe3 990int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
0ebde32c
LT
991{
992 int len = strlen(path), retval;
064d51dc 993 char *submodule;
b0626608 994 struct ref_cache *refs;
0ebde32c
LT
995
996 while (len && path[len-1] == '/')
997 len--;
998 if (!len)
999 return -1;
b0626608
MH
1000 submodule = xstrndup(path, len);
1001 refs = get_ref_cache(submodule);
1002 free(submodule);
1003
064d51dc 1004 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
0ebde32c
LT
1005 return retval;
1006}
ca8db142 1007
4886b89f 1008/*
c224ca7f
MH
1009 * Try to read ref from the packed references. On success, set sha1
1010 * and return 0; otherwise, return -1.
4886b89f 1011 */
dfefa935 1012static int get_packed_ref(const char *refname, unsigned char *sha1)
c224ca7f 1013{
d3177275 1014 struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
432ad41e 1015 struct ref_entry *entry = find_ref(packed, refname);
2c5c66be 1016 if (entry) {
593f1bb8 1017 hashcpy(sha1, entry->u.value.sha1);
2c5c66be 1018 return 0;
c224ca7f
MH
1019 }
1020 return -1;
1021}
1022
8d68493f 1023const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
8a65ff76 1024{
0104ca09
HO
1025 int depth = MAXDEPTH;
1026 ssize_t len;
a876ed83 1027 char buffer[256];
dfefa935 1028 static char refname_buffer[256];
ca8db142 1029
8da19775
JH
1030 if (flag)
1031 *flag = 0;
1032
dfefa935 1033 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
8384d788
MH
1034 return NULL;
1035
a876ed83 1036 for (;;) {
55956350 1037 char path[PATH_MAX];
a876ed83
JH
1038 struct stat st;
1039 char *buf;
1040 int fd;
8a65ff76 1041
a876ed83
JH
1042 if (--depth < 0)
1043 return NULL;
ca8db142 1044
dfefa935 1045 git_snpath(path, sizeof(path), "%s", refname);
c224ca7f 1046
a876ed83 1047 if (lstat(path, &st) < 0) {
c224ca7f
MH
1048 if (errno != ENOENT)
1049 return NULL;
1050 /*
1051 * The loose reference file does not exist;
1052 * check for a packed reference.
1053 */
dfefa935 1054 if (!get_packed_ref(refname, sha1)) {
c224ca7f
MH
1055 if (flag)
1056 *flag |= REF_ISPACKED;
dfefa935 1057 return refname;
434cd0cd 1058 }
c224ca7f
MH
1059 /* The reference is not a packed reference, either. */
1060 if (reading) {
a876ed83 1061 return NULL;
c224ca7f
MH
1062 } else {
1063 hashclr(sha1);
dfefa935 1064 return refname;
c224ca7f 1065 }
a876ed83 1066 }
ca8db142 1067
a876ed83
JH
1068 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1069 if (S_ISLNK(st.st_mode)) {
1070 len = readlink(path, buffer, sizeof(buffer)-1);
7bb2bf8e
MH
1071 if (len < 0)
1072 return NULL;
b54cb795 1073 buffer[len] = 0;
1f58a038
MH
1074 if (!prefixcmp(buffer, "refs/") &&
1075 !check_refname_format(buffer, 0)) {
dfefa935
MH
1076 strcpy(refname_buffer, buffer);
1077 refname = refname_buffer;
8da19775
JH
1078 if (flag)
1079 *flag |= REF_ISSYMREF;
a876ed83
JH
1080 continue;
1081 }
ca8db142 1082 }
a876ed83 1083
7a21632f
DS
1084 /* Is it a directory? */
1085 if (S_ISDIR(st.st_mode)) {
1086 errno = EISDIR;
1087 return NULL;
1088 }
1089
a876ed83
JH
1090 /*
1091 * Anything else, just open it and try to use it as
1092 * a ref
1093 */
1094 fd = open(path, O_RDONLY);
1095 if (fd < 0)
1096 return NULL;
93d26e4c 1097 len = read_in_full(fd, buffer, sizeof(buffer)-1);
a876ed83 1098 close(fd);
28775050
MH
1099 if (len < 0)
1100 return NULL;
1101 while (len && isspace(buffer[len-1]))
1102 len--;
1103 buffer[len] = '\0';
a876ed83
JH
1104
1105 /*
1106 * Is it a symbolic ref?
1107 */
28775050 1108 if (prefixcmp(buffer, "ref:"))
a876ed83 1109 break;
55956350
JH
1110 if (flag)
1111 *flag |= REF_ISSYMREF;
a876ed83 1112 buf = buffer + 4;
28775050
MH
1113 while (isspace(*buf))
1114 buf++;
313fb010 1115 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
55956350
JH
1116 if (flag)
1117 *flag |= REF_ISBROKEN;
313fb010
MH
1118 return NULL;
1119 }
dfefa935 1120 refname = strcpy(refname_buffer, buf);
8a65ff76 1121 }
f989fea0
MH
1122 /* Please note that FETCH_HEAD has a second line containing other data. */
1123 if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
55956350
JH
1124 if (flag)
1125 *flag |= REF_ISBROKEN;
a876ed83 1126 return NULL;
629cd3ac 1127 }
dfefa935 1128 return refname;
a876ed83
JH
1129}
1130
96ec7b1e
NTND
1131char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1132{
8cad4744 1133 const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
96ec7b1e
NTND
1134 return ret ? xstrdup(ret) : NULL;
1135}
1136
d08bae7e
IL
1137/* The argument to filter_refs */
1138struct ref_filter {
1139 const char *pattern;
1140 each_ref_fn *fn;
1141 void *cb_data;
1142};
1143
dfefa935 1144int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
a876ed83 1145{
8d68493f 1146 if (resolve_ref_unsafe(refname, sha1, reading, flags))
a876ed83
JH
1147 return 0;
1148 return -1;
8a65ff76
LT
1149}
1150
dfefa935 1151int read_ref(const char *refname, unsigned char *sha1)
c6893323 1152{
dfefa935 1153 return read_ref_full(refname, sha1, 1, NULL);
c6893323
NTND
1154}
1155
bc5fd6d3 1156int ref_exists(const char *refname)
ef06b918 1157{
bc5fd6d3
MH
1158 unsigned char sha1[20];
1159 return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
ef06b918
JH
1160}
1161
85be1fe3 1162static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
dfefa935 1163 void *data)
d08bae7e
IL
1164{
1165 struct ref_filter *filter = (struct ref_filter *)data;
dfefa935 1166 if (fnmatch(filter->pattern, refname, 0))
d08bae7e 1167 return 0;
85be1fe3 1168 return filter->fn(refname, sha1, flags, filter->cb_data);
d08bae7e
IL
1169}
1170
dfefa935 1171int peel_ref(const char *refname, unsigned char *sha1)
cf0adba7
JH
1172{
1173 int flag;
1174 unsigned char base[20];
1175 struct object *o;
1176
dfefa935
MH
1177 if (current_ref && (current_ref->name == refname
1178 || !strcmp(current_ref->name, refname))) {
0ae91be0 1179 if (current_ref->flag & REF_KNOWS_PEELED) {
593f1bb8 1180 hashcpy(sha1, current_ref->u.value.peeled);
0ae91be0
SP
1181 return 0;
1182 }
593f1bb8 1183 hashcpy(base, current_ref->u.value.sha1);
0ae91be0
SP
1184 goto fallback;
1185 }
1186
dfefa935 1187 if (read_ref_full(refname, base, 1, &flag))
cf0adba7
JH
1188 return -1;
1189
1190 if ((flag & REF_ISPACKED)) {
d3177275 1191 struct ref_dir *dir = get_packed_refs(get_ref_cache(NULL));
432ad41e 1192 struct ref_entry *r = find_ref(dir, refname);
cf0adba7 1193
e9c4c111 1194 if (r != NULL && r->flag & REF_KNOWS_PEELED) {
593f1bb8 1195 hashcpy(sha1, r->u.value.peeled);
e9c4c111 1196 return 0;
cf0adba7 1197 }
cf0adba7
JH
1198 }
1199
0ae91be0 1200fallback:
cf0adba7 1201 o = parse_object(base);
8c87dc77 1202 if (o && o->type == OBJ_TAG) {
dfefa935 1203 o = deref_tag(o, refname, 0);
cf0adba7
JH
1204 if (o) {
1205 hashcpy(sha1, o->sha1);
1206 return 0;
1207 }
1208 }
1209 return -1;
1210}
1211
bc5fd6d3
MH
1212struct warn_if_dangling_data {
1213 FILE *fp;
1214 const char *refname;
1215 const char *msg_fmt;
1216};
1217
1218static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1219 int flags, void *cb_data)
1220{
1221 struct warn_if_dangling_data *d = cb_data;
1222 const char *resolves_to;
1223 unsigned char junk[20];
1224
1225 if (!(flags & REF_ISSYMREF))
1226 return 0;
1227
1228 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1229 if (!resolves_to || strcmp(resolves_to, d->refname))
1230 return 0;
1231
1232 fprintf(d->fp, d->msg_fmt, refname);
1233 return 0;
1234}
1235
1236void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1237{
1238 struct warn_if_dangling_data data;
1239
1240 data.fp = fp;
1241 data.refname = refname;
1242 data.msg_fmt = msg_fmt;
1243 for_each_rawref(warn_if_dangling_symref, &data);
1244}
1245
0bad611b
HV
1246static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1247 int trim, int flags, void *cb_data)
8a65ff76 1248{
316b097a 1249 struct ref_cache *refs = get_ref_cache(submodule);
933ac036
MH
1250 struct ref_dir *packed_dir = get_packed_refs(refs);
1251 struct ref_dir *loose_dir = get_loose_refs(refs);
1252 int retval = 0;
1253
1254 if (base && *base) {
1255 packed_dir = find_containing_dir(packed_dir, base, 0);
1256 loose_dir = find_containing_dir(loose_dir, base, 0);
1257 }
1258
1259 if (packed_dir && loose_dir) {
1260 sort_ref_dir(packed_dir);
1261 sort_ref_dir(loose_dir);
1262 retval = do_for_each_ref_in_dirs(
1263 packed_dir, loose_dir,
1264 base, fn, trim, flags, cb_data);
1265 } else if (packed_dir) {
1266 sort_ref_dir(packed_dir);
1267 retval = do_for_each_ref_in_dir(
1268 packed_dir, 0,
1269 base, fn, trim, flags, cb_data);
1270 } else if (loose_dir) {
1271 sort_ref_dir(loose_dir);
1272 retval = do_for_each_ref_in_dir(
1273 loose_dir, 0,
1274 base, fn, trim, flags, cb_data);
1275 }
1276
1277 return retval;
8a65ff76
LT
1278}
1279
0bad611b 1280static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
723c31fe
LT
1281{
1282 unsigned char sha1[20];
8da19775
JH
1283 int flag;
1284
0bad611b
HV
1285 if (submodule) {
1286 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1287 return fn("HEAD", sha1, 0, cb_data);
1288
1289 return 0;
1290 }
1291
c6893323 1292 if (!read_ref_full("HEAD", sha1, 1, &flag))
8da19775 1293 return fn("HEAD", sha1, flag, cb_data);
0bad611b 1294
2f34ba32 1295 return 0;
723c31fe
LT
1296}
1297
0bad611b
HV
1298int head_ref(each_ref_fn fn, void *cb_data)
1299{
1300 return do_head_ref(NULL, fn, cb_data);
1301}
1302
9ef6aeb0
HV
1303int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1304{
1305 return do_head_ref(submodule, fn, cb_data);
1306}
1307
cb5d709f 1308int for_each_ref(each_ref_fn fn, void *cb_data)
8a65ff76 1309{
b3cfc406 1310 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
a62be77f
SE
1311}
1312
9ef6aeb0
HV
1313int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1314{
b3cfc406 1315 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
a62be77f
SE
1316}
1317
2a8177b6
CC
1318int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1319{
0bad611b 1320 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
2a8177b6
CC
1321}
1322
9ef6aeb0
HV
1323int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1324 each_ref_fn fn, void *cb_data)
1325{
1326 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
2a8177b6
CC
1327}
1328
cb5d709f 1329int for_each_tag_ref(each_ref_fn fn, void *cb_data)
a62be77f 1330{
2a8177b6 1331 return for_each_ref_in("refs/tags/", fn, cb_data);
a62be77f
SE
1332}
1333
9ef6aeb0
HV
1334int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1335{
1336 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1337}
1338
cb5d709f 1339int for_each_branch_ref(each_ref_fn fn, void *cb_data)
a62be77f 1340{
2a8177b6 1341 return for_each_ref_in("refs/heads/", fn, cb_data);
a62be77f
SE
1342}
1343
9ef6aeb0
HV
1344int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1345{
1346 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1347}
1348
cb5d709f 1349int for_each_remote_ref(each_ref_fn fn, void *cb_data)
a62be77f 1350{
2a8177b6 1351 return for_each_ref_in("refs/remotes/", fn, cb_data);
f8948e2f
JH
1352}
1353
9ef6aeb0
HV
1354int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1355{
1356 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1357}
1358
29268700
CC
1359int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1360{
0bad611b 1361 return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
29268700
CC
1362}
1363
a1bea2c1
JT
1364int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1365{
1366 struct strbuf buf = STRBUF_INIT;
1367 int ret = 0;
1368 unsigned char sha1[20];
1369 int flag;
1370
1371 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
c6893323 1372 if (!read_ref_full(buf.buf, sha1, 1, &flag))
a1bea2c1
JT
1373 ret = fn(buf.buf, sha1, flag, cb_data);
1374 strbuf_release(&buf);
1375
1376 return ret;
1377}
1378
1379int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1380{
1381 struct strbuf buf = STRBUF_INIT;
1382 int ret;
1383 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1384 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1385 strbuf_release(&buf);
1386 return ret;
1387}
1388
b09fe971
IL
1389int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1390 const char *prefix, void *cb_data)
d08bae7e
IL
1391{
1392 struct strbuf real_pattern = STRBUF_INIT;
1393 struct ref_filter filter;
d08bae7e
IL
1394 int ret;
1395
b09fe971 1396 if (!prefix && prefixcmp(pattern, "refs/"))
d08bae7e 1397 strbuf_addstr(&real_pattern, "refs/");
b09fe971
IL
1398 else if (prefix)
1399 strbuf_addstr(&real_pattern, prefix);
d08bae7e
IL
1400 strbuf_addstr(&real_pattern, pattern);
1401
894a9d33 1402 if (!has_glob_specials(pattern)) {
9517e6b8 1403 /* Append implied '/' '*' if not present. */
d08bae7e
IL
1404 if (real_pattern.buf[real_pattern.len - 1] != '/')
1405 strbuf_addch(&real_pattern, '/');
1406 /* No need to check for '*', there is none. */
1407 strbuf_addch(&real_pattern, '*');
1408 }
1409
1410 filter.pattern = real_pattern.buf;
1411 filter.fn = fn;
1412 filter.cb_data = cb_data;
1413 ret = for_each_ref(filter_refs, &filter);
1414
1415 strbuf_release(&real_pattern);
1416 return ret;
1417}
1418
b09fe971
IL
1419int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1420{
1421 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1422}
1423
f8948e2f
JH
1424int for_each_rawref(each_ref_fn fn, void *cb_data)
1425{
b3cfc406 1426 return do_for_each_ref(NULL, "", fn, 0,
f8948e2f 1427 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
8a65ff76
LT
1428}
1429
4577e483 1430const char *prettify_refname(const char *name)
a9c37a72 1431{
a9c37a72
DB
1432 return name + (
1433 !prefixcmp(name, "refs/heads/") ? 11 :
1434 !prefixcmp(name, "refs/tags/") ? 10 :
1435 !prefixcmp(name, "refs/remotes/") ? 13 :
1436 0);
1437}
1438
79803322
SP
1439const char *ref_rev_parse_rules[] = {
1440 "%.*s",
1441 "refs/%.*s",
1442 "refs/tags/%.*s",
1443 "refs/heads/%.*s",
1444 "refs/remotes/%.*s",
1445 "refs/remotes/%.*s/HEAD",
1446 NULL
1447};
1448
1449int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1450{
1451 const char **p;
1452 const int abbrev_name_len = strlen(abbrev_name);
1453
1454 for (p = rules; *p; p++) {
1455 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1456 return 1;
1457 }
1458 }
1459
1460 return 0;
1461}
1462
e5f38ec3 1463static struct ref_lock *verify_lock(struct ref_lock *lock,
4bd18c43
SP
1464 const unsigned char *old_sha1, int mustexist)
1465{
c6893323 1466 if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
434cd0cd 1467 error("Can't verify ref %s", lock->ref_name);
4bd18c43
SP
1468 unlock_ref(lock);
1469 return NULL;
1470 }
a89fccd2 1471 if (hashcmp(lock->old_sha1, old_sha1)) {
434cd0cd 1472 error("Ref %s is at %s but expected %s", lock->ref_name,
4bd18c43
SP
1473 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1474 unlock_ref(lock);
1475 return NULL;
1476 }
1477 return lock;
1478}
1479
7155b727 1480static int remove_empty_directories(const char *file)
bc7127ef
JH
1481{
1482 /* we want to create a file but there is a directory there;
1483 * if that is an empty directory (or a directory that contains
1484 * only empty directories), remove them.
1485 */
7155b727
JS
1486 struct strbuf path;
1487 int result;
bc7127ef 1488
7155b727
JS
1489 strbuf_init(&path, 20);
1490 strbuf_addstr(&path, file);
1491
a0f4afbe 1492 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
7155b727
JS
1493
1494 strbuf_release(&path);
1495
1496 return result;
bc7127ef
JH
1497}
1498
ff74f7f1
JH
1499/*
1500 * *string and *len will only be substituted, and *string returned (for
1501 * later free()ing) if the string passed in is a magic short-hand form
1502 * to name a branch.
1503 */
1504static char *substitute_branch_name(const char **string, int *len)
1505{
1506 struct strbuf buf = STRBUF_INIT;
1507 int ret = interpret_branch_name(*string, &buf);
1508
1509 if (ret == *len) {
1510 size_t size;
1511 *string = strbuf_detach(&buf, &size);
1512 *len = size;
1513 return (char *)*string;
1514 }
1515
1516 return NULL;
1517}
1518
1519int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1520{
1521 char *last_branch = substitute_branch_name(&str, &len);
1522 const char **p, *r;
1523 int refs_found = 0;
1524
1525 *ref = NULL;
1526 for (p = ref_rev_parse_rules; *p; p++) {
1527 char fullref[PATH_MAX];
1528 unsigned char sha1_from_ref[20];
1529 unsigned char *this_result;
1530 int flag;
1531
1532 this_result = refs_found ? sha1_from_ref : sha1;
1533 mksnpath(fullref, sizeof(fullref), *p, len, str);
8cad4744 1534 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
ff74f7f1
JH
1535 if (r) {
1536 if (!refs_found++)
1537 *ref = xstrdup(r);
1538 if (!warn_ambiguous_refs)
1539 break;
55956350 1540 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
ff74f7f1 1541 warning("ignoring dangling symref %s.", fullref);
55956350
JH
1542 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1543 warning("ignoring broken ref %s.", fullref);
1544 }
ff74f7f1
JH
1545 }
1546 free(last_branch);
1547 return refs_found;
1548}
1549
1550int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1551{
1552 char *last_branch = substitute_branch_name(&str, &len);
1553 const char **p;
1554 int logs_found = 0;
1555
1556 *log = NULL;
1557 for (p = ref_rev_parse_rules; *p; p++) {
1558 struct stat st;
1559 unsigned char hash[20];
1560 char path[PATH_MAX];
1561 const char *ref, *it;
1562
1563 mksnpath(path, sizeof(path), *p, len, str);
8cad4744 1564 ref = resolve_ref_unsafe(path, hash, 1, NULL);
ff74f7f1
JH
1565 if (!ref)
1566 continue;
1567 if (!stat(git_path("logs/%s", path), &st) &&
1568 S_ISREG(st.st_mode))
1569 it = path;
1570 else if (strcmp(ref, path) &&
1571 !stat(git_path("logs/%s", ref), &st) &&
1572 S_ISREG(st.st_mode))
1573 it = ref;
1574 else
1575 continue;
1576 if (!logs_found++) {
1577 *log = xstrdup(it);
1578 hashcpy(sha1, hash);
1579 }
1580 if (!warn_ambiguous_refs)
1581 break;
1582 }
1583 free(last_branch);
1584 return logs_found;
1585}
1586
dfefa935
MH
1587static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1588 const unsigned char *old_sha1,
1589 int flags, int *type_p)
4bd18c43 1590{
434cd0cd 1591 char *ref_file;
dfefa935 1592 const char *orig_refname = refname;
4bd18c43 1593 struct ref_lock *lock;
5cc3cef9 1594 int last_errno = 0;
acd3b9ec 1595 int type, lflags;
4431fcc4 1596 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
5bdd8d4a 1597 int missing = 0;
4bd18c43
SP
1598
1599 lock = xcalloc(1, sizeof(struct ref_lock));
1600 lock->lock_fd = -1;
1601
8d68493f 1602 refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
dfefa935 1603 if (!refname && errno == EISDIR) {
bc7127ef
JH
1604 /* we are trying to lock foo but we used to
1605 * have foo/bar which now does not exist;
1606 * it is normal for the empty directory 'foo'
1607 * to remain.
1608 */
dfefa935 1609 ref_file = git_path("%s", orig_refname);
5cc3cef9
JH
1610 if (remove_empty_directories(ref_file)) {
1611 last_errno = errno;
dfefa935 1612 error("there are still refs under '%s'", orig_refname);
5cc3cef9
JH
1613 goto error_return;
1614 }
8d68493f 1615 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
bc7127ef 1616 }
68db31cc
SV
1617 if (type_p)
1618 *type_p = type;
dfefa935 1619 if (!refname) {
5cc3cef9 1620 last_errno = errno;
818f477c 1621 error("unable to resolve reference %s: %s",
dfefa935 1622 orig_refname, strerror(errno));
5cc3cef9 1623 goto error_return;
4bd18c43 1624 }
5bdd8d4a 1625 missing = is_null_sha1(lock->old_sha1);
c976d415
LH
1626 /* When the ref did not exist and we are creating it,
1627 * make sure there is no existing ref that is packed
1628 * whose name begins with our refname, nor a ref whose
1629 * name is a proper prefix of our refname.
1630 */
5bdd8d4a 1631 if (missing &&
316b097a 1632 !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
f475e08e 1633 last_errno = ENOTDIR;
c976d415 1634 goto error_return;
f475e08e 1635 }
22a3844e 1636
c33d5174 1637 lock->lk = xcalloc(1, sizeof(struct lock_file));
4bd18c43 1638
acd3b9ec
JH
1639 lflags = LOCK_DIE_ON_ERROR;
1640 if (flags & REF_NODEREF) {
dfefa935 1641 refname = orig_refname;
acd3b9ec
JH
1642 lflags |= LOCK_NODEREF;
1643 }
dfefa935
MH
1644 lock->ref_name = xstrdup(refname);
1645 lock->orig_ref_name = xstrdup(orig_refname);
1646 ref_file = git_path("%s", refname);
5bdd8d4a 1647 if (missing)
68db31cc
SV
1648 lock->force_write = 1;
1649 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1650 lock->force_write = 1;
4bd18c43 1651
5cc3cef9
JH
1652 if (safe_create_leading_directories(ref_file)) {
1653 last_errno = errno;
1654 error("unable to create directory for %s", ref_file);
1655 goto error_return;
1656 }
4bd18c43 1657
acd3b9ec 1658 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
4bd18c43 1659 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
5cc3cef9
JH
1660
1661 error_return:
1662 unlock_ref(lock);
1663 errno = last_errno;
1664 return NULL;
4bd18c43
SP
1665}
1666
dfefa935 1667struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
95fc7512 1668{
53cce84c 1669 char refpath[PATH_MAX];
dfefa935 1670 if (check_refname_format(refname, 0))
4bd18c43 1671 return NULL;
dfefa935 1672 strcpy(refpath, mkpath("refs/%s", refname));
68db31cc 1673 return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
4bd18c43
SP
1674}
1675
dfefa935
MH
1676struct ref_lock *lock_any_ref_for_update(const char *refname,
1677 const unsigned char *old_sha1, int flags)
4bd18c43 1678{
dfefa935 1679 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
257f3020 1680 return NULL;
dfefa935 1681 return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
c0277d15
JH
1682}
1683
d66da478
MH
1684struct repack_without_ref_sb {
1685 const char *refname;
1686 int fd;
1687};
1688
1689static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1690 int flags, void *cb_data)
1691{
1692 struct repack_without_ref_sb *data = cb_data;
1693 char line[PATH_MAX + 100];
1694 int len;
1695
1696 if (!strcmp(data->refname, refname))
1697 return 0;
1698 len = snprintf(line, sizeof(line), "%s %s\n",
1699 sha1_to_hex(sha1), refname);
1700 /* this should not happen but just being defensive */
1701 if (len > sizeof(line))
1702 die("too long a refname '%s'", refname);
1703 write_or_die(data->fd, line, len);
1704 return 0;
1705}
1706
26a063a1
JH
1707static struct lock_file packlock;
1708
c0277d15
JH
1709static int repack_without_ref(const char *refname)
1710{
d66da478 1711 struct repack_without_ref_sb data;
d3177275 1712 struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
432ad41e 1713 if (find_ref(packed, refname) == NULL)
c0277d15 1714 return 0;
d66da478
MH
1715 data.refname = refname;
1716 data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1717 if (data.fd < 0) {
1b018fd9 1718 unable_to_lock_error(git_path("packed-refs"), errno);
c0277d15 1719 return error("cannot delete '%s' from packed refs", refname);
1b018fd9 1720 }
d3177275 1721 do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
c0277d15
JH
1722 return commit_lock_file(&packlock);
1723}
1724
eca35a25 1725int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
c0277d15
JH
1726{
1727 struct ref_lock *lock;
eca35a25 1728 int err, i = 0, ret = 0, flag = 0;
c0277d15 1729
68db31cc 1730 lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
c0277d15
JH
1731 if (!lock)
1732 return 1;
045a476f 1733 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
c0277d15 1734 /* loose */
eca35a25
MV
1735 const char *path;
1736
1737 if (!(delopt & REF_NODEREF)) {
1738 i = strlen(lock->lk->filename) - 5; /* .lock */
1739 lock->lk->filename[i] = 0;
1740 path = lock->lk->filename;
1741 } else {
9db56f71 1742 path = git_path("%s", refname);
eca35a25 1743 }
691f1a28
AR
1744 err = unlink_or_warn(path);
1745 if (err && errno != ENOENT)
c0277d15 1746 ret = 1;
691f1a28 1747
eca35a25
MV
1748 if (!(delopt & REF_NODEREF))
1749 lock->lk->filename[i] = '.';
c0277d15
JH
1750 }
1751 /* removing the loose one could have resurrected an earlier
1752 * packed one. Also, if it was not loose we need to repack
1753 * without it.
1754 */
1755 ret |= repack_without_ref(refname);
1756
691f1a28 1757 unlink_or_warn(git_path("logs/%s", lock->ref_name));
3870a0d1 1758 invalidate_ref_cache(NULL);
c0277d15
JH
1759 unlock_ref(lock);
1760 return ret;
4bd18c43
SP
1761}
1762
765c2258
PH
1763/*
1764 * People using contrib's git-new-workdir have .git/logs/refs ->
1765 * /some/other/path/.git/logs/refs, and that may live on another device.
1766 *
1767 * IOW, to avoid cross device rename errors, the temporary renamed log must
1768 * live into logs/refs.
1769 */
1770#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
1771
dfefa935 1772int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
c976d415 1773{
c976d415
LH
1774 unsigned char sha1[20], orig_sha1[20];
1775 int flag = 0, logmoved = 0;
1776 struct ref_lock *lock;
c976d415 1777 struct stat loginfo;
dfefa935 1778 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
eca35a25 1779 const char *symref = NULL;
316b097a 1780 struct ref_cache *refs = get_ref_cache(NULL);
c976d415 1781
450d4c0f 1782 if (log && S_ISLNK(loginfo.st_mode))
dfefa935 1783 return error("reflog for %s is a symlink", oldrefname);
c976d415 1784
8d68493f 1785 symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
eca35a25 1786 if (flag & REF_ISSYMREF)
fa58186c 1787 return error("refname %s is a symbolic ref, renaming it is not supported",
dfefa935 1788 oldrefname);
eca35a25 1789 if (!symref)
dfefa935 1790 return error("refname %s not found", oldrefname);
c976d415 1791
316b097a 1792 if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
c976d415
LH
1793 return 1;
1794
316b097a 1795 if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
c976d415
LH
1796 return 1;
1797
dfefa935 1798 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
765c2258 1799 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
dfefa935 1800 oldrefname, strerror(errno));
c976d415 1801
dfefa935
MH
1802 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1803 error("unable to delete old %s", oldrefname);
c976d415
LH
1804 goto rollback;
1805 }
1806
dfefa935
MH
1807 if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1808 delete_ref(newrefname, sha1, REF_NODEREF)) {
c976d415 1809 if (errno==EISDIR) {
dfefa935
MH
1810 if (remove_empty_directories(git_path("%s", newrefname))) {
1811 error("Directory not empty: %s", newrefname);
c976d415
LH
1812 goto rollback;
1813 }
1814 } else {
dfefa935 1815 error("unable to delete existing %s", newrefname);
c976d415
LH
1816 goto rollback;
1817 }
1818 }
1819
dfefa935
MH
1820 if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1821 error("unable to create directory for %s", newrefname);
c976d415
LH
1822 goto rollback;
1823 }
1824
1825 retry:
dfefa935 1826 if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
d9e74d57
JR
1827 if (errno==EISDIR || errno==ENOTDIR) {
1828 /*
1829 * rename(a, b) when b is an existing
1830 * directory ought to result in ISDIR, but
1831 * Solaris 5.8 gives ENOTDIR. Sheesh.
1832 */
dfefa935
MH
1833 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1834 error("Directory not empty: logs/%s", newrefname);
c976d415
LH
1835 goto rollback;
1836 }
1837 goto retry;
1838 } else {
765c2258 1839 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
dfefa935 1840 newrefname, strerror(errno));
c976d415
LH
1841 goto rollback;
1842 }
1843 }
1844 logmoved = log;
1845
dfefa935 1846 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
c976d415 1847 if (!lock) {
dfefa935 1848 error("unable to lock %s for update", newrefname);
c976d415
LH
1849 goto rollback;
1850 }
c976d415
LH
1851 lock->force_write = 1;
1852 hashcpy(lock->old_sha1, orig_sha1);
678d0f4c 1853 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
dfefa935 1854 error("unable to write current sha1 into %s", newrefname);
c976d415
LH
1855 goto rollback;
1856 }
1857
1858 return 0;
1859
1860 rollback:
dfefa935 1861 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
c976d415 1862 if (!lock) {
dfefa935 1863 error("unable to lock %s for rollback", oldrefname);
c976d415
LH
1864 goto rollbacklog;
1865 }
1866
1867 lock->force_write = 1;
1868 flag = log_all_ref_updates;
1869 log_all_ref_updates = 0;
1870 if (write_ref_sha1(lock, orig_sha1, NULL))
dfefa935 1871 error("unable to write current sha1 into %s", oldrefname);
c976d415
LH
1872 log_all_ref_updates = flag;
1873
1874 rollbacklog:
dfefa935 1875 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
c976d415 1876 error("unable to restore logfile %s from %s: %s",
dfefa935 1877 oldrefname, newrefname, strerror(errno));
c976d415 1878 if (!logmoved && log &&
dfefa935 1879 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
765c2258 1880 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
dfefa935 1881 oldrefname, strerror(errno));
c976d415
LH
1882
1883 return 1;
1884}
1885
435fc852 1886int close_ref(struct ref_lock *lock)
b531394d
BC
1887{
1888 if (close_lock_file(lock->lk))
1889 return -1;
1890 lock->lock_fd = -1;
1891 return 0;
1892}
1893
435fc852 1894int commit_ref(struct ref_lock *lock)
b531394d
BC
1895{
1896 if (commit_lock_file(lock->lk))
1897 return -1;
1898 lock->lock_fd = -1;
1899 return 0;
1900}
1901
e5f38ec3 1902void unlock_ref(struct ref_lock *lock)
4bd18c43 1903{
4ed7cd3a
BC
1904 /* Do not free lock->lk -- atexit() still looks at them */
1905 if (lock->lk)
1906 rollback_lock_file(lock->lk);
434cd0cd 1907 free(lock->ref_name);
1655707c 1908 free(lock->orig_ref_name);
4bd18c43
SP
1909 free(lock);
1910}
1911
0ec29a47
JH
1912/*
1913 * copy the reflog message msg to buf, which has been allocated sufficiently
1914 * large, while cleaning up the whitespaces. Especially, convert LF to space,
1915 * because reflog file is one line per entry.
1916 */
1917static int copy_msg(char *buf, const char *msg)
1918{
1919 char *cp = buf;
1920 char c;
1921 int wasspace = 1;
1922
1923 *cp++ = '\t';
1924 while ((c = *msg++)) {
1925 if (wasspace && isspace(c))
1926 continue;
1927 wasspace = isspace(c);
1928 if (wasspace)
1929 c = ' ';
1930 *cp++ = c;
1931 }
1932 while (buf < cp && isspace(cp[-1]))
1933 cp--;
1934 *cp++ = '\n';
1935 return cp - buf;
1936}
1937
dfefa935 1938int log_ref_setup(const char *refname, char *logfile, int bufsize)
6de08ae6 1939{
859c3017 1940 int logfd, oflags = O_APPEND | O_WRONLY;
9a13f0b7 1941
dfefa935 1942 git_snpath(logfile, bufsize, "logs/%s", refname);
4057deb5 1943 if (log_all_ref_updates &&
dfefa935
MH
1944 (!prefixcmp(refname, "refs/heads/") ||
1945 !prefixcmp(refname, "refs/remotes/") ||
1946 !prefixcmp(refname, "refs/notes/") ||
1947 !strcmp(refname, "HEAD"))) {
157aaea5 1948 if (safe_create_leading_directories(logfile) < 0)
6de08ae6 1949 return error("unable to create directory for %s",
157aaea5 1950 logfile);
6de08ae6
SP
1951 oflags |= O_CREAT;
1952 }
1953
157aaea5 1954 logfd = open(logfile, oflags, 0666);
6de08ae6 1955 if (logfd < 0) {
1974bf62 1956 if (!(oflags & O_CREAT) && errno == ENOENT)
6de08ae6 1957 return 0;
3b463c3f
JH
1958
1959 if ((oflags & O_CREAT) && errno == EISDIR) {
157aaea5 1960 if (remove_empty_directories(logfile)) {
3b463c3f 1961 return error("There are still logs under '%s'",
157aaea5 1962 logfile);
3b463c3f 1963 }
157aaea5 1964 logfd = open(logfile, oflags, 0666);
3b463c3f
JH
1965 }
1966
1967 if (logfd < 0)
1968 return error("Unable to append to %s: %s",
157aaea5 1969 logfile, strerror(errno));
6de08ae6
SP
1970 }
1971
157aaea5 1972 adjust_shared_perm(logfile);
859c3017
EM
1973 close(logfd);
1974 return 0;
1975}
443b92b6 1976
dfefa935 1977static int log_ref_write(const char *refname, const unsigned char *old_sha1,
859c3017
EM
1978 const unsigned char *new_sha1, const char *msg)
1979{
1980 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1981 unsigned maxlen, len;
1982 int msglen;
157aaea5 1983 char log_file[PATH_MAX];
859c3017
EM
1984 char *logrec;
1985 const char *committer;
1986
1987 if (log_all_ref_updates < 0)
1988 log_all_ref_updates = !is_bare_repository();
1989
dfefa935 1990 result = log_ref_setup(refname, log_file, sizeof(log_file));
859c3017
EM
1991 if (result)
1992 return result;
1993
1994 logfd = open(log_file, oflags);
1995 if (logfd < 0)
1996 return 0;
0ec29a47 1997 msglen = msg ? strlen(msg) : 0;
774751a8 1998 committer = git_committer_info(0);
8ac65937
JH
1999 maxlen = strlen(committer) + msglen + 100;
2000 logrec = xmalloc(maxlen);
2001 len = sprintf(logrec, "%s %s %s\n",
9a13f0b7
NP
2002 sha1_to_hex(old_sha1),
2003 sha1_to_hex(new_sha1),
8ac65937
JH
2004 committer);
2005 if (msglen)
0ec29a47 2006 len += copy_msg(logrec + len - 1, msg) - 1;
93822c22 2007 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
6de08ae6 2008 free(logrec);
91c8d590 2009 if (close(logfd) != 0 || written != len)
9a13f0b7 2010 return error("Unable to append to %s", log_file);
6de08ae6
SP
2011 return 0;
2012}
2013
c3b0dec5
LT
2014static int is_branch(const char *refname)
2015{
2016 return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2017}
2018
4bd18c43
SP
2019int write_ref_sha1(struct ref_lock *lock,
2020 const unsigned char *sha1, const char *logmsg)
2021{
2022 static char term = '\n';
c3b0dec5 2023 struct object *o;
4bd18c43
SP
2024
2025 if (!lock)
95fc7512 2026 return -1;
a89fccd2 2027 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
4bd18c43
SP
2028 unlock_ref(lock);
2029 return 0;
95fc7512 2030 }
c3b0dec5
LT
2031 o = parse_object(sha1);
2032 if (!o) {
7be8b3ba 2033 error("Trying to write ref %s with nonexistent object %s",
c3b0dec5
LT
2034 lock->ref_name, sha1_to_hex(sha1));
2035 unlock_ref(lock);
2036 return -1;
2037 }
2038 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2039 error("Trying to write non-commit object %s to branch %s",
2040 sha1_to_hex(sha1), lock->ref_name);
2041 unlock_ref(lock);
2042 return -1;
2043 }
93822c22
AW
2044 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2045 write_in_full(lock->lock_fd, &term, 1) != 1
b531394d 2046 || close_ref(lock) < 0) {
c33d5174 2047 error("Couldn't write %s", lock->lk->filename);
4bd18c43
SP
2048 unlock_ref(lock);
2049 return -1;
2050 }
8bf90dc9 2051 clear_loose_ref_cache(get_ref_cache(NULL));
bd104db1
NP
2052 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2053 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2054 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
6de08ae6
SP
2055 unlock_ref(lock);
2056 return -1;
2057 }
605fac8b
NP
2058 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2059 /*
2060 * Special hack: If a branch is updated directly and HEAD
2061 * points to it (may happen on the remote side of a push
2062 * for example) then logically the HEAD reflog should be
2063 * updated too.
2064 * A generic solution implies reverse symref information,
2065 * but finding all symrefs pointing to the given branch
2066 * would be rather costly for this rare event (the direct
2067 * update of a branch) to be worth it. So let's cheat and
2068 * check with HEAD only which should cover 99% of all usage
2069 * scenarios (even 100% of the default ones).
2070 */
2071 unsigned char head_sha1[20];
2072 int head_flag;
2073 const char *head_ref;
8cad4744 2074 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
605fac8b
NP
2075 if (head_ref && (head_flag & REF_ISSYMREF) &&
2076 !strcmp(head_ref, lock->ref_name))
2077 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2078 }
b531394d 2079 if (commit_ref(lock)) {
434cd0cd 2080 error("Couldn't set %s", lock->ref_name);
4bd18c43
SP
2081 unlock_ref(lock);
2082 return -1;
2083 }
4bd18c43
SP
2084 unlock_ref(lock);
2085 return 0;
95fc7512 2086}
d556fae2 2087
8b5157e4
NP
2088int create_symref(const char *ref_target, const char *refs_heads_master,
2089 const char *logmsg)
41b625b0
NP
2090{
2091 const char *lockpath;
2092 char ref[1000];
2093 int fd, len, written;
a4f34cbb 2094 char *git_HEAD = git_pathdup("%s", ref_target);
8b5157e4
NP
2095 unsigned char old_sha1[20], new_sha1[20];
2096
2097 if (logmsg && read_ref(ref_target, old_sha1))
2098 hashclr(old_sha1);
41b625b0 2099
d48744d1
JH
2100 if (safe_create_leading_directories(git_HEAD) < 0)
2101 return error("unable to create directory for %s", git_HEAD);
2102
41b625b0
NP
2103#ifndef NO_SYMLINK_HEAD
2104 if (prefer_symlink_refs) {
2105 unlink(git_HEAD);
2106 if (!symlink(refs_heads_master, git_HEAD))
8b5157e4 2107 goto done;
41b625b0
NP
2108 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2109 }
2110#endif
2111
2112 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2113 if (sizeof(ref) <= len) {
2114 error("refname too long: %s", refs_heads_master);
47fc52e2 2115 goto error_free_return;
41b625b0
NP
2116 }
2117 lockpath = mkpath("%s.lock", git_HEAD);
2118 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2119 if (fd < 0) {
2120 error("Unable to open %s for writing", lockpath);
47fc52e2 2121 goto error_free_return;
41b625b0
NP
2122 }
2123 written = write_in_full(fd, ref, len);
91c8d590 2124 if (close(fd) != 0 || written != len) {
41b625b0 2125 error("Unable to write to %s", lockpath);
47fc52e2 2126 goto error_unlink_return;
41b625b0
NP
2127 }
2128 if (rename(lockpath, git_HEAD) < 0) {
41b625b0 2129 error("Unable to create %s", git_HEAD);
47fc52e2 2130 goto error_unlink_return;
41b625b0
NP
2131 }
2132 if (adjust_shared_perm(git_HEAD)) {
41b625b0 2133 error("Unable to fix permissions on %s", lockpath);
47fc52e2 2134 error_unlink_return:
691f1a28 2135 unlink_or_warn(lockpath);
47fc52e2
JH
2136 error_free_return:
2137 free(git_HEAD);
2138 return -1;
41b625b0 2139 }
8b5157e4 2140
ee96d11b 2141#ifndef NO_SYMLINK_HEAD
8b5157e4 2142 done:
ee96d11b 2143#endif
8b5157e4
NP
2144 if (logmsg && !read_ref(refs_heads_master, new_sha1))
2145 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2146
47fc52e2 2147 free(git_HEAD);
41b625b0
NP
2148 return 0;
2149}
2150
16d7cc90
JH
2151static char *ref_msg(const char *line, const char *endp)
2152{
2153 const char *ep;
16d7cc90 2154 line += 82;
182af834
PH
2155 ep = memchr(line, '\n', endp - line);
2156 if (!ep)
2157 ep = endp;
2158 return xmemdupz(line, ep - line);
16d7cc90
JH
2159}
2160
dfefa935
MH
2161int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2162 unsigned char *sha1, char **msg,
2163 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
d556fae2 2164{
e5229042 2165 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
d556fae2 2166 char *tz_c;
e29cb53a 2167 int logfd, tz, reccnt = 0;
d556fae2
SP
2168 struct stat st;
2169 unsigned long date;
e5229042 2170 unsigned char logged_sha1[20];
cb48cb58 2171 void *log_mapped;
dc49cd76 2172 size_t mapsz;
d556fae2 2173
dfefa935 2174 logfile = git_path("logs/%s", refname);
d556fae2
SP
2175 logfd = open(logfile, O_RDONLY, 0);
2176 if (logfd < 0)
d824cbba 2177 die_errno("Unable to read log '%s'", logfile);
d556fae2
SP
2178 fstat(logfd, &st);
2179 if (!st.st_size)
2180 die("Log %s is empty.", logfile);
dc49cd76
SP
2181 mapsz = xsize_t(st.st_size);
2182 log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
cb48cb58 2183 logdata = log_mapped;
d556fae2
SP
2184 close(logfd);
2185
e5229042 2186 lastrec = NULL;
d556fae2
SP
2187 rec = logend = logdata + st.st_size;
2188 while (logdata < rec) {
e29cb53a 2189 reccnt++;
d556fae2
SP
2190 if (logdata < rec && *(rec-1) == '\n')
2191 rec--;
e5229042
SP
2192 lastgt = NULL;
2193 while (logdata < rec && *(rec-1) != '\n') {
d556fae2 2194 rec--;
e5229042
SP
2195 if (*rec == '>')
2196 lastgt = rec;
2197 }
2198 if (!lastgt)
d556fae2 2199 die("Log %s is corrupt.", logfile);
e5229042 2200 date = strtoul(lastgt + 1, &tz_c, 10);
ab2a1a32 2201 if (date <= at_time || cnt == 0) {
76a44c5c 2202 tz = strtoul(tz_c, NULL, 10);
16d7cc90
JH
2203 if (msg)
2204 *msg = ref_msg(rec, logend);
2205 if (cutoff_time)
2206 *cutoff_time = date;
2207 if (cutoff_tz)
2208 *cutoff_tz = tz;
2209 if (cutoff_cnt)
76a44c5c 2210 *cutoff_cnt = reccnt - 1;
e5229042
SP
2211 if (lastrec) {
2212 if (get_sha1_hex(lastrec, logged_sha1))
2213 die("Log %s is corrupt.", logfile);
2214 if (get_sha1_hex(rec + 41, sha1))
2215 die("Log %s is corrupt.", logfile);
a89fccd2 2216 if (hashcmp(logged_sha1, sha1)) {
edbc25c5 2217 warning("Log %s has gap after %s.",
73013afd 2218 logfile, show_date(date, tz, DATE_RFC2822));
e5229042 2219 }
e5f38ec3
JH
2220 }
2221 else if (date == at_time) {
e5229042
SP
2222 if (get_sha1_hex(rec + 41, sha1))
2223 die("Log %s is corrupt.", logfile);
e5f38ec3
JH
2224 }
2225 else {
e5229042
SP
2226 if (get_sha1_hex(rec + 41, logged_sha1))
2227 die("Log %s is corrupt.", logfile);
a89fccd2 2228 if (hashcmp(logged_sha1, sha1)) {
edbc25c5 2229 warning("Log %s unexpectedly ended on %s.",
73013afd 2230 logfile, show_date(date, tz, DATE_RFC2822));
e5229042
SP
2231 }
2232 }
dc49cd76 2233 munmap(log_mapped, mapsz);
d556fae2
SP
2234 return 0;
2235 }
e5229042 2236 lastrec = rec;
ab2a1a32
JH
2237 if (cnt > 0)
2238 cnt--;
d556fae2
SP
2239 }
2240
e5229042
SP
2241 rec = logdata;
2242 while (rec < logend && *rec != '>' && *rec != '\n')
2243 rec++;
2244 if (rec == logend || *rec == '\n')
d556fae2 2245 die("Log %s is corrupt.", logfile);
e5229042 2246 date = strtoul(rec + 1, &tz_c, 10);
d556fae2
SP
2247 tz = strtoul(tz_c, NULL, 10);
2248 if (get_sha1_hex(logdata, sha1))
2249 die("Log %s is corrupt.", logfile);
d1a4489a
JK
2250 if (is_null_sha1(sha1)) {
2251 if (get_sha1_hex(logdata + 41, sha1))
2252 die("Log %s is corrupt.", logfile);
2253 }
16d7cc90
JH
2254 if (msg)
2255 *msg = ref_msg(logdata, logend);
dc49cd76 2256 munmap(log_mapped, mapsz);
16d7cc90
JH
2257
2258 if (cutoff_time)
2259 *cutoff_time = date;
2260 if (cutoff_tz)
2261 *cutoff_tz = tz;
2262 if (cutoff_cnt)
2263 *cutoff_cnt = reccnt;
2264 return 1;
d556fae2 2265}
2ff81662 2266
dfefa935 2267int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
2ff81662
JH
2268{
2269 const char *logfile;
2270 FILE *logfp;
8ca78803 2271 struct strbuf sb = STRBUF_INIT;
2266bf27 2272 int ret = 0;
2ff81662 2273
dfefa935 2274 logfile = git_path("logs/%s", refname);
2ff81662
JH
2275 logfp = fopen(logfile, "r");
2276 if (!logfp)
883d60fa 2277 return -1;
101d15e0
JH
2278
2279 if (ofs) {
2280 struct stat statbuf;
2281 if (fstat(fileno(logfp), &statbuf) ||
2282 statbuf.st_size < ofs ||
2283 fseek(logfp, -ofs, SEEK_END) ||
8ca78803 2284 strbuf_getwholeline(&sb, logfp, '\n')) {
9d33f7c2 2285 fclose(logfp);
8ca78803 2286 strbuf_release(&sb);
101d15e0 2287 return -1;
9d33f7c2 2288 }
101d15e0
JH
2289 }
2290
8ca78803 2291 while (!strbuf_getwholeline(&sb, logfp, '\n')) {
2ff81662 2292 unsigned char osha1[20], nsha1[20];
883d60fa
JS
2293 char *email_end, *message;
2294 unsigned long timestamp;
8ca78803 2295 int tz;
2ff81662
JH
2296
2297 /* old SP new SP name <email> SP time TAB msg LF */
8ca78803
RS
2298 if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
2299 get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
2300 get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
2301 !(email_end = strchr(sb.buf + 82, '>')) ||
883d60fa
JS
2302 email_end[1] != ' ' ||
2303 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2304 !message || message[0] != ' ' ||
2305 (message[1] != '+' && message[1] != '-') ||
2306 !isdigit(message[2]) || !isdigit(message[3]) ||
b4dd4856 2307 !isdigit(message[4]) || !isdigit(message[5]))
2ff81662 2308 continue; /* corrupt? */
883d60fa
JS
2309 email_end[1] = '\0';
2310 tz = strtol(message + 1, NULL, 10);
b4dd4856
JS
2311 if (message[6] != '\t')
2312 message += 6;
2313 else
2314 message += 7;
8ca78803
RS
2315 ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
2316 cb_data);
883d60fa 2317 if (ret)
2266bf27 2318 break;
2ff81662
JH
2319 }
2320 fclose(logfp);
8ca78803 2321 strbuf_release(&sb);
2266bf27 2322 return ret;
2ff81662 2323}
e29cb53a 2324
dfefa935 2325int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
101d15e0 2326{
dfefa935 2327 return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
101d15e0
JH
2328}
2329
989c0e5d
MH
2330/*
2331 * Call fn for each reflog in the namespace indicated by name. name
2332 * must be empty or end with '/'. Name will be used as a scratch
2333 * space, but its contents will be restored before return.
2334 */
2335static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
eb8381c8 2336{
989c0e5d 2337 DIR *d = opendir(git_path("logs/%s", name->buf));
fcee5a14 2338 int retval = 0;
93c603fc 2339 struct dirent *de;
989c0e5d 2340 int oldlen = name->len;
eb8381c8 2341
93c603fc 2342 if (!d)
989c0e5d 2343 return name->len ? errno : 0;
eb8381c8 2344
93c603fc
MH
2345 while ((de = readdir(d)) != NULL) {
2346 struct stat st;
eb8381c8 2347
93c603fc
MH
2348 if (de->d_name[0] == '.')
2349 continue;
93c603fc
MH
2350 if (has_extension(de->d_name, ".lock"))
2351 continue;
989c0e5d
MH
2352 strbuf_addstr(name, de->d_name);
2353 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2354 ; /* silently ignore */
93c603fc 2355 } else {
989c0e5d
MH
2356 if (S_ISDIR(st.st_mode)) {
2357 strbuf_addch(name, '/');
2358 retval = do_for_each_reflog(name, fn, cb_data);
2359 } else {
2360 unsigned char sha1[20];
2361 if (read_ref_full(name->buf, sha1, 0, NULL))
2362 retval = error("bad ref for %s", name->buf);
2363 else
2364 retval = fn(name->buf, sha1, 0, cb_data);
2365 }
2366 if (retval)
2367 break;
eb8381c8 2368 }
989c0e5d 2369 strbuf_setlen(name, oldlen);
eb8381c8 2370 }
93c603fc 2371 closedir(d);
eb8381c8
NP
2372 return retval;
2373}
2374
2375int for_each_reflog(each_ref_fn fn, void *cb_data)
2376{
989c0e5d
MH
2377 int retval;
2378 struct strbuf name;
2379 strbuf_init(&name, PATH_MAX);
2380 retval = do_for_each_reflog(&name, fn, cb_data);
2381 strbuf_release(&name);
2382 return retval;
eb8381c8 2383}
3d9f037c
CR
2384
2385int update_ref(const char *action, const char *refname,
2386 const unsigned char *sha1, const unsigned char *oldval,
2387 int flags, enum action_on_err onerr)
2388{
2389 static struct ref_lock *lock;
2390 lock = lock_any_ref_for_update(refname, oldval, flags);
2391 if (!lock) {
2392 const char *str = "Cannot lock the ref '%s'.";
2393 switch (onerr) {
2394 case MSG_ON_ERR: error(str, refname); break;
2395 case DIE_ON_ERR: die(str, refname); break;
2396 case QUIET_ON_ERR: break;
2397 }
2398 return 1;
2399 }
2400 if (write_ref_sha1(lock, sha1, action) < 0) {
2401 const char *str = "Cannot update the ref '%s'.";
2402 switch (onerr) {
2403 case MSG_ON_ERR: error(str, refname); break;
2404 case DIE_ON_ERR: die(str, refname); break;
2405 case QUIET_ON_ERR: break;
2406 }
2407 return 1;
2408 }
2409 return 0;
2410}
cda69f48 2411
5483f799 2412struct ref *find_ref_by_name(const struct ref *list, const char *name)
cda69f48
JK
2413{
2414 for ( ; list; list = list->next)
2415 if (!strcmp(list->name, name))
5483f799 2416 return (struct ref *)list;
cda69f48
JK
2417 return NULL;
2418}
7c2b3029
JK
2419
2420/*
2421 * generate a format suitable for scanf from a ref_rev_parse_rules
2422 * rule, that is replace the "%.*s" spec with a "%s" spec
2423 */
2424static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2425{
2426 char *spec;
2427
2428 spec = strstr(rule, "%.*s");
2429 if (!spec || strstr(spec + 4, "%.*s"))
2430 die("invalid rule in ref_rev_parse_rules: %s", rule);
2431
2432 /* copy all until spec */
2433 strncpy(scanf_fmt, rule, spec - rule);
2434 scanf_fmt[spec - rule] = '\0';
2435 /* copy new spec */
2436 strcat(scanf_fmt, "%s");
2437 /* copy remaining rule */
2438 strcat(scanf_fmt, spec + 4);
2439
2440 return;
2441}
2442
dfefa935 2443char *shorten_unambiguous_ref(const char *refname, int strict)
7c2b3029
JK
2444{
2445 int i;
2446 static char **scanf_fmts;
2447 static int nr_rules;
2448 char *short_name;
2449
2450 /* pre generate scanf formats from ref_rev_parse_rules[] */
2451 if (!nr_rules) {
2452 size_t total_len = 0;
2453
2454 /* the rule list is NULL terminated, count them first */
2455 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2456 /* no +1 because strlen("%s") < strlen("%.*s") */
2457 total_len += strlen(ref_rev_parse_rules[nr_rules]);
2458
2459 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2460
2461 total_len = 0;
2462 for (i = 0; i < nr_rules; i++) {
2463 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2464 + total_len;
2465 gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2466 total_len += strlen(ref_rev_parse_rules[i]);
2467 }
2468 }
2469
2470 /* bail out if there are no rules */
2471 if (!nr_rules)
dfefa935 2472 return xstrdup(refname);
7c2b3029 2473
dfefa935
MH
2474 /* buffer for scanf result, at most refname must fit */
2475 short_name = xstrdup(refname);
7c2b3029
JK
2476
2477 /* skip first rule, it will always match */
2478 for (i = nr_rules - 1; i > 0 ; --i) {
2479 int j;
6e7b3309 2480 int rules_to_fail = i;
7c2b3029
JK
2481 int short_name_len;
2482
dfefa935 2483 if (1 != sscanf(refname, scanf_fmts[i], short_name))
7c2b3029
JK
2484 continue;
2485
2486 short_name_len = strlen(short_name);
2487
6e7b3309
BW
2488 /*
2489 * in strict mode, all (except the matched one) rules
2490 * must fail to resolve to a valid non-ambiguous ref
2491 */
2492 if (strict)
2493 rules_to_fail = nr_rules;
2494
7c2b3029
JK
2495 /*
2496 * check if the short name resolves to a valid ref,
2497 * but use only rules prior to the matched one
2498 */
6e7b3309 2499 for (j = 0; j < rules_to_fail; j++) {
7c2b3029 2500 const char *rule = ref_rev_parse_rules[j];
7c2b3029
JK
2501 char refname[PATH_MAX];
2502
6e7b3309
BW
2503 /* skip matched rule */
2504 if (i == j)
2505 continue;
2506
7c2b3029
JK
2507 /*
2508 * the short name is ambiguous, if it resolves
2509 * (with this previous rule) to a valid ref
2510 * read_ref() returns 0 on success
2511 */
2512 mksnpath(refname, sizeof(refname),
2513 rule, short_name_len, short_name);
c6893323 2514 if (ref_exists(refname))
7c2b3029
JK
2515 break;
2516 }
2517
2518 /*
2519 * short name is non-ambiguous if all previous rules
2520 * haven't resolved to a valid ref
2521 */
6e7b3309 2522 if (j == rules_to_fail)
7c2b3029
JK
2523 return short_name;
2524 }
2525
2526 free(short_name);
dfefa935 2527 return xstrdup(refname);
7c2b3029 2528}