]> git.ipfire.org Git - thirdparty/git.git/blame - refs.c
add logref support to git-symbolic-ref
[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"
95fc7512 5
f4204ab9
JH
6/* ISSYMREF=01 and ISPACKED=02 are public interfaces */
7#define REF_KNOWS_PEELED 04
8
e1e22e37
LT
9struct ref_list {
10 struct ref_list *next;
f4204ab9 11 unsigned char flag; /* ISSYMREF? ISPACKED? */
e1e22e37 12 unsigned char sha1[20];
f4204ab9 13 unsigned char peeled[20];
e1e22e37
LT
14 char name[FLEX_ARRAY];
15};
16
f4204ab9 17static const char *parse_ref_line(char *line, unsigned char *sha1)
e1e22e37
LT
18{
19 /*
20 * 42: the answer to everything.
21 *
22 * In this case, it happens to be the answer to
23 * 40 (length of sha1 hex representation)
24 * +1 (space in between hex and name)
25 * +1 (newline at the end of the line)
26 */
27 int len = strlen(line) - 42;
28
29 if (len <= 0)
30 return NULL;
31 if (get_sha1_hex(line, sha1) < 0)
32 return NULL;
33 if (!isspace(line[40]))
34 return NULL;
35 line += 41;
f4204ab9
JH
36 if (isspace(*line))
37 return NULL;
e1e22e37
LT
38 if (line[len] != '\n')
39 return NULL;
40 line[len] = 0;
cf0adba7 41
e1e22e37
LT
42 return line;
43}
44
8da19775 45static struct ref_list *add_ref(const char *name, const unsigned char *sha1,
f4204ab9
JH
46 int flag, struct ref_list *list,
47 struct ref_list **new_entry)
e1e22e37
LT
48{
49 int len;
50 struct ref_list **p = &list, *entry;
51
52 /* Find the place to insert the ref into.. */
53 while ((entry = *p) != NULL) {
54 int cmp = strcmp(entry->name, name);
55 if (cmp > 0)
56 break;
57
58 /* Same as existing entry? */
f4204ab9
JH
59 if (!cmp) {
60 if (new_entry)
61 *new_entry = entry;
e1e22e37 62 return list;
f4204ab9 63 }
e1e22e37
LT
64 p = &entry->next;
65 }
66
67 /* Allocate it and add it in.. */
68 len = strlen(name) + 1;
69 entry = xmalloc(sizeof(struct ref_list) + len);
70 hashcpy(entry->sha1, sha1);
f4204ab9 71 hashclr(entry->peeled);
e1e22e37 72 memcpy(entry->name, name, len);
8da19775 73 entry->flag = flag;
e1e22e37
LT
74 entry->next = *p;
75 *p = entry;
f4204ab9
JH
76 if (new_entry)
77 *new_entry = entry;
e1e22e37
LT
78 return list;
79}
80
5e290ff7
JH
81/*
82 * Future: need to be in "struct repository"
83 * when doing a full libification.
84 */
85struct cached_refs {
86 char did_loose;
87 char did_packed;
88 struct ref_list *loose;
89 struct ref_list *packed;
90} cached_refs;
91
92static void free_ref_list(struct ref_list *list)
93{
94 struct ref_list *next;
95 for ( ; list; list = next) {
96 next = list->next;
97 free(list);
98 }
99}
100
101static void invalidate_cached_refs(void)
e1e22e37 102{
5e290ff7
JH
103 struct cached_refs *ca = &cached_refs;
104
105 if (ca->did_loose && ca->loose)
106 free_ref_list(ca->loose);
107 if (ca->did_packed && ca->packed)
108 free_ref_list(ca->packed);
109 ca->loose = ca->packed = NULL;
110 ca->did_loose = ca->did_packed = 0;
111}
e1e22e37 112
f4204ab9
JH
113static void read_packed_refs(FILE *f, struct cached_refs *cached_refs)
114{
115 struct ref_list *list = NULL;
116 struct ref_list *last = NULL;
117 char refline[PATH_MAX];
118 int flag = REF_ISPACKED;
119
120 while (fgets(refline, sizeof(refline), f)) {
121 unsigned char sha1[20];
122 const char *name;
123 static const char header[] = "# pack-refs with:";
124
125 if (!strncmp(refline, header, sizeof(header)-1)) {
126 const char *traits = refline + sizeof(header) - 1;
127 if (strstr(traits, " peeled "))
128 flag |= REF_KNOWS_PEELED;
129 /* perhaps other traits later as well */
130 continue;
131 }
132
133 name = parse_ref_line(refline, sha1);
134 if (name) {
135 list = add_ref(name, sha1, flag, list, &last);
136 continue;
137 }
138 if (last &&
139 refline[0] == '^' &&
140 strlen(refline) == 42 &&
141 refline[41] == '\n' &&
142 !get_sha1_hex(refline + 1, sha1))
143 hashcpy(last->peeled, sha1);
144 }
145 cached_refs->packed = list;
146}
147
5e290ff7
JH
148static struct ref_list *get_packed_refs(void)
149{
150 if (!cached_refs.did_packed) {
e1e22e37 151 FILE *f = fopen(git_path("packed-refs"), "r");
f4204ab9 152 cached_refs.packed = NULL;
e1e22e37 153 if (f) {
f4204ab9 154 read_packed_refs(f, &cached_refs);
e1e22e37 155 fclose(f);
e1e22e37 156 }
5e290ff7 157 cached_refs.did_packed = 1;
e1e22e37 158 }
5e290ff7 159 return cached_refs.packed;
e1e22e37
LT
160}
161
162static struct ref_list *get_ref_dir(const char *base, struct ref_list *list)
163{
164 DIR *dir = opendir(git_path("%s", base));
165
166 if (dir) {
167 struct dirent *de;
168 int baselen = strlen(base);
ed378ec7 169 char *ref = xmalloc(baselen + 257);
e1e22e37 170
ed378ec7 171 memcpy(ref, base, baselen);
e1e22e37 172 if (baselen && base[baselen-1] != '/')
ed378ec7 173 ref[baselen++] = '/';
e1e22e37
LT
174
175 while ((de = readdir(dir)) != NULL) {
176 unsigned char sha1[20];
177 struct stat st;
8da19775 178 int flag;
e1e22e37
LT
179 int namelen;
180
181 if (de->d_name[0] == '.')
182 continue;
183 namelen = strlen(de->d_name);
184 if (namelen > 255)
185 continue;
186 if (has_extension(de->d_name, ".lock"))
187 continue;
ed378ec7
LT
188 memcpy(ref + baselen, de->d_name, namelen+1);
189 if (stat(git_path("%s", ref), &st) < 0)
e1e22e37
LT
190 continue;
191 if (S_ISDIR(st.st_mode)) {
ed378ec7 192 list = get_ref_dir(ref, list);
e1e22e37
LT
193 continue;
194 }
8da19775 195 if (!resolve_ref(ref, sha1, 1, &flag)) {
ed378ec7 196 error("%s points nowhere!", ref);
e1e22e37
LT
197 continue;
198 }
f4204ab9 199 list = add_ref(ref, sha1, flag, list, NULL);
e1e22e37 200 }
ed378ec7 201 free(ref);
e1e22e37
LT
202 closedir(dir);
203 }
204 return list;
205}
206
207static struct ref_list *get_loose_refs(void)
208{
5e290ff7
JH
209 if (!cached_refs.did_loose) {
210 cached_refs.loose = get_ref_dir("refs", NULL);
211 cached_refs.did_loose = 1;
e1e22e37 212 }
5e290ff7 213 return cached_refs.loose;
e1e22e37
LT
214}
215
ca8db142
LT
216/* We allow "recursive" symbolic refs. Only within reason, though */
217#define MAXDEPTH 5
218
8da19775 219const char *resolve_ref(const char *ref, unsigned char *sha1, int reading, int *flag)
8a65ff76 220{
a876ed83
JH
221 int depth = MAXDEPTH, len;
222 char buffer[256];
ed378ec7 223 static char ref_buffer[256];
ca8db142 224
8da19775
JH
225 if (flag)
226 *flag = 0;
227
a876ed83 228 for (;;) {
ed378ec7 229 const char *path = git_path("%s", ref);
a876ed83
JH
230 struct stat st;
231 char *buf;
232 int fd;
8a65ff76 233
a876ed83
JH
234 if (--depth < 0)
235 return NULL;
ca8db142 236
a876ed83
JH
237 /* Special case: non-existing file.
238 * Not having the refs/heads/new-branch is OK
239 * if we are writing into it, so is .git/HEAD
240 * that points at refs/heads/master still to be
241 * born. It is NOT OK if we are resolving for
242 * reading.
243 */
244 if (lstat(path, &st) < 0) {
434cd0cd
LT
245 struct ref_list *list = get_packed_refs();
246 while (list) {
f4204ab9 247 if (!strcmp(ref, list->name)) {
434cd0cd 248 hashcpy(sha1, list->sha1);
8da19775
JH
249 if (flag)
250 *flag |= REF_ISPACKED;
434cd0cd
LT
251 return ref;
252 }
253 list = list->next;
254 }
a876ed83
JH
255 if (reading || errno != ENOENT)
256 return NULL;
e702496e 257 hashclr(sha1);
ed378ec7 258 return ref;
a876ed83 259 }
ca8db142 260
a876ed83
JH
261 /* Follow "normalized" - ie "refs/.." symlinks by hand */
262 if (S_ISLNK(st.st_mode)) {
263 len = readlink(path, buffer, sizeof(buffer)-1);
264 if (len >= 5 && !memcmp("refs/", buffer, 5)) {
ed378ec7
LT
265 buffer[len] = 0;
266 strcpy(ref_buffer, buffer);
267 ref = ref_buffer;
8da19775
JH
268 if (flag)
269 *flag |= REF_ISSYMREF;
a876ed83
JH
270 continue;
271 }
ca8db142 272 }
a876ed83 273
7a21632f
DS
274 /* Is it a directory? */
275 if (S_ISDIR(st.st_mode)) {
276 errno = EISDIR;
277 return NULL;
278 }
279
a876ed83
JH
280 /*
281 * Anything else, just open it and try to use it as
282 * a ref
283 */
284 fd = open(path, O_RDONLY);
285 if (fd < 0)
286 return NULL;
93d26e4c 287 len = read_in_full(fd, buffer, sizeof(buffer)-1);
a876ed83
JH
288 close(fd);
289
290 /*
291 * Is it a symbolic ref?
292 */
293 if (len < 4 || memcmp("ref:", buffer, 4))
294 break;
295 buf = buffer + 4;
296 len -= 4;
297 while (len && isspace(*buf))
298 buf++, len--;
299 while (len && isspace(buf[len-1]))
ed378ec7
LT
300 len--;
301 buf[len] = 0;
302 memcpy(ref_buffer, buf, len + 1);
303 ref = ref_buffer;
8da19775
JH
304 if (flag)
305 *flag |= REF_ISSYMREF;
8a65ff76 306 }
a876ed83
JH
307 if (len < 40 || get_sha1_hex(buffer, sha1))
308 return NULL;
ed378ec7 309 return ref;
a876ed83
JH
310}
311
ed378ec7 312int read_ref(const char *ref, unsigned char *sha1)
a876ed83 313{
8da19775 314 if (resolve_ref(ref, sha1, 1, NULL))
a876ed83
JH
315 return 0;
316 return -1;
8a65ff76
LT
317}
318
ef06b918
JH
319static int do_one_ref(const char *base, each_ref_fn fn, int trim,
320 void *cb_data, struct ref_list *entry)
321{
322 if (strncmp(base, entry->name, trim))
323 return 0;
324 if (is_null_sha1(entry->sha1))
325 return 0;
326 if (!has_sha1_file(entry->sha1)) {
327 error("%s does not point to a valid object!", entry->name);
328 return 0;
329 }
330 return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
331}
332
cf0adba7
JH
333int peel_ref(const char *ref, unsigned char *sha1)
334{
335 int flag;
336 unsigned char base[20];
337 struct object *o;
338
339 if (!resolve_ref(ref, base, 1, &flag))
340 return -1;
341
342 if ((flag & REF_ISPACKED)) {
343 struct ref_list *list = get_packed_refs();
cf0adba7
JH
344
345 while (list) {
f4204ab9
JH
346 if (!strcmp(list->name, ref)) {
347 if (list->flag & REF_KNOWS_PEELED) {
348 hashcpy(sha1, list->peeled);
349 return 0;
350 }
351 /* older pack-refs did not leave peeled ones */
352 break;
cf0adba7
JH
353 }
354 list = list->next;
355 }
cf0adba7
JH
356 }
357
f4204ab9 358 /* fallback - callers should not call this for unpacked refs */
cf0adba7
JH
359 o = parse_object(base);
360 if (o->type == OBJ_TAG) {
361 o = deref_tag(o, ref, 0);
362 if (o) {
363 hashcpy(sha1, o->sha1);
364 return 0;
365 }
366 }
367 return -1;
368}
369
8da19775
JH
370static int do_for_each_ref(const char *base, each_ref_fn fn, int trim,
371 void *cb_data)
8a65ff76 372{
e1e22e37
LT
373 int retval;
374 struct ref_list *packed = get_packed_refs();
375 struct ref_list *loose = get_loose_refs();
8a65ff76 376
e1e22e37
LT
377 while (packed && loose) {
378 struct ref_list *entry;
379 int cmp = strcmp(packed->name, loose->name);
380 if (!cmp) {
381 packed = packed->next;
382 continue;
6cada6a9 383 }
e1e22e37
LT
384 if (cmp > 0) {
385 entry = loose;
386 loose = loose->next;
387 } else {
388 entry = packed;
389 packed = packed->next;
390 }
ef06b918 391 retval = do_one_ref(base, fn, trim, cb_data, entry);
e1e22e37
LT
392 if (retval)
393 return retval;
394 }
8a65ff76 395
ef06b918
JH
396 for (packed = packed ? packed : loose; packed; packed = packed->next) {
397 retval = do_one_ref(base, fn, trim, cb_data, packed);
398 if (retval)
399 return retval;
8a65ff76 400 }
e1e22e37 401 return 0;
8a65ff76
LT
402}
403
cb5d709f 404int head_ref(each_ref_fn fn, void *cb_data)
723c31fe
LT
405{
406 unsigned char sha1[20];
8da19775
JH
407 int flag;
408
409 if (resolve_ref("HEAD", sha1, 1, &flag))
410 return fn("HEAD", sha1, flag, cb_data);
2f34ba32 411 return 0;
723c31fe
LT
412}
413
cb5d709f 414int for_each_ref(each_ref_fn fn, void *cb_data)
8a65ff76 415{
cb5d709f 416 return do_for_each_ref("refs/", fn, 0, cb_data);
a62be77f
SE
417}
418
cb5d709f 419int for_each_tag_ref(each_ref_fn fn, void *cb_data)
a62be77f 420{
cb5d709f 421 return do_for_each_ref("refs/tags/", fn, 10, cb_data);
a62be77f
SE
422}
423
cb5d709f 424int for_each_branch_ref(each_ref_fn fn, void *cb_data)
a62be77f 425{
cb5d709f 426 return do_for_each_ref("refs/heads/", fn, 11, cb_data);
a62be77f
SE
427}
428
cb5d709f 429int for_each_remote_ref(each_ref_fn fn, void *cb_data)
a62be77f 430{
cb5d709f 431 return do_for_each_ref("refs/remotes/", fn, 13, cb_data);
8a65ff76
LT
432}
433
cb5d709f
JH
434/* NEEDSWORK: This is only used by ssh-upload and it should go; the
435 * caller should do resolve_ref or read_ref like everybody else. Or
436 * maybe everybody else should use get_ref_sha1() instead of doing
437 * read_ref().
438 */
95fc7512
DB
439int get_ref_sha1(const char *ref, unsigned char *sha1)
440{
95fc7512
DB
441 if (check_ref_format(ref))
442 return -1;
ed378ec7 443 return read_ref(mkpath("refs/%s", ref), sha1);
95fc7512
DB
444}
445
03feddd6
JH
446/*
447 * Make sure "ref" is something reasonable to have under ".git/refs/";
448 * We do not like it if:
449 *
450 * - any path component of it begins with ".", or
451 * - it has double dots "..", or
452 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
453 * - it ends with a "/".
454 */
455
456static inline int bad_ref_char(int ch)
457{
458 return (((unsigned) ch) <= ' ' ||
68283999
JH
459 ch == '~' || ch == '^' || ch == ':' ||
460 /* 2.13 Pattern Matching Notation */
461 ch == '?' || ch == '*' || ch == '[');
03feddd6
JH
462}
463
95fc7512
DB
464int check_ref_format(const char *ref)
465{
03feddd6
JH
466 int ch, level;
467 const char *cp = ref;
468
469 level = 0;
470 while (1) {
471 while ((ch = *cp++) == '/')
472 ; /* tolerate duplicated slashes */
473 if (!ch)
474 return -1; /* should not end with slashes */
475
476 /* we are at the beginning of the path component */
477 if (ch == '.' || bad_ref_char(ch))
478 return -1;
479
480 /* scan the rest of the path component */
481 while ((ch = *cp++) != 0) {
482 if (bad_ref_char(ch))
483 return -1;
484 if (ch == '/')
485 break;
486 if (ch == '.' && *cp == '.')
487 return -1;
488 }
489 level++;
490 if (!ch) {
491 if (level < 2)
37adac76 492 return -2; /* at least of form "heads/blah" */
03feddd6
JH
493 return 0;
494 }
495 }
95fc7512
DB
496}
497
e5f38ec3 498static struct ref_lock *verify_lock(struct ref_lock *lock,
4bd18c43
SP
499 const unsigned char *old_sha1, int mustexist)
500{
8da19775 501 if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
434cd0cd 502 error("Can't verify ref %s", lock->ref_name);
4bd18c43
SP
503 unlock_ref(lock);
504 return NULL;
505 }
a89fccd2 506 if (hashcmp(lock->old_sha1, old_sha1)) {
434cd0cd 507 error("Ref %s is at %s but expected %s", lock->ref_name,
4bd18c43
SP
508 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
509 unlock_ref(lock);
510 return NULL;
511 }
512 return lock;
513}
514
bc7127ef
JH
515static int remove_empty_dir_recursive(char *path, int len)
516{
517 DIR *dir = opendir(path);
518 struct dirent *e;
519 int ret = 0;
520
521 if (!dir)
522 return -1;
523 if (path[len-1] != '/')
524 path[len++] = '/';
525 while ((e = readdir(dir)) != NULL) {
526 struct stat st;
527 int namlen;
528 if ((e->d_name[0] == '.') &&
529 ((e->d_name[1] == 0) ||
530 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
531 continue; /* "." and ".." */
532
533 namlen = strlen(e->d_name);
534 if ((len + namlen < PATH_MAX) &&
535 strcpy(path + len, e->d_name) &&
536 !lstat(path, &st) &&
537 S_ISDIR(st.st_mode) &&
28bed6ea 538 !remove_empty_dir_recursive(path, len + namlen))
bc7127ef
JH
539 continue; /* happy */
540
541 /* path too long, stat fails, or non-directory still exists */
542 ret = -1;
543 break;
544 }
545 closedir(dir);
546 if (!ret) {
547 path[len] = 0;
548 ret = rmdir(path);
549 }
550 return ret;
551}
552
553static int remove_empty_directories(char *file)
554{
555 /* we want to create a file but there is a directory there;
556 * if that is an empty directory (or a directory that contains
557 * only empty directories), remove them.
558 */
559 char path[PATH_MAX];
560 int len = strlen(file);
561
562 if (len >= PATH_MAX) /* path too long ;-) */
563 return -1;
564 strcpy(path, file);
565 return remove_empty_dir_recursive(path, len);
566}
567
c976d415
LH
568static int is_refname_available(const char *ref, const char *oldref,
569 struct ref_list *list, int quiet)
570{
571 int namlen = strlen(ref); /* e.g. 'foo/bar' */
572 while (list) {
573 /* list->name could be 'foo' or 'foo/bar/baz' */
574 if (!oldref || strcmp(oldref, list->name)) {
575 int len = strlen(list->name);
576 int cmplen = (namlen < len) ? namlen : len;
577 const char *lead = (namlen < len) ? list->name : ref;
578 if (!strncmp(ref, list->name, cmplen) &&
579 lead[cmplen] == '/') {
580 if (!quiet)
581 error("'%s' exists; cannot create '%s'",
582 list->name, ref);
583 return 0;
584 }
585 }
586 list = list->next;
587 }
588 return 1;
589}
590
c0277d15 591static struct ref_lock *lock_ref_sha1_basic(const char *ref, const unsigned char *old_sha1, int *flag)
4bd18c43 592{
434cd0cd 593 char *ref_file;
ed378ec7 594 const char *orig_ref = ref;
4bd18c43 595 struct ref_lock *lock;
732232a1 596 struct stat st;
5cc3cef9 597 int last_errno = 0;
4431fcc4 598 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
4bd18c43
SP
599
600 lock = xcalloc(1, sizeof(struct ref_lock));
601 lock->lock_fd = -1;
602
c0277d15 603 ref = resolve_ref(ref, lock->old_sha1, mustexist, flag);
bc7127ef
JH
604 if (!ref && errno == EISDIR) {
605 /* we are trying to lock foo but we used to
606 * have foo/bar which now does not exist;
607 * it is normal for the empty directory 'foo'
608 * to remain.
609 */
610 ref_file = git_path("%s", orig_ref);
5cc3cef9
JH
611 if (remove_empty_directories(ref_file)) {
612 last_errno = errno;
613 error("there are still refs under '%s'", orig_ref);
614 goto error_return;
615 }
c0277d15 616 ref = resolve_ref(orig_ref, lock->old_sha1, mustexist, flag);
bc7127ef 617 }
ed378ec7 618 if (!ref) {
5cc3cef9 619 last_errno = errno;
818f477c 620 error("unable to resolve reference %s: %s",
ed378ec7 621 orig_ref, strerror(errno));
5cc3cef9 622 goto error_return;
4bd18c43 623 }
c976d415
LH
624 /* When the ref did not exist and we are creating it,
625 * make sure there is no existing ref that is packed
626 * whose name begins with our refname, nor a ref whose
627 * name is a proper prefix of our refname.
628 */
629 if (is_null_sha1(lock->old_sha1) &&
630 !is_refname_available(ref, NULL, get_packed_refs(), 0))
631 goto error_return;
22a3844e 632
c33d5174 633 lock->lk = xcalloc(1, sizeof(struct lock_file));
4bd18c43 634
434cd0cd 635 lock->ref_name = xstrdup(ref);
1655707c 636 lock->orig_ref_name = xstrdup(orig_ref);
7c1a278d 637 ref_file = git_path("%s", ref);
434cd0cd 638 lock->force_write = lstat(ref_file, &st) && errno == ENOENT;
4bd18c43 639
5cc3cef9
JH
640 if (safe_create_leading_directories(ref_file)) {
641 last_errno = errno;
642 error("unable to create directory for %s", ref_file);
643 goto error_return;
644 }
434cd0cd 645 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, 1);
4bd18c43
SP
646
647 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
5cc3cef9
JH
648
649 error_return:
650 unlock_ref(lock);
651 errno = last_errno;
652 return NULL;
4bd18c43
SP
653}
654
4431fcc4 655struct ref_lock *lock_ref_sha1(const char *ref, const unsigned char *old_sha1)
95fc7512 656{
53cce84c 657 char refpath[PATH_MAX];
95fc7512 658 if (check_ref_format(ref))
4bd18c43 659 return NULL;
53cce84c 660 strcpy(refpath, mkpath("refs/%s", ref));
c0277d15 661 return lock_ref_sha1_basic(refpath, old_sha1, NULL);
4bd18c43
SP
662}
663
4431fcc4 664struct ref_lock *lock_any_ref_for_update(const char *ref, const unsigned char *old_sha1)
4bd18c43 665{
c0277d15
JH
666 return lock_ref_sha1_basic(ref, old_sha1, NULL);
667}
668
26a063a1
JH
669static struct lock_file packlock;
670
c0277d15
JH
671static int repack_without_ref(const char *refname)
672{
673 struct ref_list *list, *packed_ref_list;
674 int fd;
675 int found = 0;
c0277d15
JH
676
677 packed_ref_list = get_packed_refs();
678 for (list = packed_ref_list; list; list = list->next) {
679 if (!strcmp(refname, list->name)) {
680 found = 1;
681 break;
682 }
683 }
684 if (!found)
685 return 0;
c0277d15
JH
686 fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
687 if (fd < 0)
688 return error("cannot delete '%s' from packed refs", refname);
689
690 for (list = packed_ref_list; list; list = list->next) {
691 char line[PATH_MAX + 100];
692 int len;
693
694 if (!strcmp(refname, list->name))
695 continue;
696 len = snprintf(line, sizeof(line), "%s %s\n",
697 sha1_to_hex(list->sha1), list->name);
698 /* this should not happen but just being defensive */
699 if (len > sizeof(line))
700 die("too long a refname '%s'", list->name);
701 write_or_die(fd, line, len);
702 }
703 return commit_lock_file(&packlock);
704}
705
706int delete_ref(const char *refname, unsigned char *sha1)
707{
708 struct ref_lock *lock;
709 int err, i, ret = 0, flag = 0;
710
711 lock = lock_ref_sha1_basic(refname, sha1, &flag);
712 if (!lock)
713 return 1;
714 if (!(flag & REF_ISPACKED)) {
715 /* loose */
716 i = strlen(lock->lk->filename) - 5; /* .lock */
717 lock->lk->filename[i] = 0;
718 err = unlink(lock->lk->filename);
719 if (err) {
720 ret = 1;
721 error("unlink(%s) failed: %s",
722 lock->lk->filename, strerror(errno));
723 }
724 lock->lk->filename[i] = '.';
725 }
726 /* removing the loose one could have resurrected an earlier
727 * packed one. Also, if it was not loose we need to repack
728 * without it.
729 */
730 ret |= repack_without_ref(refname);
731
9a13f0b7 732 err = unlink(git_path("logs/%s", lock->ref_name));
c0277d15
JH
733 if (err && errno != ENOENT)
734 fprintf(stderr, "warning: unlink(%s) failed: %s",
9a13f0b7 735 git_path("logs/%s", lock->ref_name), strerror(errno));
c0277d15
JH
736 invalidate_cached_refs();
737 unlock_ref(lock);
738 return ret;
4bd18c43
SP
739}
740
678d0f4c 741int rename_ref(const char *oldref, const char *newref, const char *logmsg)
c976d415
LH
742{
743 static const char renamed_ref[] = "RENAMED-REF";
744 unsigned char sha1[20], orig_sha1[20];
745 int flag = 0, logmoved = 0;
746 struct ref_lock *lock;
c976d415 747 struct stat loginfo;
16c2bfbb 748 int log = !lstat(git_path("logs/%s", oldref), &loginfo);
c976d415
LH
749
750 if (S_ISLNK(loginfo.st_mode))
751 return error("reflog for %s is a symlink", oldref);
752
753 if (!resolve_ref(oldref, orig_sha1, 1, &flag))
754 return error("refname %s not found", oldref);
755
756 if (!is_refname_available(newref, oldref, get_packed_refs(), 0))
757 return 1;
758
759 if (!is_refname_available(newref, oldref, get_loose_refs(), 0))
760 return 1;
761
c976d415
LH
762 lock = lock_ref_sha1_basic(renamed_ref, NULL, NULL);
763 if (!lock)
764 return error("unable to lock %s", renamed_ref);
765 lock->force_write = 1;
678d0f4c 766 if (write_ref_sha1(lock, orig_sha1, logmsg))
c976d415
LH
767 return error("unable to save current sha1 in %s", renamed_ref);
768
769 if (log && rename(git_path("logs/%s", oldref), git_path("tmp-renamed-log")))
770 return error("unable to move logfile logs/%s to tmp-renamed-log: %s",
771 oldref, strerror(errno));
772
773 if (delete_ref(oldref, orig_sha1)) {
774 error("unable to delete old %s", oldref);
775 goto rollback;
776 }
777
778 if (resolve_ref(newref, sha1, 1, &flag) && delete_ref(newref, sha1)) {
779 if (errno==EISDIR) {
780 if (remove_empty_directories(git_path("%s", newref))) {
781 error("Directory not empty: %s", newref);
782 goto rollback;
783 }
784 } else {
785 error("unable to delete existing %s", newref);
786 goto rollback;
787 }
788 }
789
790 if (log && safe_create_leading_directories(git_path("logs/%s", newref))) {
791 error("unable to create directory for %s", newref);
792 goto rollback;
793 }
794
795 retry:
796 if (log && rename(git_path("tmp-renamed-log"), git_path("logs/%s", newref))) {
d9e74d57
JR
797 if (errno==EISDIR || errno==ENOTDIR) {
798 /*
799 * rename(a, b) when b is an existing
800 * directory ought to result in ISDIR, but
801 * Solaris 5.8 gives ENOTDIR. Sheesh.
802 */
c976d415
LH
803 if (remove_empty_directories(git_path("logs/%s", newref))) {
804 error("Directory not empty: logs/%s", newref);
805 goto rollback;
806 }
807 goto retry;
808 } else {
809 error("unable to move logfile tmp-renamed-log to logs/%s: %s",
810 newref, strerror(errno));
811 goto rollback;
812 }
813 }
814 logmoved = log;
815
816 lock = lock_ref_sha1_basic(newref, NULL, NULL);
817 if (!lock) {
818 error("unable to lock %s for update", newref);
819 goto rollback;
820 }
821
822 lock->force_write = 1;
823 hashcpy(lock->old_sha1, orig_sha1);
678d0f4c 824 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
c976d415
LH
825 error("unable to write current sha1 into %s", newref);
826 goto rollback;
827 }
828
dc81c58c
JS
829 if (!strncmp(oldref, "refs/heads/", 11) &&
830 !strncmp(newref, "refs/heads/", 11)) {
831 char oldsection[1024], newsection[1024];
832
833 snprintf(oldsection, 1024, "branch.%s", oldref + 11);
834 snprintf(newsection, 1024, "branch.%s", newref + 11);
835 if (git_config_rename_section(oldsection, newsection) < 0)
836 return 1;
837 }
838
c976d415
LH
839 return 0;
840
841 rollback:
842 lock = lock_ref_sha1_basic(oldref, NULL, NULL);
843 if (!lock) {
844 error("unable to lock %s for rollback", oldref);
845 goto rollbacklog;
846 }
847
848 lock->force_write = 1;
849 flag = log_all_ref_updates;
850 log_all_ref_updates = 0;
851 if (write_ref_sha1(lock, orig_sha1, NULL))
852 error("unable to write current sha1 into %s", oldref);
853 log_all_ref_updates = flag;
854
855 rollbacklog:
856 if (logmoved && rename(git_path("logs/%s", newref), git_path("logs/%s", oldref)))
857 error("unable to restore logfile %s from %s: %s",
858 oldref, newref, strerror(errno));
859 if (!logmoved && log &&
860 rename(git_path("tmp-renamed-log"), git_path("logs/%s", oldref)))
861 error("unable to restore logfile %s from tmp-renamed-log: %s",
862 oldref, strerror(errno));
863
864 return 1;
865}
866
e5f38ec3 867void unlock_ref(struct ref_lock *lock)
4bd18c43
SP
868{
869 if (lock->lock_fd >= 0) {
870 close(lock->lock_fd);
c33d5174
JH
871 /* Do not free lock->lk -- atexit() still looks at them */
872 if (lock->lk)
873 rollback_lock_file(lock->lk);
4bd18c43 874 }
434cd0cd 875 free(lock->ref_name);
1655707c 876 free(lock->orig_ref_name);
4bd18c43
SP
877 free(lock);
878}
879
9a13f0b7
NP
880static int log_ref_write(const char *ref_name, const unsigned char *old_sha1,
881 const unsigned char *new_sha1, const char *msg)
6de08ae6
SP
882{
883 int logfd, written, oflags = O_APPEND | O_WRONLY;
884 unsigned maxlen, len;
8ac65937 885 int msglen;
9a13f0b7 886 char *log_file, *logrec;
ff4c8485 887 const char *committer;
6de08ae6 888
510c5a8e 889 if (log_all_ref_updates < 0)
7d1864ce 890 log_all_ref_updates = !is_bare_repository();
510c5a8e 891
9a13f0b7
NP
892 log_file = git_path("logs/%s", ref_name);
893
4057deb5 894 if (log_all_ref_updates &&
9a13f0b7 895 (!strncmp(ref_name, "refs/heads/", 11) ||
bd104db1
NP
896 !strncmp(ref_name, "refs/remotes/", 13) ||
897 !strcmp(ref_name, "HEAD"))) {
9a13f0b7 898 if (safe_create_leading_directories(log_file) < 0)
6de08ae6 899 return error("unable to create directory for %s",
9a13f0b7 900 log_file);
6de08ae6
SP
901 oflags |= O_CREAT;
902 }
903
9a13f0b7 904 logfd = open(log_file, oflags, 0666);
6de08ae6 905 if (logfd < 0) {
1974bf62 906 if (!(oflags & O_CREAT) && errno == ENOENT)
6de08ae6 907 return 0;
3b463c3f
JH
908
909 if ((oflags & O_CREAT) && errno == EISDIR) {
9a13f0b7 910 if (remove_empty_directories(log_file)) {
3b463c3f 911 return error("There are still logs under '%s'",
9a13f0b7 912 log_file);
3b463c3f 913 }
9a13f0b7 914 logfd = open(log_file, oflags, 0666);
3b463c3f
JH
915 }
916
917 if (logfd < 0)
918 return error("Unable to append to %s: %s",
9a13f0b7 919 log_file, strerror(errno));
6de08ae6
SP
920 }
921
8ac65937 922 msglen = 0;
6de08ae6 923 if (msg) {
8ac65937
JH
924 /* clean up the message and make sure it is a single line */
925 for ( ; *msg; msg++)
926 if (!isspace(*msg))
927 break;
928 if (*msg) {
929 const char *ep = strchr(msg, '\n');
930 if (ep)
931 msglen = ep - msg;
932 else
933 msglen = strlen(msg);
934 }
6de08ae6 935 }
8ac65937
JH
936
937 committer = git_committer_info(-1);
938 maxlen = strlen(committer) + msglen + 100;
939 logrec = xmalloc(maxlen);
940 len = sprintf(logrec, "%s %s %s\n",
9a13f0b7
NP
941 sha1_to_hex(old_sha1),
942 sha1_to_hex(new_sha1),
8ac65937
JH
943 committer);
944 if (msglen)
945 len += sprintf(logrec + len - 1, "\t%.*s\n", msglen, msg) - 1;
93822c22 946 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
6de08ae6
SP
947 free(logrec);
948 close(logfd);
949 if (written != len)
9a13f0b7 950 return error("Unable to append to %s", log_file);
6de08ae6
SP
951 return 0;
952}
953
4bd18c43
SP
954int write_ref_sha1(struct ref_lock *lock,
955 const unsigned char *sha1, const char *logmsg)
956{
957 static char term = '\n';
958
959 if (!lock)
95fc7512 960 return -1;
a89fccd2 961 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
4bd18c43
SP
962 unlock_ref(lock);
963 return 0;
95fc7512 964 }
93822c22
AW
965 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
966 write_in_full(lock->lock_fd, &term, 1) != 1
4bd18c43 967 || close(lock->lock_fd) < 0) {
c33d5174 968 error("Couldn't write %s", lock->lk->filename);
4bd18c43
SP
969 unlock_ref(lock);
970 return -1;
971 }
5e290ff7 972 invalidate_cached_refs();
bd104db1
NP
973 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
974 (strcmp(lock->ref_name, lock->orig_ref_name) &&
975 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
6de08ae6
SP
976 unlock_ref(lock);
977 return -1;
978 }
c33d5174 979 if (commit_lock_file(lock->lk)) {
434cd0cd 980 error("Couldn't set %s", lock->ref_name);
4bd18c43
SP
981 unlock_ref(lock);
982 return -1;
983 }
984 lock->lock_fd = -1;
985 unlock_ref(lock);
986 return 0;
95fc7512 987}
d556fae2 988
8b5157e4
NP
989int create_symref(const char *ref_target, const char *refs_heads_master,
990 const char *logmsg)
41b625b0
NP
991{
992 const char *lockpath;
993 char ref[1000];
994 int fd, len, written;
995 const char *git_HEAD = git_path("%s", ref_target);
8b5157e4
NP
996 unsigned char old_sha1[20], new_sha1[20];
997
998 if (logmsg && read_ref(ref_target, old_sha1))
999 hashclr(old_sha1);
41b625b0
NP
1000
1001#ifndef NO_SYMLINK_HEAD
1002 if (prefer_symlink_refs) {
1003 unlink(git_HEAD);
1004 if (!symlink(refs_heads_master, git_HEAD))
8b5157e4 1005 goto done;
41b625b0
NP
1006 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1007 }
1008#endif
1009
1010 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
1011 if (sizeof(ref) <= len) {
1012 error("refname too long: %s", refs_heads_master);
1013 return -1;
1014 }
1015 lockpath = mkpath("%s.lock", git_HEAD);
1016 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
1017 if (fd < 0) {
1018 error("Unable to open %s for writing", lockpath);
1019 return -5;
1020 }
1021 written = write_in_full(fd, ref, len);
1022 close(fd);
1023 if (written != len) {
1024 unlink(lockpath);
1025 error("Unable to write to %s", lockpath);
1026 return -2;
1027 }
1028 if (rename(lockpath, git_HEAD) < 0) {
1029 unlink(lockpath);
1030 error("Unable to create %s", git_HEAD);
1031 return -3;
1032 }
1033 if (adjust_shared_perm(git_HEAD)) {
1034 unlink(lockpath);
1035 error("Unable to fix permissions on %s", lockpath);
1036 return -4;
1037 }
8b5157e4
NP
1038
1039 done:
1040 if (logmsg && !read_ref(refs_heads_master, new_sha1))
1041 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
1042
41b625b0
NP
1043 return 0;
1044}
1045
16d7cc90
JH
1046static char *ref_msg(const char *line, const char *endp)
1047{
1048 const char *ep;
1049 char *msg;
1050
1051 line += 82;
1052 for (ep = line; ep < endp && *ep != '\n'; ep++)
1053 ;
1054 msg = xmalloc(ep - line + 1);
1055 memcpy(msg, line, ep - line);
1056 msg[ep - line] = 0;
1057 return msg;
1058}
1059
1060int read_ref_at(const char *ref, unsigned long at_time, int cnt, unsigned char *sha1, char **msg, unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
d556fae2 1061{
e5229042 1062 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
d556fae2 1063 char *tz_c;
e29cb53a 1064 int logfd, tz, reccnt = 0;
d556fae2
SP
1065 struct stat st;
1066 unsigned long date;
e5229042 1067 unsigned char logged_sha1[20];
cb48cb58 1068 void *log_mapped;
d556fae2
SP
1069
1070 logfile = git_path("logs/%s", ref);
1071 logfd = open(logfile, O_RDONLY, 0);
1072 if (logfd < 0)
1073 die("Unable to read log %s: %s", logfile, strerror(errno));
1074 fstat(logfd, &st);
1075 if (!st.st_size)
1076 die("Log %s is empty.", logfile);
cb48cb58
JH
1077 log_mapped = xmmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, logfd, 0);
1078 logdata = log_mapped;
d556fae2
SP
1079 close(logfd);
1080
e5229042 1081 lastrec = NULL;
d556fae2
SP
1082 rec = logend = logdata + st.st_size;
1083 while (logdata < rec) {
e29cb53a 1084 reccnt++;
d556fae2
SP
1085 if (logdata < rec && *(rec-1) == '\n')
1086 rec--;
e5229042
SP
1087 lastgt = NULL;
1088 while (logdata < rec && *(rec-1) != '\n') {
d556fae2 1089 rec--;
e5229042
SP
1090 if (*rec == '>')
1091 lastgt = rec;
1092 }
1093 if (!lastgt)
d556fae2 1094 die("Log %s is corrupt.", logfile);
e5229042 1095 date = strtoul(lastgt + 1, &tz_c, 10);
ab2a1a32 1096 if (date <= at_time || cnt == 0) {
76a44c5c 1097 tz = strtoul(tz_c, NULL, 10);
16d7cc90
JH
1098 if (msg)
1099 *msg = ref_msg(rec, logend);
1100 if (cutoff_time)
1101 *cutoff_time = date;
1102 if (cutoff_tz)
1103 *cutoff_tz = tz;
1104 if (cutoff_cnt)
76a44c5c 1105 *cutoff_cnt = reccnt - 1;
e5229042
SP
1106 if (lastrec) {
1107 if (get_sha1_hex(lastrec, logged_sha1))
1108 die("Log %s is corrupt.", logfile);
1109 if (get_sha1_hex(rec + 41, sha1))
1110 die("Log %s is corrupt.", logfile);
a89fccd2 1111 if (hashcmp(logged_sha1, sha1)) {
e5229042
SP
1112 fprintf(stderr,
1113 "warning: Log %s has gap after %s.\n",
1114 logfile, show_rfc2822_date(date, tz));
1115 }
e5f38ec3
JH
1116 }
1117 else if (date == at_time) {
e5229042
SP
1118 if (get_sha1_hex(rec + 41, sha1))
1119 die("Log %s is corrupt.", logfile);
e5f38ec3
JH
1120 }
1121 else {
e5229042
SP
1122 if (get_sha1_hex(rec + 41, logged_sha1))
1123 die("Log %s is corrupt.", logfile);
a89fccd2 1124 if (hashcmp(logged_sha1, sha1)) {
e5229042
SP
1125 fprintf(stderr,
1126 "warning: Log %s unexpectedly ended on %s.\n",
1127 logfile, show_rfc2822_date(date, tz));
1128 }
1129 }
cb48cb58 1130 munmap(log_mapped, st.st_size);
d556fae2
SP
1131 return 0;
1132 }
e5229042 1133 lastrec = rec;
ab2a1a32
JH
1134 if (cnt > 0)
1135 cnt--;
d556fae2
SP
1136 }
1137
e5229042
SP
1138 rec = logdata;
1139 while (rec < logend && *rec != '>' && *rec != '\n')
1140 rec++;
1141 if (rec == logend || *rec == '\n')
d556fae2 1142 die("Log %s is corrupt.", logfile);
e5229042 1143 date = strtoul(rec + 1, &tz_c, 10);
d556fae2
SP
1144 tz = strtoul(tz_c, NULL, 10);
1145 if (get_sha1_hex(logdata, sha1))
1146 die("Log %s is corrupt.", logfile);
16d7cc90
JH
1147 if (msg)
1148 *msg = ref_msg(logdata, logend);
cb48cb58 1149 munmap(log_mapped, st.st_size);
16d7cc90
JH
1150
1151 if (cutoff_time)
1152 *cutoff_time = date;
1153 if (cutoff_tz)
1154 *cutoff_tz = tz;
1155 if (cutoff_cnt)
1156 *cutoff_cnt = reccnt;
1157 return 1;
d556fae2 1158}
2ff81662 1159
883d60fa 1160int for_each_reflog_ent(const char *ref, each_reflog_ent_fn fn, void *cb_data)
2ff81662
JH
1161{
1162 const char *logfile;
1163 FILE *logfp;
1164 char buf[1024];
2266bf27 1165 int ret = 0;
2ff81662
JH
1166
1167 logfile = git_path("logs/%s", ref);
1168 logfp = fopen(logfile, "r");
1169 if (!logfp)
883d60fa 1170 return -1;
2ff81662
JH
1171 while (fgets(buf, sizeof(buf), logfp)) {
1172 unsigned char osha1[20], nsha1[20];
883d60fa
JS
1173 char *email_end, *message;
1174 unsigned long timestamp;
2266bf27 1175 int len, tz;
2ff81662
JH
1176
1177 /* old SP new SP name <email> SP time TAB msg LF */
1178 len = strlen(buf);
1179 if (len < 83 || buf[len-1] != '\n' ||
1180 get_sha1_hex(buf, osha1) || buf[40] != ' ' ||
883d60fa
JS
1181 get_sha1_hex(buf + 41, nsha1) || buf[81] != ' ' ||
1182 !(email_end = strchr(buf + 82, '>')) ||
1183 email_end[1] != ' ' ||
1184 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1185 !message || message[0] != ' ' ||
1186 (message[1] != '+' && message[1] != '-') ||
1187 !isdigit(message[2]) || !isdigit(message[3]) ||
1188 !isdigit(message[4]) || !isdigit(message[5]) ||
1189 message[6] != '\t')
2ff81662 1190 continue; /* corrupt? */
883d60fa
JS
1191 email_end[1] = '\0';
1192 tz = strtol(message + 1, NULL, 10);
1193 message += 7;
1194 ret = fn(osha1, nsha1, buf+82, timestamp, tz, message, cb_data);
1195 if (ret)
2266bf27 1196 break;
2ff81662
JH
1197 }
1198 fclose(logfp);
2266bf27 1199 return ret;
2ff81662 1200}
e29cb53a 1201