Merge branch 'lt/case-insensitive'
[git] / refs.c
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
6
7 /* ISSYMREF=01 and ISPACKED=02 are public interfaces */
8 #define REF_KNOWS_PEELED 04
9
10 struct ref_list {
11         struct ref_list *next;
12         unsigned char flag; /* ISSYMREF? ISPACKED? */
13         unsigned char sha1[20];
14         unsigned char peeled[20];
15         char name[FLEX_ARRAY];
16 };
17
18 static const char *parse_ref_line(char *line, unsigned char *sha1)
19 {
20         /*
21          * 42: the answer to everything.
22          *
23          * In this case, it happens to be the answer to
24          *  40 (length of sha1 hex representation)
25          *  +1 (space in between hex and name)
26          *  +1 (newline at the end of the line)
27          */
28         int len = strlen(line) - 42;
29
30         if (len <= 0)
31                 return NULL;
32         if (get_sha1_hex(line, sha1) < 0)
33                 return NULL;
34         if (!isspace(line[40]))
35                 return NULL;
36         line += 41;
37         if (isspace(*line))
38                 return NULL;
39         if (line[len] != '\n')
40                 return NULL;
41         line[len] = 0;
42
43         return line;
44 }
45
46 static struct ref_list *add_ref(const char *name, const unsigned char *sha1,
47                                 int flag, struct ref_list *list,
48                                 struct ref_list **new_entry)
49 {
50         int len;
51         struct ref_list *entry;
52
53         /* Allocate it and add it in.. */
54         len = strlen(name) + 1;
55         entry = xmalloc(sizeof(struct ref_list) + len);
56         hashcpy(entry->sha1, sha1);
57         hashclr(entry->peeled);
58         memcpy(entry->name, name, len);
59         entry->flag = flag;
60         entry->next = list;
61         if (new_entry)
62                 *new_entry = entry;
63         return entry;
64 }
65
66 /* merge sort the ref list */
67 static struct ref_list *sort_ref_list(struct ref_list *list)
68 {
69         int psize, qsize, last_merge_count, cmp;
70         struct ref_list *p, *q, *l, *e;
71         struct ref_list *new_list = list;
72         int k = 1;
73         int merge_count = 0;
74
75         if (!list)
76                 return list;
77
78         do {
79                 last_merge_count = merge_count;
80                 merge_count = 0;
81
82                 psize = 0;
83
84                 p = new_list;
85                 q = new_list;
86                 new_list = NULL;
87                 l = NULL;
88
89                 while (p) {
90                         merge_count++;
91
92                         while (psize < k && q->next) {
93                                 q = q->next;
94                                 psize++;
95                         }
96                         qsize = k;
97
98                         while ((psize > 0) || (qsize > 0 && q)) {
99                                 if (qsize == 0 || !q) {
100                                         e = p;
101                                         p = p->next;
102                                         psize--;
103                                 } else if (psize == 0) {
104                                         e = q;
105                                         q = q->next;
106                                         qsize--;
107                                 } else {
108                                         cmp = strcmp(q->name, p->name);
109                                         if (cmp < 0) {
110                                                 e = q;
111                                                 q = q->next;
112                                                 qsize--;
113                                         } else if (cmp > 0) {
114                                                 e = p;
115                                                 p = p->next;
116                                                 psize--;
117                                         } else {
118                                                 if (hashcmp(q->sha1, p->sha1))
119                                                         die("Duplicated ref, and SHA1s don't match: %s",
120                                                             q->name);
121                                                 warning("Duplicated ref: %s", q->name);
122                                                 e = q;
123                                                 q = q->next;
124                                                 qsize--;
125                                                 free(e);
126                                                 e = p;
127                                                 p = p->next;
128                                                 psize--;
129                                         }
130                                 }
131
132                                 e->next = NULL;
133
134                                 if (l)
135                                         l->next = e;
136                                 if (!new_list)
137                                         new_list = e;
138                                 l = e;
139                         }
140
141                         p = q;
142                 };
143
144                 k = k * 2;
145         } while ((last_merge_count != merge_count) || (last_merge_count != 1));
146
147         return new_list;
148 }
149
150 /*
151  * Future: need to be in "struct repository"
152  * when doing a full libification.
153  */
154 static struct cached_refs {
155         char did_loose;
156         char did_packed;
157         struct ref_list *loose;
158         struct ref_list *packed;
159 } cached_refs;
160 static struct ref_list *current_ref;
161
162 static void free_ref_list(struct ref_list *list)
163 {
164         struct ref_list *next;
165         for ( ; list; list = next) {
166                 next = list->next;
167                 free(list);
168         }
169 }
170
171 static void invalidate_cached_refs(void)
172 {
173         struct cached_refs *ca = &cached_refs;
174
175         if (ca->did_loose && ca->loose)
176                 free_ref_list(ca->loose);
177         if (ca->did_packed && ca->packed)
178                 free_ref_list(ca->packed);
179         ca->loose = ca->packed = NULL;
180         ca->did_loose = ca->did_packed = 0;
181 }
182
183 static void read_packed_refs(FILE *f, struct cached_refs *cached_refs)
184 {
185         struct ref_list *list = NULL;
186         struct ref_list *last = NULL;
187         char refline[PATH_MAX];
188         int flag = REF_ISPACKED;
189
190         while (fgets(refline, sizeof(refline), f)) {
191                 unsigned char sha1[20];
192                 const char *name;
193                 static const char header[] = "# pack-refs with:";
194
195                 if (!strncmp(refline, header, sizeof(header)-1)) {
196                         const char *traits = refline + sizeof(header) - 1;
197                         if (strstr(traits, " peeled "))
198                                 flag |= REF_KNOWS_PEELED;
199                         /* perhaps other traits later as well */
200                         continue;
201                 }
202
203                 name = parse_ref_line(refline, sha1);
204                 if (name) {
205                         list = add_ref(name, sha1, flag, list, &last);
206                         continue;
207                 }
208                 if (last &&
209                     refline[0] == '^' &&
210                     strlen(refline) == 42 &&
211                     refline[41] == '\n' &&
212                     !get_sha1_hex(refline + 1, sha1))
213                         hashcpy(last->peeled, sha1);
214         }
215         cached_refs->packed = sort_ref_list(list);
216 }
217
218 static struct ref_list *get_packed_refs(void)
219 {
220         if (!cached_refs.did_packed) {
221                 FILE *f = fopen(git_path("packed-refs"), "r");
222                 cached_refs.packed = NULL;
223                 if (f) {
224                         read_packed_refs(f, &cached_refs);
225                         fclose(f);
226                 }
227                 cached_refs.did_packed = 1;
228         }
229         return cached_refs.packed;
230 }
231
232 static struct ref_list *get_ref_dir(const char *base, struct ref_list *list)
233 {
234         DIR *dir = opendir(git_path("%s", base));
235
236         if (dir) {
237                 struct dirent *de;
238                 int baselen = strlen(base);
239                 char *ref = xmalloc(baselen + 257);
240
241                 memcpy(ref, base, baselen);
242                 if (baselen && base[baselen-1] != '/')
243                         ref[baselen++] = '/';
244
245                 while ((de = readdir(dir)) != NULL) {
246                         unsigned char sha1[20];
247                         struct stat st;
248                         int flag;
249                         int namelen;
250
251                         if (de->d_name[0] == '.')
252                                 continue;
253                         namelen = strlen(de->d_name);
254                         if (namelen > 255)
255                                 continue;
256                         if (has_extension(de->d_name, ".lock"))
257                                 continue;
258                         memcpy(ref + baselen, de->d_name, namelen+1);
259                         if (stat(git_path("%s", ref), &st) < 0)
260                                 continue;
261                         if (S_ISDIR(st.st_mode)) {
262                                 list = get_ref_dir(ref, list);
263                                 continue;
264                         }
265                         if (!resolve_ref(ref, sha1, 1, &flag)) {
266                                 error("%s points nowhere!", ref);
267                                 continue;
268                         }
269                         list = add_ref(ref, sha1, flag, list, NULL);
270                 }
271                 free(ref);
272                 closedir(dir);
273         }
274         return sort_ref_list(list);
275 }
276
277 static struct ref_list *get_loose_refs(void)
278 {
279         if (!cached_refs.did_loose) {
280                 cached_refs.loose = get_ref_dir("refs", NULL);
281                 cached_refs.did_loose = 1;
282         }
283         return cached_refs.loose;
284 }
285
286 /* We allow "recursive" symbolic refs. Only within reason, though */
287 #define MAXDEPTH 5
288 #define MAXREFLEN (1024)
289
290 static int resolve_gitlink_packed_ref(char *name, int pathlen, const char *refname, unsigned char *result)
291 {
292         FILE *f;
293         struct cached_refs refs;
294         struct ref_list *ref;
295         int retval;
296
297         strcpy(name + pathlen, "packed-refs");
298         f = fopen(name, "r");
299         if (!f)
300                 return -1;
301         read_packed_refs(f, &refs);
302         fclose(f);
303         ref = refs.packed;
304         retval = -1;
305         while (ref) {
306                 if (!strcmp(ref->name, refname)) {
307                         retval = 0;
308                         memcpy(result, ref->sha1, 20);
309                         break;
310                 }
311                 ref = ref->next;
312         }
313         free_ref_list(refs.packed);
314         return retval;
315 }
316
317 static int resolve_gitlink_ref_recursive(char *name, int pathlen, const char *refname, unsigned char *result, int recursion)
318 {
319         int fd, len = strlen(refname);
320         char buffer[128], *p;
321
322         if (recursion > MAXDEPTH || len > MAXREFLEN)
323                 return -1;
324         memcpy(name + pathlen, refname, len+1);
325         fd = open(name, O_RDONLY);
326         if (fd < 0)
327                 return resolve_gitlink_packed_ref(name, pathlen, refname, result);
328
329         len = read(fd, buffer, sizeof(buffer)-1);
330         close(fd);
331         if (len < 0)
332                 return -1;
333         while (len && isspace(buffer[len-1]))
334                 len--;
335         buffer[len] = 0;
336
337         /* Was it a detached head or an old-fashioned symlink? */
338         if (!get_sha1_hex(buffer, result))
339                 return 0;
340
341         /* Symref? */
342         if (strncmp(buffer, "ref:", 4))
343                 return -1;
344         p = buffer + 4;
345         while (isspace(*p))
346                 p++;
347
348         return resolve_gitlink_ref_recursive(name, pathlen, p, result, recursion+1);
349 }
350
351 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *result)
352 {
353         int len = strlen(path), retval;
354         char *gitdir;
355         const char *tmp;
356
357         while (len && path[len-1] == '/')
358                 len--;
359         if (!len)
360                 return -1;
361         gitdir = xmalloc(len + MAXREFLEN + 8);
362         memcpy(gitdir, path, len);
363         memcpy(gitdir + len, "/.git", 6);
364         len += 5;
365
366         tmp = read_gitfile_gently(gitdir);
367         if (tmp) {
368                 free(gitdir);
369                 len = strlen(tmp);
370                 gitdir = xmalloc(len + MAXREFLEN + 3);
371                 memcpy(gitdir, tmp, len);
372         }
373         gitdir[len] = '/';
374         gitdir[++len] = '\0';
375         retval = resolve_gitlink_ref_recursive(gitdir, len, refname, result, 0);
376         free(gitdir);
377         return retval;
378 }
379
380 const char *resolve_ref(const char *ref, unsigned char *sha1, int reading, int *flag)
381 {
382         int depth = MAXDEPTH;
383         ssize_t len;
384         char buffer[256];
385         static char ref_buffer[256];
386
387         if (flag)
388                 *flag = 0;
389
390         for (;;) {
391                 const char *path = git_path("%s", ref);
392                 struct stat st;
393                 char *buf;
394                 int fd;
395
396                 if (--depth < 0)
397                         return NULL;
398
399                 /* Special case: non-existing file.
400                  * Not having the refs/heads/new-branch is OK
401                  * if we are writing into it, so is .git/HEAD
402                  * that points at refs/heads/master still to be
403                  * born.  It is NOT OK if we are resolving for
404                  * reading.
405                  */
406                 if (lstat(path, &st) < 0) {
407                         struct ref_list *list = get_packed_refs();
408                         while (list) {
409                                 if (!strcmp(ref, list->name)) {
410                                         hashcpy(sha1, list->sha1);
411                                         if (flag)
412                                                 *flag |= REF_ISPACKED;
413                                         return ref;
414                                 }
415                                 list = list->next;
416                         }
417                         if (reading || errno != ENOENT)
418                                 return NULL;
419                         hashclr(sha1);
420                         return ref;
421                 }
422
423                 /* Follow "normalized" - ie "refs/.." symlinks by hand */
424                 if (S_ISLNK(st.st_mode)) {
425                         len = readlink(path, buffer, sizeof(buffer)-1);
426                         if (len >= 5 && !memcmp("refs/", buffer, 5)) {
427                                 buffer[len] = 0;
428                                 strcpy(ref_buffer, buffer);
429                                 ref = ref_buffer;
430                                 if (flag)
431                                         *flag |= REF_ISSYMREF;
432                                 continue;
433                         }
434                 }
435
436                 /* Is it a directory? */
437                 if (S_ISDIR(st.st_mode)) {
438                         errno = EISDIR;
439                         return NULL;
440                 }
441
442                 /*
443                  * Anything else, just open it and try to use it as
444                  * a ref
445                  */
446                 fd = open(path, O_RDONLY);
447                 if (fd < 0)
448                         return NULL;
449                 len = read_in_full(fd, buffer, sizeof(buffer)-1);
450                 close(fd);
451
452                 /*
453                  * Is it a symbolic ref?
454                  */
455                 if (len < 4 || memcmp("ref:", buffer, 4))
456                         break;
457                 buf = buffer + 4;
458                 len -= 4;
459                 while (len && isspace(*buf))
460                         buf++, len--;
461                 while (len && isspace(buf[len-1]))
462                         len--;
463                 buf[len] = 0;
464                 memcpy(ref_buffer, buf, len + 1);
465                 ref = ref_buffer;
466                 if (flag)
467                         *flag |= REF_ISSYMREF;
468         }
469         if (len < 40 || get_sha1_hex(buffer, sha1))
470                 return NULL;
471         return ref;
472 }
473
474 int read_ref(const char *ref, unsigned char *sha1)
475 {
476         if (resolve_ref(ref, sha1, 1, NULL))
477                 return 0;
478         return -1;
479 }
480
481 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
482                       void *cb_data, struct ref_list *entry)
483 {
484         if (strncmp(base, entry->name, trim))
485                 return 0;
486         if (is_null_sha1(entry->sha1))
487                 return 0;
488         if (!has_sha1_file(entry->sha1)) {
489                 error("%s does not point to a valid object!", entry->name);
490                 return 0;
491         }
492         current_ref = entry;
493         return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
494 }
495
496 int peel_ref(const char *ref, unsigned char *sha1)
497 {
498         int flag;
499         unsigned char base[20];
500         struct object *o;
501
502         if (current_ref && (current_ref->name == ref
503                 || !strcmp(current_ref->name, ref))) {
504                 if (current_ref->flag & REF_KNOWS_PEELED) {
505                         hashcpy(sha1, current_ref->peeled);
506                         return 0;
507                 }
508                 hashcpy(base, current_ref->sha1);
509                 goto fallback;
510         }
511
512         if (!resolve_ref(ref, base, 1, &flag))
513                 return -1;
514
515         if ((flag & REF_ISPACKED)) {
516                 struct ref_list *list = get_packed_refs();
517
518                 while (list) {
519                         if (!strcmp(list->name, ref)) {
520                                 if (list->flag & REF_KNOWS_PEELED) {
521                                         hashcpy(sha1, list->peeled);
522                                         return 0;
523                                 }
524                                 /* older pack-refs did not leave peeled ones */
525                                 break;
526                         }
527                         list = list->next;
528                 }
529         }
530
531 fallback:
532         o = parse_object(base);
533         if (o && o->type == OBJ_TAG) {
534                 o = deref_tag(o, ref, 0);
535                 if (o) {
536                         hashcpy(sha1, o->sha1);
537                         return 0;
538                 }
539         }
540         return -1;
541 }
542
543 static int do_for_each_ref(const char *base, each_ref_fn fn, int trim,
544                            void *cb_data)
545 {
546         int retval = 0;
547         struct ref_list *packed = get_packed_refs();
548         struct ref_list *loose = get_loose_refs();
549
550         while (packed && loose) {
551                 struct ref_list *entry;
552                 int cmp = strcmp(packed->name, loose->name);
553                 if (!cmp) {
554                         packed = packed->next;
555                         continue;
556                 }
557                 if (cmp > 0) {
558                         entry = loose;
559                         loose = loose->next;
560                 } else {
561                         entry = packed;
562                         packed = packed->next;
563                 }
564                 retval = do_one_ref(base, fn, trim, cb_data, entry);
565                 if (retval)
566                         goto end_each;
567         }
568
569         for (packed = packed ? packed : loose; packed; packed = packed->next) {
570                 retval = do_one_ref(base, fn, trim, cb_data, packed);
571                 if (retval)
572                         goto end_each;
573         }
574
575 end_each:
576         current_ref = NULL;
577         return retval;
578 }
579
580 int head_ref(each_ref_fn fn, void *cb_data)
581 {
582         unsigned char sha1[20];
583         int flag;
584
585         if (resolve_ref("HEAD", sha1, 1, &flag))
586                 return fn("HEAD", sha1, flag, cb_data);
587         return 0;
588 }
589
590 int for_each_ref(each_ref_fn fn, void *cb_data)
591 {
592         return do_for_each_ref("refs/", fn, 0, cb_data);
593 }
594
595 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
596 {
597         return do_for_each_ref("refs/tags/", fn, 10, cb_data);
598 }
599
600 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
601 {
602         return do_for_each_ref("refs/heads/", fn, 11, cb_data);
603 }
604
605 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
606 {
607         return do_for_each_ref("refs/remotes/", fn, 13, cb_data);
608 }
609
610 /*
611  * Make sure "ref" is something reasonable to have under ".git/refs/";
612  * We do not like it if:
613  *
614  * - any path component of it begins with ".", or
615  * - it has double dots "..", or
616  * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
617  * - it ends with a "/".
618  */
619
620 static inline int bad_ref_char(int ch)
621 {
622         if (((unsigned) ch) <= ' ' ||
623             ch == '~' || ch == '^' || ch == ':')
624                 return 1;
625         /* 2.13 Pattern Matching Notation */
626         if (ch == '?' || ch == '[') /* Unsupported */
627                 return 1;
628         if (ch == '*') /* Supported at the end */
629                 return 2;
630         return 0;
631 }
632
633 int check_ref_format(const char *ref)
634 {
635         int ch, level, bad_type;
636         const char *cp = ref;
637
638         level = 0;
639         while (1) {
640                 while ((ch = *cp++) == '/')
641                         ; /* tolerate duplicated slashes */
642                 if (!ch)
643                         /* should not end with slashes */
644                         return CHECK_REF_FORMAT_ERROR;
645
646                 /* we are at the beginning of the path component */
647                 if (ch == '.')
648                         return CHECK_REF_FORMAT_ERROR;
649                 bad_type = bad_ref_char(ch);
650                 if (bad_type) {
651                         return (bad_type == 2 && !*cp)
652                                 ? CHECK_REF_FORMAT_WILDCARD
653                                 : CHECK_REF_FORMAT_ERROR;
654                 }
655
656                 /* scan the rest of the path component */
657                 while ((ch = *cp++) != 0) {
658                         bad_type = bad_ref_char(ch);
659                         if (bad_type) {
660                                 return (bad_type == 2 && !*cp)
661                                         ? CHECK_REF_FORMAT_WILDCARD
662                                         : CHECK_REF_FORMAT_ERROR;
663                         }
664                         if (ch == '/')
665                                 break;
666                         if (ch == '.' && *cp == '.')
667                                 return CHECK_REF_FORMAT_ERROR;
668                 }
669                 level++;
670                 if (!ch) {
671                         if (level < 2)
672                                 return CHECK_REF_FORMAT_ONELEVEL;
673                         return CHECK_REF_FORMAT_OK;
674                 }
675         }
676 }
677
678 const char *ref_rev_parse_rules[] = {
679         "%.*s",
680         "refs/%.*s",
681         "refs/tags/%.*s",
682         "refs/heads/%.*s",
683         "refs/remotes/%.*s",
684         "refs/remotes/%.*s/HEAD",
685         NULL
686 };
687
688 const char *ref_fetch_rules[] = {
689         "%.*s",
690         "refs/%.*s",
691         "refs/heads/%.*s",
692         NULL
693 };
694
695 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
696 {
697         const char **p;
698         const int abbrev_name_len = strlen(abbrev_name);
699
700         for (p = rules; *p; p++) {
701                 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
702                         return 1;
703                 }
704         }
705
706         return 0;
707 }
708
709 static struct ref_lock *verify_lock(struct ref_lock *lock,
710         const unsigned char *old_sha1, int mustexist)
711 {
712         if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
713                 error("Can't verify ref %s", lock->ref_name);
714                 unlock_ref(lock);
715                 return NULL;
716         }
717         if (hashcmp(lock->old_sha1, old_sha1)) {
718                 error("Ref %s is at %s but expected %s", lock->ref_name,
719                         sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
720                 unlock_ref(lock);
721                 return NULL;
722         }
723         return lock;
724 }
725
726 static int remove_empty_directories(const char *file)
727 {
728         /* we want to create a file but there is a directory there;
729          * if that is an empty directory (or a directory that contains
730          * only empty directories), remove them.
731          */
732         struct strbuf path;
733         int result;
734
735         strbuf_init(&path, 20);
736         strbuf_addstr(&path, file);
737
738         result = remove_dir_recursively(&path, 1);
739
740         strbuf_release(&path);
741
742         return result;
743 }
744
745 static int is_refname_available(const char *ref, const char *oldref,
746                                 struct ref_list *list, int quiet)
747 {
748         int namlen = strlen(ref); /* e.g. 'foo/bar' */
749         while (list) {
750                 /* list->name could be 'foo' or 'foo/bar/baz' */
751                 if (!oldref || strcmp(oldref, list->name)) {
752                         int len = strlen(list->name);
753                         int cmplen = (namlen < len) ? namlen : len;
754                         const char *lead = (namlen < len) ? list->name : ref;
755                         if (!strncmp(ref, list->name, cmplen) &&
756                             lead[cmplen] == '/') {
757                                 if (!quiet)
758                                         error("'%s' exists; cannot create '%s'",
759                                               list->name, ref);
760                                 return 0;
761                         }
762                 }
763                 list = list->next;
764         }
765         return 1;
766 }
767
768 static struct ref_lock *lock_ref_sha1_basic(const char *ref, const unsigned char *old_sha1, int flags, int *type_p)
769 {
770         char *ref_file;
771         const char *orig_ref = ref;
772         struct ref_lock *lock;
773         struct stat st;
774         int last_errno = 0;
775         int type;
776         int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
777
778         lock = xcalloc(1, sizeof(struct ref_lock));
779         lock->lock_fd = -1;
780
781         ref = resolve_ref(ref, lock->old_sha1, mustexist, &type);
782         if (!ref && errno == EISDIR) {
783                 /* we are trying to lock foo but we used to
784                  * have foo/bar which now does not exist;
785                  * it is normal for the empty directory 'foo'
786                  * to remain.
787                  */
788                 ref_file = git_path("%s", orig_ref);
789                 if (remove_empty_directories(ref_file)) {
790                         last_errno = errno;
791                         error("there are still refs under '%s'", orig_ref);
792                         goto error_return;
793                 }
794                 ref = resolve_ref(orig_ref, lock->old_sha1, mustexist, &type);
795         }
796         if (type_p)
797             *type_p = type;
798         if (!ref) {
799                 last_errno = errno;
800                 error("unable to resolve reference %s: %s",
801                         orig_ref, strerror(errno));
802                 goto error_return;
803         }
804         /* When the ref did not exist and we are creating it,
805          * make sure there is no existing ref that is packed
806          * whose name begins with our refname, nor a ref whose
807          * name is a proper prefix of our refname.
808          */
809         if (is_null_sha1(lock->old_sha1) &&
810             !is_refname_available(ref, NULL, get_packed_refs(), 0))
811                 goto error_return;
812
813         lock->lk = xcalloc(1, sizeof(struct lock_file));
814
815         if (flags & REF_NODEREF)
816                 ref = orig_ref;
817         lock->ref_name = xstrdup(ref);
818         lock->orig_ref_name = xstrdup(orig_ref);
819         ref_file = git_path("%s", ref);
820         if (lstat(ref_file, &st) && errno == ENOENT)
821                 lock->force_write = 1;
822         if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
823                 lock->force_write = 1;
824
825         if (safe_create_leading_directories(ref_file)) {
826                 last_errno = errno;
827                 error("unable to create directory for %s", ref_file);
828                 goto error_return;
829         }
830         lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, 1);
831
832         return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
833
834  error_return:
835         unlock_ref(lock);
836         errno = last_errno;
837         return NULL;
838 }
839
840 struct ref_lock *lock_ref_sha1(const char *ref, const unsigned char *old_sha1)
841 {
842         char refpath[PATH_MAX];
843         if (check_ref_format(ref))
844                 return NULL;
845         strcpy(refpath, mkpath("refs/%s", ref));
846         return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
847 }
848
849 struct ref_lock *lock_any_ref_for_update(const char *ref, const unsigned char *old_sha1, int flags)
850 {
851         switch (check_ref_format(ref)) {
852         default:
853                 return NULL;
854         case 0:
855         case CHECK_REF_FORMAT_ONELEVEL:
856                 return lock_ref_sha1_basic(ref, old_sha1, flags, NULL);
857         }
858 }
859
860 static struct lock_file packlock;
861
862 static int repack_without_ref(const char *refname)
863 {
864         struct ref_list *list, *packed_ref_list;
865         int fd;
866         int found = 0;
867
868         packed_ref_list = get_packed_refs();
869         for (list = packed_ref_list; list; list = list->next) {
870                 if (!strcmp(refname, list->name)) {
871                         found = 1;
872                         break;
873                 }
874         }
875         if (!found)
876                 return 0;
877         fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
878         if (fd < 0)
879                 return error("cannot delete '%s' from packed refs", refname);
880
881         for (list = packed_ref_list; list; list = list->next) {
882                 char line[PATH_MAX + 100];
883                 int len;
884
885                 if (!strcmp(refname, list->name))
886                         continue;
887                 len = snprintf(line, sizeof(line), "%s %s\n",
888                                sha1_to_hex(list->sha1), list->name);
889                 /* this should not happen but just being defensive */
890                 if (len > sizeof(line))
891                         die("too long a refname '%s'", list->name);
892                 write_or_die(fd, line, len);
893         }
894         return commit_lock_file(&packlock);
895 }
896
897 int delete_ref(const char *refname, const unsigned char *sha1)
898 {
899         struct ref_lock *lock;
900         int err, i, ret = 0, flag = 0;
901
902         lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
903         if (!lock)
904                 return 1;
905         if (!(flag & REF_ISPACKED)) {
906                 /* loose */
907                 i = strlen(lock->lk->filename) - 5; /* .lock */
908                 lock->lk->filename[i] = 0;
909                 err = unlink(lock->lk->filename);
910                 if (err) {
911                         ret = 1;
912                         error("unlink(%s) failed: %s",
913                               lock->lk->filename, strerror(errno));
914                 }
915                 lock->lk->filename[i] = '.';
916         }
917         /* removing the loose one could have resurrected an earlier
918          * packed one.  Also, if it was not loose we need to repack
919          * without it.
920          */
921         ret |= repack_without_ref(refname);
922
923         err = unlink(git_path("logs/%s", lock->ref_name));
924         if (err && errno != ENOENT)
925                 fprintf(stderr, "warning: unlink(%s) failed: %s",
926                         git_path("logs/%s", lock->ref_name), strerror(errno));
927         invalidate_cached_refs();
928         unlock_ref(lock);
929         return ret;
930 }
931
932 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
933 {
934         static const char renamed_ref[] = "RENAMED-REF";
935         unsigned char sha1[20], orig_sha1[20];
936         int flag = 0, logmoved = 0;
937         struct ref_lock *lock;
938         struct stat loginfo;
939         int log = !lstat(git_path("logs/%s", oldref), &loginfo);
940
941         if (S_ISLNK(loginfo.st_mode))
942                 return error("reflog for %s is a symlink", oldref);
943
944         if (!resolve_ref(oldref, orig_sha1, 1, &flag))
945                 return error("refname %s not found", oldref);
946
947         if (!is_refname_available(newref, oldref, get_packed_refs(), 0))
948                 return 1;
949
950         if (!is_refname_available(newref, oldref, get_loose_refs(), 0))
951                 return 1;
952
953         lock = lock_ref_sha1_basic(renamed_ref, NULL, 0, NULL);
954         if (!lock)
955                 return error("unable to lock %s", renamed_ref);
956         lock->force_write = 1;
957         if (write_ref_sha1(lock, orig_sha1, logmsg))
958                 return error("unable to save current sha1 in %s", renamed_ref);
959
960         if (log && rename(git_path("logs/%s", oldref), git_path("tmp-renamed-log")))
961                 return error("unable to move logfile logs/%s to tmp-renamed-log: %s",
962                         oldref, strerror(errno));
963
964         if (delete_ref(oldref, orig_sha1)) {
965                 error("unable to delete old %s", oldref);
966                 goto rollback;
967         }
968
969         if (resolve_ref(newref, sha1, 1, &flag) && delete_ref(newref, sha1)) {
970                 if (errno==EISDIR) {
971                         if (remove_empty_directories(git_path("%s", newref))) {
972                                 error("Directory not empty: %s", newref);
973                                 goto rollback;
974                         }
975                 } else {
976                         error("unable to delete existing %s", newref);
977                         goto rollback;
978                 }
979         }
980
981         if (log && safe_create_leading_directories(git_path("logs/%s", newref))) {
982                 error("unable to create directory for %s", newref);
983                 goto rollback;
984         }
985
986  retry:
987         if (log && rename(git_path("tmp-renamed-log"), git_path("logs/%s", newref))) {
988                 if (errno==EISDIR || errno==ENOTDIR) {
989                         /*
990                          * rename(a, b) when b is an existing
991                          * directory ought to result in ISDIR, but
992                          * Solaris 5.8 gives ENOTDIR.  Sheesh.
993                          */
994                         if (remove_empty_directories(git_path("logs/%s", newref))) {
995                                 error("Directory not empty: logs/%s", newref);
996                                 goto rollback;
997                         }
998                         goto retry;
999                 } else {
1000                         error("unable to move logfile tmp-renamed-log to logs/%s: %s",
1001                                 newref, strerror(errno));
1002                         goto rollback;
1003                 }
1004         }
1005         logmoved = log;
1006
1007         lock = lock_ref_sha1_basic(newref, NULL, 0, NULL);
1008         if (!lock) {
1009                 error("unable to lock %s for update", newref);
1010                 goto rollback;
1011         }
1012
1013         lock->force_write = 1;
1014         hashcpy(lock->old_sha1, orig_sha1);
1015         if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1016                 error("unable to write current sha1 into %s", newref);
1017                 goto rollback;
1018         }
1019
1020         return 0;
1021
1022  rollback:
1023         lock = lock_ref_sha1_basic(oldref, NULL, 0, NULL);
1024         if (!lock) {
1025                 error("unable to lock %s for rollback", oldref);
1026                 goto rollbacklog;
1027         }
1028
1029         lock->force_write = 1;
1030         flag = log_all_ref_updates;
1031         log_all_ref_updates = 0;
1032         if (write_ref_sha1(lock, orig_sha1, NULL))
1033                 error("unable to write current sha1 into %s", oldref);
1034         log_all_ref_updates = flag;
1035
1036  rollbacklog:
1037         if (logmoved && rename(git_path("logs/%s", newref), git_path("logs/%s", oldref)))
1038                 error("unable to restore logfile %s from %s: %s",
1039                         oldref, newref, strerror(errno));
1040         if (!logmoved && log &&
1041             rename(git_path("tmp-renamed-log"), git_path("logs/%s", oldref)))
1042                 error("unable to restore logfile %s from tmp-renamed-log: %s",
1043                         oldref, strerror(errno));
1044
1045         return 1;
1046 }
1047
1048 int close_ref(struct ref_lock *lock)
1049 {
1050         if (close_lock_file(lock->lk))
1051                 return -1;
1052         lock->lock_fd = -1;
1053         return 0;
1054 }
1055
1056 int commit_ref(struct ref_lock *lock)
1057 {
1058         if (commit_lock_file(lock->lk))
1059                 return -1;
1060         lock->lock_fd = -1;
1061         return 0;
1062 }
1063
1064 void unlock_ref(struct ref_lock *lock)
1065 {
1066         /* Do not free lock->lk -- atexit() still looks at them */
1067         if (lock->lk)
1068                 rollback_lock_file(lock->lk);
1069         free(lock->ref_name);
1070         free(lock->orig_ref_name);
1071         free(lock);
1072 }
1073
1074 /*
1075  * copy the reflog message msg to buf, which has been allocated sufficiently
1076  * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1077  * because reflog file is one line per entry.
1078  */
1079 static int copy_msg(char *buf, const char *msg)
1080 {
1081         char *cp = buf;
1082         char c;
1083         int wasspace = 1;
1084
1085         *cp++ = '\t';
1086         while ((c = *msg++)) {
1087                 if (wasspace && isspace(c))
1088                         continue;
1089                 wasspace = isspace(c);
1090                 if (wasspace)
1091                         c = ' ';
1092                 *cp++ = c;
1093         }
1094         while (buf < cp && isspace(cp[-1]))
1095                 cp--;
1096         *cp++ = '\n';
1097         return cp - buf;
1098 }
1099
1100 static int log_ref_write(const char *ref_name, const unsigned char *old_sha1,
1101                          const unsigned char *new_sha1, const char *msg)
1102 {
1103         int logfd, written, oflags = O_APPEND | O_WRONLY;
1104         unsigned maxlen, len;
1105         int msglen;
1106         char *log_file, *logrec;
1107         const char *committer;
1108
1109         if (log_all_ref_updates < 0)
1110                 log_all_ref_updates = !is_bare_repository();
1111
1112         log_file = git_path("logs/%s", ref_name);
1113
1114         if (log_all_ref_updates &&
1115             (!prefixcmp(ref_name, "refs/heads/") ||
1116              !prefixcmp(ref_name, "refs/remotes/") ||
1117              !strcmp(ref_name, "HEAD"))) {
1118                 if (safe_create_leading_directories(log_file) < 0)
1119                         return error("unable to create directory for %s",
1120                                      log_file);
1121                 oflags |= O_CREAT;
1122         }
1123
1124         logfd = open(log_file, oflags, 0666);
1125         if (logfd < 0) {
1126                 if (!(oflags & O_CREAT) && errno == ENOENT)
1127                         return 0;
1128
1129                 if ((oflags & O_CREAT) && errno == EISDIR) {
1130                         if (remove_empty_directories(log_file)) {
1131                                 return error("There are still logs under '%s'",
1132                                              log_file);
1133                         }
1134                         logfd = open(log_file, oflags, 0666);
1135                 }
1136
1137                 if (logfd < 0)
1138                         return error("Unable to append to %s: %s",
1139                                      log_file, strerror(errno));
1140         }
1141
1142         adjust_shared_perm(log_file);
1143
1144         msglen = msg ? strlen(msg) : 0;
1145         committer = git_committer_info(0);
1146         maxlen = strlen(committer) + msglen + 100;
1147         logrec = xmalloc(maxlen);
1148         len = sprintf(logrec, "%s %s %s\n",
1149                       sha1_to_hex(old_sha1),
1150                       sha1_to_hex(new_sha1),
1151                       committer);
1152         if (msglen)
1153                 len += copy_msg(logrec + len - 1, msg) - 1;
1154         written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
1155         free(logrec);
1156         if (close(logfd) != 0 || written != len)
1157                 return error("Unable to append to %s", log_file);
1158         return 0;
1159 }
1160
1161 static int is_branch(const char *refname)
1162 {
1163         return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
1164 }
1165
1166 int write_ref_sha1(struct ref_lock *lock,
1167         const unsigned char *sha1, const char *logmsg)
1168 {
1169         static char term = '\n';
1170         struct object *o;
1171
1172         if (!lock)
1173                 return -1;
1174         if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
1175                 unlock_ref(lock);
1176                 return 0;
1177         }
1178         o = parse_object(sha1);
1179         if (!o) {
1180                 error("Trying to write ref %s with nonexistant object %s",
1181                         lock->ref_name, sha1_to_hex(sha1));
1182                 unlock_ref(lock);
1183                 return -1;
1184         }
1185         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1186                 error("Trying to write non-commit object %s to branch %s",
1187                         sha1_to_hex(sha1), lock->ref_name);
1188                 unlock_ref(lock);
1189                 return -1;
1190         }
1191         if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
1192             write_in_full(lock->lock_fd, &term, 1) != 1
1193                 || close_ref(lock) < 0) {
1194                 error("Couldn't write %s", lock->lk->filename);
1195                 unlock_ref(lock);
1196                 return -1;
1197         }
1198         invalidate_cached_refs();
1199         if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
1200             (strcmp(lock->ref_name, lock->orig_ref_name) &&
1201              log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
1202                 unlock_ref(lock);
1203                 return -1;
1204         }
1205         if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
1206                 /*
1207                  * Special hack: If a branch is updated directly and HEAD
1208                  * points to it (may happen on the remote side of a push
1209                  * for example) then logically the HEAD reflog should be
1210                  * updated too.
1211                  * A generic solution implies reverse symref information,
1212                  * but finding all symrefs pointing to the given branch
1213                  * would be rather costly for this rare event (the direct
1214                  * update of a branch) to be worth it.  So let's cheat and
1215                  * check with HEAD only which should cover 99% of all usage
1216                  * scenarios (even 100% of the default ones).
1217                  */
1218                 unsigned char head_sha1[20];
1219                 int head_flag;
1220                 const char *head_ref;
1221                 head_ref = resolve_ref("HEAD", head_sha1, 1, &head_flag);
1222                 if (head_ref && (head_flag & REF_ISSYMREF) &&
1223                     !strcmp(head_ref, lock->ref_name))
1224                         log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
1225         }
1226         if (commit_ref(lock)) {
1227                 error("Couldn't set %s", lock->ref_name);
1228                 unlock_ref(lock);
1229                 return -1;
1230         }
1231         unlock_ref(lock);
1232         return 0;
1233 }
1234
1235 int create_symref(const char *ref_target, const char *refs_heads_master,
1236                   const char *logmsg)
1237 {
1238         const char *lockpath;
1239         char ref[1000];
1240         int fd, len, written;
1241         char *git_HEAD = xstrdup(git_path("%s", ref_target));
1242         unsigned char old_sha1[20], new_sha1[20];
1243
1244         if (logmsg && read_ref(ref_target, old_sha1))
1245                 hashclr(old_sha1);
1246
1247         if (safe_create_leading_directories(git_HEAD) < 0)
1248                 return error("unable to create directory for %s", git_HEAD);
1249
1250 #ifndef NO_SYMLINK_HEAD
1251         if (prefer_symlink_refs) {
1252                 unlink(git_HEAD);
1253                 if (!symlink(refs_heads_master, git_HEAD))
1254                         goto done;
1255                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1256         }
1257 #endif
1258
1259         len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
1260         if (sizeof(ref) <= len) {
1261                 error("refname too long: %s", refs_heads_master);
1262                 goto error_free_return;
1263         }
1264         lockpath = mkpath("%s.lock", git_HEAD);
1265         fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
1266         if (fd < 0) {
1267                 error("Unable to open %s for writing", lockpath);
1268                 goto error_free_return;
1269         }
1270         written = write_in_full(fd, ref, len);
1271         if (close(fd) != 0 || written != len) {
1272                 error("Unable to write to %s", lockpath);
1273                 goto error_unlink_return;
1274         }
1275         if (rename(lockpath, git_HEAD) < 0) {
1276                 error("Unable to create %s", git_HEAD);
1277                 goto error_unlink_return;
1278         }
1279         if (adjust_shared_perm(git_HEAD)) {
1280                 error("Unable to fix permissions on %s", lockpath);
1281         error_unlink_return:
1282                 unlink(lockpath);
1283         error_free_return:
1284                 free(git_HEAD);
1285                 return -1;
1286         }
1287
1288 #ifndef NO_SYMLINK_HEAD
1289         done:
1290 #endif
1291         if (logmsg && !read_ref(refs_heads_master, new_sha1))
1292                 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
1293
1294         free(git_HEAD);
1295         return 0;
1296 }
1297
1298 static char *ref_msg(const char *line, const char *endp)
1299 {
1300         const char *ep;
1301         line += 82;
1302         ep = memchr(line, '\n', endp - line);
1303         if (!ep)
1304                 ep = endp;
1305         return xmemdupz(line, ep - line);
1306 }
1307
1308 int 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)
1309 {
1310         const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
1311         char *tz_c;
1312         int logfd, tz, reccnt = 0;
1313         struct stat st;
1314         unsigned long date;
1315         unsigned char logged_sha1[20];
1316         void *log_mapped;
1317         size_t mapsz;
1318
1319         logfile = git_path("logs/%s", ref);
1320         logfd = open(logfile, O_RDONLY, 0);
1321         if (logfd < 0)
1322                 die("Unable to read log %s: %s", logfile, strerror(errno));
1323         fstat(logfd, &st);
1324         if (!st.st_size)
1325                 die("Log %s is empty.", logfile);
1326         mapsz = xsize_t(st.st_size);
1327         log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
1328         logdata = log_mapped;
1329         close(logfd);
1330
1331         lastrec = NULL;
1332         rec = logend = logdata + st.st_size;
1333         while (logdata < rec) {
1334                 reccnt++;
1335                 if (logdata < rec && *(rec-1) == '\n')
1336                         rec--;
1337                 lastgt = NULL;
1338                 while (logdata < rec && *(rec-1) != '\n') {
1339                         rec--;
1340                         if (*rec == '>')
1341                                 lastgt = rec;
1342                 }
1343                 if (!lastgt)
1344                         die("Log %s is corrupt.", logfile);
1345                 date = strtoul(lastgt + 1, &tz_c, 10);
1346                 if (date <= at_time || cnt == 0) {
1347                         tz = strtoul(tz_c, NULL, 10);
1348                         if (msg)
1349                                 *msg = ref_msg(rec, logend);
1350                         if (cutoff_time)
1351                                 *cutoff_time = date;
1352                         if (cutoff_tz)
1353                                 *cutoff_tz = tz;
1354                         if (cutoff_cnt)
1355                                 *cutoff_cnt = reccnt - 1;
1356                         if (lastrec) {
1357                                 if (get_sha1_hex(lastrec, logged_sha1))
1358                                         die("Log %s is corrupt.", logfile);
1359                                 if (get_sha1_hex(rec + 41, sha1))
1360                                         die("Log %s is corrupt.", logfile);
1361                                 if (hashcmp(logged_sha1, sha1)) {
1362                                         fprintf(stderr,
1363                                                 "warning: Log %s has gap after %s.\n",
1364                                                 logfile, show_date(date, tz, DATE_RFC2822));
1365                                 }
1366                         }
1367                         else if (date == at_time) {
1368                                 if (get_sha1_hex(rec + 41, sha1))
1369                                         die("Log %s is corrupt.", logfile);
1370                         }
1371                         else {
1372                                 if (get_sha1_hex(rec + 41, logged_sha1))
1373                                         die("Log %s is corrupt.", logfile);
1374                                 if (hashcmp(logged_sha1, sha1)) {
1375                                         fprintf(stderr,
1376                                                 "warning: Log %s unexpectedly ended on %s.\n",
1377                                                 logfile, show_date(date, tz, DATE_RFC2822));
1378                                 }
1379                         }
1380                         munmap(log_mapped, mapsz);
1381                         return 0;
1382                 }
1383                 lastrec = rec;
1384                 if (cnt > 0)
1385                         cnt--;
1386         }
1387
1388         rec = logdata;
1389         while (rec < logend && *rec != '>' && *rec != '\n')
1390                 rec++;
1391         if (rec == logend || *rec == '\n')
1392                 die("Log %s is corrupt.", logfile);
1393         date = strtoul(rec + 1, &tz_c, 10);
1394         tz = strtoul(tz_c, NULL, 10);
1395         if (get_sha1_hex(logdata, sha1))
1396                 die("Log %s is corrupt.", logfile);
1397         if (msg)
1398                 *msg = ref_msg(logdata, logend);
1399         munmap(log_mapped, mapsz);
1400
1401         if (cutoff_time)
1402                 *cutoff_time = date;
1403         if (cutoff_tz)
1404                 *cutoff_tz = tz;
1405         if (cutoff_cnt)
1406                 *cutoff_cnt = reccnt;
1407         return 1;
1408 }
1409
1410 int for_each_reflog_ent(const char *ref, each_reflog_ent_fn fn, void *cb_data)
1411 {
1412         const char *logfile;
1413         FILE *logfp;
1414         char buf[1024];
1415         int ret = 0;
1416
1417         logfile = git_path("logs/%s", ref);
1418         logfp = fopen(logfile, "r");
1419         if (!logfp)
1420                 return -1;
1421         while (fgets(buf, sizeof(buf), logfp)) {
1422                 unsigned char osha1[20], nsha1[20];
1423                 char *email_end, *message;
1424                 unsigned long timestamp;
1425                 int len, tz;
1426
1427                 /* old SP new SP name <email> SP time TAB msg LF */
1428                 len = strlen(buf);
1429                 if (len < 83 || buf[len-1] != '\n' ||
1430                     get_sha1_hex(buf, osha1) || buf[40] != ' ' ||
1431                     get_sha1_hex(buf + 41, nsha1) || buf[81] != ' ' ||
1432                     !(email_end = strchr(buf + 82, '>')) ||
1433                     email_end[1] != ' ' ||
1434                     !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1435                     !message || message[0] != ' ' ||
1436                     (message[1] != '+' && message[1] != '-') ||
1437                     !isdigit(message[2]) || !isdigit(message[3]) ||
1438                     !isdigit(message[4]) || !isdigit(message[5]))
1439                         continue; /* corrupt? */
1440                 email_end[1] = '\0';
1441                 tz = strtol(message + 1, NULL, 10);
1442                 if (message[6] != '\t')
1443                         message += 6;
1444                 else
1445                         message += 7;
1446                 ret = fn(osha1, nsha1, buf+82, timestamp, tz, message, cb_data);
1447                 if (ret)
1448                         break;
1449         }
1450         fclose(logfp);
1451         return ret;
1452 }
1453
1454 static int do_for_each_reflog(const char *base, each_ref_fn fn, void *cb_data)
1455 {
1456         DIR *dir = opendir(git_path("logs/%s", base));
1457         int retval = 0;
1458
1459         if (dir) {
1460                 struct dirent *de;
1461                 int baselen = strlen(base);
1462                 char *log = xmalloc(baselen + 257);
1463
1464                 memcpy(log, base, baselen);
1465                 if (baselen && base[baselen-1] != '/')
1466                         log[baselen++] = '/';
1467
1468                 while ((de = readdir(dir)) != NULL) {
1469                         struct stat st;
1470                         int namelen;
1471
1472                         if (de->d_name[0] == '.')
1473                                 continue;
1474                         namelen = strlen(de->d_name);
1475                         if (namelen > 255)
1476                                 continue;
1477                         if (has_extension(de->d_name, ".lock"))
1478                                 continue;
1479                         memcpy(log + baselen, de->d_name, namelen+1);
1480                         if (stat(git_path("logs/%s", log), &st) < 0)
1481                                 continue;
1482                         if (S_ISDIR(st.st_mode)) {
1483                                 retval = do_for_each_reflog(log, fn, cb_data);
1484                         } else {
1485                                 unsigned char sha1[20];
1486                                 if (!resolve_ref(log, sha1, 0, NULL))
1487                                         retval = error("bad ref for %s", log);
1488                                 else
1489                                         retval = fn(log, sha1, 0, cb_data);
1490                         }
1491                         if (retval)
1492                                 break;
1493                 }
1494                 free(log);
1495                 closedir(dir);
1496         }
1497         else if (*base)
1498                 return errno;
1499         return retval;
1500 }
1501
1502 int for_each_reflog(each_ref_fn fn, void *cb_data)
1503 {
1504         return do_for_each_reflog("", fn, cb_data);
1505 }
1506
1507 int update_ref(const char *action, const char *refname,
1508                 const unsigned char *sha1, const unsigned char *oldval,
1509                 int flags, enum action_on_err onerr)
1510 {
1511         static struct ref_lock *lock;
1512         lock = lock_any_ref_for_update(refname, oldval, flags);
1513         if (!lock) {
1514                 const char *str = "Cannot lock the ref '%s'.";
1515                 switch (onerr) {
1516                 case MSG_ON_ERR: error(str, refname); break;
1517                 case DIE_ON_ERR: die(str, refname); break;
1518                 case QUIET_ON_ERR: break;
1519                 }
1520                 return 1;
1521         }
1522         if (write_ref_sha1(lock, sha1, action) < 0) {
1523                 const char *str = "Cannot update the ref '%s'.";
1524                 switch (onerr) {
1525                 case MSG_ON_ERR: error(str, refname); break;
1526                 case DIE_ON_ERR: die(str, refname); break;
1527                 case QUIET_ON_ERR: break;
1528                 }
1529                 return 1;
1530         }
1531         return 0;
1532 }
1533
1534 struct ref *find_ref_by_name(struct ref *list, const char *name)
1535 {
1536         for ( ; list; list = list->next)
1537                 if (!strcmp(list->name, name))
1538                         return list;
1539         return NULL;
1540 }