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