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