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