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