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