rename() fails on Windows if the destination exists.
[4msysgit-hv.git] / refs.c
blobf48045c5c90001ccc6af26fb9f3179ffffd8f831
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
6 /* ISSYMREF=01 and ISPACKED=02 are public interfaces */
7 #define REF_KNOWS_PEELED 04
9 struct ref_list {
10 struct ref_list *next;
11 unsigned char flag; /* ISSYMREF? ISPACKED? */
12 unsigned char sha1[20];
13 unsigned char peeled[20];
14 char name[FLEX_ARRAY];
17 static const char *parse_ref_line(char *line, unsigned char *sha1)
20 * 42: the answer to everything.
22 * In this case, it happens to be the answer to
23 * 40 (length of sha1 hex representation)
24 * +1 (space in between hex and name)
25 * +1 (newline at the end of the line)
27 int len = strlen(line) - 42;
29 if (len <= 0)
30 return NULL;
31 if (get_sha1_hex(line, sha1) < 0)
32 return NULL;
33 if (!isspace(line[40]))
34 return NULL;
35 line += 41;
36 if (isspace(*line))
37 return NULL;
38 if (line[len] != '\n')
39 return NULL;
40 line[len] = 0;
42 return line;
45 static struct ref_list *add_ref(const char *name, const unsigned char *sha1,
46 int flag, struct ref_list *list,
47 struct ref_list **new_entry)
49 int len;
50 struct ref_list **p = &list, *entry;
52 /* Find the place to insert the ref into.. */
53 while ((entry = *p) != NULL) {
54 int cmp = strcmp(entry->name, name);
55 if (cmp > 0)
56 break;
58 /* Same as existing entry? */
59 if (!cmp) {
60 if (new_entry)
61 *new_entry = entry;
62 return list;
64 p = &entry->next;
67 /* Allocate it and add it in.. */
68 len = strlen(name) + 1;
69 entry = xmalloc(sizeof(struct ref_list) + len);
70 hashcpy(entry->sha1, sha1);
71 hashclr(entry->peeled);
72 memcpy(entry->name, name, len);
73 entry->flag = flag;
74 entry->next = *p;
75 *p = entry;
76 if (new_entry)
77 *new_entry = entry;
78 return list;
82 * Future: need to be in "struct repository"
83 * when doing a full libification.
85 struct cached_refs {
86 char did_loose;
87 char did_packed;
88 struct ref_list *loose;
89 struct ref_list *packed;
90 } cached_refs;
92 static void free_ref_list(struct ref_list *list)
94 struct ref_list *next;
95 for ( ; list; list = next) {
96 next = list->next;
97 free(list);
101 static void invalidate_cached_refs(void)
103 struct cached_refs *ca = &cached_refs;
105 if (ca->did_loose && ca->loose)
106 free_ref_list(ca->loose);
107 if (ca->did_packed && ca->packed)
108 free_ref_list(ca->packed);
109 ca->loose = ca->packed = NULL;
110 ca->did_loose = ca->did_packed = 0;
113 static void read_packed_refs(FILE *f, struct cached_refs *cached_refs)
115 struct ref_list *list = NULL;
116 struct ref_list *last = NULL;
117 char refline[PATH_MAX];
118 int flag = REF_ISPACKED;
120 while (fgets(refline, sizeof(refline), f)) {
121 unsigned char sha1[20];
122 const char *name;
123 static const char header[] = "# pack-refs with:";
125 if (!strncmp(refline, header, sizeof(header)-1)) {
126 const char *traits = refline + sizeof(header) - 1;
127 if (strstr(traits, " peeled "))
128 flag |= REF_KNOWS_PEELED;
129 /* perhaps other traits later as well */
130 continue;
133 name = parse_ref_line(refline, sha1);
134 if (name) {
135 list = add_ref(name, sha1, flag, list, &last);
136 continue;
138 if (last &&
139 refline[0] == '^' &&
140 strlen(refline) == 42 &&
141 refline[41] == '\n' &&
142 !get_sha1_hex(refline + 1, sha1))
143 hashcpy(last->peeled, sha1);
145 cached_refs->packed = list;
148 static struct ref_list *get_packed_refs(void)
150 if (!cached_refs.did_packed) {
151 FILE *f = fopen(git_path("packed-refs"), "r");
152 cached_refs.packed = NULL;
153 if (f) {
154 read_packed_refs(f, &cached_refs);
155 fclose(f);
157 cached_refs.did_packed = 1;
159 return cached_refs.packed;
162 static struct ref_list *get_ref_dir(const char *base, struct ref_list *list)
164 DIR *dir = opendir(git_path("%s", base));
166 if (dir) {
167 struct dirent *de;
168 int baselen = strlen(base);
169 char *ref = xmalloc(baselen + 257);
171 memcpy(ref, base, baselen);
172 if (baselen && base[baselen-1] != '/')
173 ref[baselen++] = '/';
175 while ((de = readdir(dir)) != NULL) {
176 unsigned char sha1[20];
177 struct stat st;
178 int flag;
179 int namelen;
181 if (de->d_name[0] == '.')
182 continue;
183 namelen = strlen(de->d_name);
184 if (namelen > 255)
185 continue;
186 if (has_extension(de->d_name, ".lock"))
187 continue;
188 memcpy(ref + baselen, de->d_name, namelen+1);
189 if (stat(git_path("%s", ref), &st) < 0)
190 continue;
191 if (S_ISDIR(st.st_mode)) {
192 list = get_ref_dir(ref, list);
193 continue;
195 if (!resolve_ref(ref, sha1, 1, &flag)) {
196 error("%s points nowhere!", ref);
197 continue;
199 list = add_ref(ref, sha1, flag, list, NULL);
201 free(ref);
202 closedir(dir);
204 return list;
207 static struct ref_list *get_loose_refs(void)
209 if (!cached_refs.did_loose) {
210 cached_refs.loose = get_ref_dir("refs", NULL);
211 cached_refs.did_loose = 1;
213 return cached_refs.loose;
216 /* We allow "recursive" symbolic refs. Only within reason, though */
217 #define MAXDEPTH 5
219 const char *resolve_ref(const char *ref, unsigned char *sha1, int reading, int *flag)
221 int depth = MAXDEPTH, len;
222 char buffer[256];
223 static char ref_buffer[256];
225 if (flag)
226 *flag = 0;
228 for (;;) {
229 const char *path = git_path("%s", ref);
230 struct stat st;
231 char *buf;
232 int fd;
234 if (--depth < 0)
235 return NULL;
237 /* Special case: non-existing file.
238 * Not having the refs/heads/new-branch is OK
239 * if we are writing into it, so is .git/HEAD
240 * that points at refs/heads/master still to be
241 * born. It is NOT OK if we are resolving for
242 * reading.
244 if (lstat(path, &st) < 0) {
245 struct ref_list *list = get_packed_refs();
246 while (list) {
247 if (!strcmp(ref, list->name)) {
248 hashcpy(sha1, list->sha1);
249 if (flag)
250 *flag |= REF_ISPACKED;
251 return ref;
253 list = list->next;
255 if (reading || errno != ENOENT)
256 return NULL;
257 hashclr(sha1);
258 return ref;
261 /* Follow "normalized" - ie "refs/.." symlinks by hand */
262 if (S_ISLNK(st.st_mode)) {
263 len = readlink(path, buffer, sizeof(buffer)-1);
264 if (len >= 5 && !memcmp("refs/", buffer, 5)) {
265 buffer[len] = 0;
266 strcpy(ref_buffer, buffer);
267 ref = ref_buffer;
268 if (flag)
269 *flag |= REF_ISSYMREF;
270 continue;
274 /* Is it a directory? */
275 if (S_ISDIR(st.st_mode)) {
276 errno = EISDIR;
277 return NULL;
281 * Anything else, just open it and try to use it as
282 * a ref
284 fd = open(path, O_RDONLY);
285 if (fd < 0)
286 return NULL;
287 len = read_in_full(fd, buffer, sizeof(buffer)-1);
288 close(fd);
291 * Is it a symbolic ref?
293 if (len < 4 || memcmp("ref:", buffer, 4))
294 break;
295 buf = buffer + 4;
296 len -= 4;
297 while (len && isspace(*buf))
298 buf++, len--;
299 while (len && isspace(buf[len-1]))
300 len--;
301 buf[len] = 0;
302 memcpy(ref_buffer, buf, len + 1);
303 ref = ref_buffer;
304 if (flag)
305 *flag |= REF_ISSYMREF;
307 if (len < 40 || get_sha1_hex(buffer, sha1))
308 return NULL;
309 return ref;
312 int create_symref(const char *ref_target, const char *refs_heads_master)
314 const char *lockpath;
315 char ref[1000];
316 int fd, len, written;
317 const char *git_HEAD = git_path("%s", ref_target);
319 #ifndef NO_SYMLINK_HEAD
320 if (prefer_symlink_refs) {
321 unlink(git_HEAD);
322 if (!symlink(refs_heads_master, git_HEAD))
323 return 0;
324 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
326 #endif
328 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
329 if (sizeof(ref) <= len) {
330 error("refname too long: %s", refs_heads_master);
331 return -1;
333 lockpath = mkpath("%s.lock", git_HEAD);
334 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
335 written = write_in_full(fd, ref, len);
336 close(fd);
337 if (written != len) {
338 unlink(lockpath);
339 error("Unable to write to %s", lockpath);
340 return -2;
342 unlink(git_HEAD);
343 if (rename(lockpath, git_HEAD) < 0) {
344 unlink(lockpath);
345 error("Unable to create %s", git_HEAD);
346 return -3;
348 if (adjust_shared_perm(git_HEAD)) {
349 unlink(lockpath);
350 error("Unable to fix permissions on %s", lockpath);
351 return -4;
353 return 0;
356 int read_ref(const char *ref, unsigned char *sha1)
358 if (resolve_ref(ref, sha1, 1, NULL))
359 return 0;
360 return -1;
363 static int do_one_ref(const char *base, each_ref_fn fn, int trim,
364 void *cb_data, struct ref_list *entry)
366 if (strncmp(base, entry->name, trim))
367 return 0;
368 if (is_null_sha1(entry->sha1))
369 return 0;
370 if (!has_sha1_file(entry->sha1)) {
371 error("%s does not point to a valid object!", entry->name);
372 return 0;
374 return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
377 int peel_ref(const char *ref, unsigned char *sha1)
379 int flag;
380 unsigned char base[20];
381 struct object *o;
383 if (!resolve_ref(ref, base, 1, &flag))
384 return -1;
386 if ((flag & REF_ISPACKED)) {
387 struct ref_list *list = get_packed_refs();
389 while (list) {
390 if (!strcmp(list->name, ref)) {
391 if (list->flag & REF_KNOWS_PEELED) {
392 hashcpy(sha1, list->peeled);
393 return 0;
395 /* older pack-refs did not leave peeled ones */
396 break;
398 list = list->next;
402 /* fallback - callers should not call this for unpacked refs */
403 o = parse_object(base);
404 if (o->type == OBJ_TAG) {
405 o = deref_tag(o, ref, 0);
406 if (o) {
407 hashcpy(sha1, o->sha1);
408 return 0;
411 return -1;
414 static int do_for_each_ref(const char *base, each_ref_fn fn, int trim,
415 void *cb_data)
417 int retval;
418 struct ref_list *packed = get_packed_refs();
419 struct ref_list *loose = get_loose_refs();
421 while (packed && loose) {
422 struct ref_list *entry;
423 int cmp = strcmp(packed->name, loose->name);
424 if (!cmp) {
425 packed = packed->next;
426 continue;
428 if (cmp > 0) {
429 entry = loose;
430 loose = loose->next;
431 } else {
432 entry = packed;
433 packed = packed->next;
435 retval = do_one_ref(base, fn, trim, cb_data, entry);
436 if (retval)
437 return retval;
440 for (packed = packed ? packed : loose; packed; packed = packed->next) {
441 retval = do_one_ref(base, fn, trim, cb_data, packed);
442 if (retval)
443 return retval;
445 return 0;
448 int head_ref(each_ref_fn fn, void *cb_data)
450 unsigned char sha1[20];
451 int flag;
453 if (resolve_ref("HEAD", sha1, 1, &flag))
454 return fn("HEAD", sha1, flag, cb_data);
455 return 0;
458 int for_each_ref(each_ref_fn fn, void *cb_data)
460 return do_for_each_ref("refs/", fn, 0, cb_data);
463 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
465 return do_for_each_ref("refs/tags/", fn, 10, cb_data);
468 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
470 return do_for_each_ref("refs/heads/", fn, 11, cb_data);
473 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
475 return do_for_each_ref("refs/remotes/", fn, 13, cb_data);
478 /* NEEDSWORK: This is only used by ssh-upload and it should go; the
479 * caller should do resolve_ref or read_ref like everybody else. Or
480 * maybe everybody else should use get_ref_sha1() instead of doing
481 * read_ref().
483 int get_ref_sha1(const char *ref, unsigned char *sha1)
485 if (check_ref_format(ref))
486 return -1;
487 return read_ref(mkpath("refs/%s", ref), sha1);
491 * Make sure "ref" is something reasonable to have under ".git/refs/";
492 * We do not like it if:
494 * - any path component of it begins with ".", or
495 * - it has double dots "..", or
496 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
497 * - it ends with a "/".
500 static inline int bad_ref_char(int ch)
502 return (((unsigned) ch) <= ' ' ||
503 ch == '~' || ch == '^' || ch == ':' ||
504 /* 2.13 Pattern Matching Notation */
505 ch == '?' || ch == '*' || ch == '[');
508 int check_ref_format(const char *ref)
510 int ch, level;
511 const char *cp = ref;
513 level = 0;
514 while (1) {
515 while ((ch = *cp++) == '/')
516 ; /* tolerate duplicated slashes */
517 if (!ch)
518 return -1; /* should not end with slashes */
520 /* we are at the beginning of the path component */
521 if (ch == '.' || bad_ref_char(ch))
522 return -1;
524 /* scan the rest of the path component */
525 while ((ch = *cp++) != 0) {
526 if (bad_ref_char(ch))
527 return -1;
528 if (ch == '/')
529 break;
530 if (ch == '.' && *cp == '.')
531 return -1;
533 level++;
534 if (!ch) {
535 if (level < 2)
536 return -2; /* at least of form "heads/blah" */
537 return 0;
542 static struct ref_lock *verify_lock(struct ref_lock *lock,
543 const unsigned char *old_sha1, int mustexist)
545 if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
546 error("Can't verify ref %s", lock->ref_name);
547 unlock_ref(lock);
548 return NULL;
550 if (hashcmp(lock->old_sha1, old_sha1)) {
551 error("Ref %s is at %s but expected %s", lock->ref_name,
552 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
553 unlock_ref(lock);
554 return NULL;
556 return lock;
559 static int remove_empty_dir_recursive(char *path, int len)
561 DIR *dir = opendir(path);
562 struct dirent *e;
563 int ret = 0;
565 if (!dir)
566 return -1;
567 if (path[len-1] != '/')
568 path[len++] = '/';
569 while ((e = readdir(dir)) != NULL) {
570 struct stat st;
571 int namlen;
572 if ((e->d_name[0] == '.') &&
573 ((e->d_name[1] == 0) ||
574 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
575 continue; /* "." and ".." */
577 namlen = strlen(e->d_name);
578 if ((len + namlen < PATH_MAX) &&
579 strcpy(path + len, e->d_name) &&
580 !lstat(path, &st) &&
581 S_ISDIR(st.st_mode) &&
582 !remove_empty_dir_recursive(path, len + namlen))
583 continue; /* happy */
585 /* path too long, stat fails, or non-directory still exists */
586 ret = -1;
587 break;
589 closedir(dir);
590 if (!ret) {
591 path[len] = 0;
592 ret = rmdir(path);
594 return ret;
597 static int remove_empty_directories(char *file)
599 /* we want to create a file but there is a directory there;
600 * if that is an empty directory (or a directory that contains
601 * only empty directories), remove them.
603 char path[PATH_MAX];
604 int len = strlen(file);
606 if (len >= PATH_MAX) /* path too long ;-) */
607 return -1;
608 strcpy(path, file);
609 return remove_empty_dir_recursive(path, len);
612 static int is_refname_available(const char *ref, const char *oldref,
613 struct ref_list *list, int quiet)
615 int namlen = strlen(ref); /* e.g. 'foo/bar' */
616 while (list) {
617 /* list->name could be 'foo' or 'foo/bar/baz' */
618 if (!oldref || strcmp(oldref, list->name)) {
619 int len = strlen(list->name);
620 int cmplen = (namlen < len) ? namlen : len;
621 const char *lead = (namlen < len) ? list->name : ref;
622 if (!strncmp(ref, list->name, cmplen) &&
623 lead[cmplen] == '/') {
624 if (!quiet)
625 error("'%s' exists; cannot create '%s'",
626 list->name, ref);
627 return 0;
630 list = list->next;
632 return 1;
635 static struct ref_lock *lock_ref_sha1_basic(const char *ref, const unsigned char *old_sha1, int *flag)
637 char *ref_file;
638 const char *orig_ref = ref;
639 struct ref_lock *lock;
640 struct stat st;
641 int last_errno = 0;
642 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
644 lock = xcalloc(1, sizeof(struct ref_lock));
645 lock->lock_fd = -1;
647 ref = resolve_ref(ref, lock->old_sha1, mustexist, flag);
648 if (!ref && errno == EISDIR) {
649 /* we are trying to lock foo but we used to
650 * have foo/bar which now does not exist;
651 * it is normal for the empty directory 'foo'
652 * to remain.
654 ref_file = git_path("%s", orig_ref);
655 if (remove_empty_directories(ref_file)) {
656 last_errno = errno;
657 error("there are still refs under '%s'", orig_ref);
658 goto error_return;
660 ref = resolve_ref(orig_ref, lock->old_sha1, mustexist, flag);
662 if (!ref) {
663 last_errno = errno;
664 error("unable to resolve reference %s: %s",
665 orig_ref, strerror(errno));
666 goto error_return;
668 /* When the ref did not exist and we are creating it,
669 * make sure there is no existing ref that is packed
670 * whose name begins with our refname, nor a ref whose
671 * name is a proper prefix of our refname.
673 if (is_null_sha1(lock->old_sha1) &&
674 !is_refname_available(ref, NULL, get_packed_refs(), 0))
675 goto error_return;
677 lock->lk = xcalloc(1, sizeof(struct lock_file));
679 lock->ref_name = xstrdup(ref);
680 lock->log_file = xstrdup(git_path("logs/%s", ref));
681 ref_file = git_path("%s", ref);
682 lock->force_write = lstat(ref_file, &st) && errno == ENOENT;
684 if (safe_create_leading_directories(ref_file)) {
685 last_errno = errno;
686 error("unable to create directory for %s", ref_file);
687 goto error_return;
689 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, 1);
691 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
693 error_return:
694 unlock_ref(lock);
695 errno = last_errno;
696 return NULL;
699 struct ref_lock *lock_ref_sha1(const char *ref, const unsigned char *old_sha1)
701 char refpath[PATH_MAX];
702 if (check_ref_format(ref))
703 return NULL;
704 strcpy(refpath, mkpath("refs/%s", ref));
705 return lock_ref_sha1_basic(refpath, old_sha1, NULL);
708 struct ref_lock *lock_any_ref_for_update(const char *ref, const unsigned char *old_sha1)
710 return lock_ref_sha1_basic(ref, old_sha1, NULL);
713 static struct lock_file packlock;
715 static int repack_without_ref(const char *refname)
717 struct ref_list *list, *packed_ref_list;
718 int fd;
719 int found = 0;
721 packed_ref_list = get_packed_refs();
722 for (list = packed_ref_list; list; list = list->next) {
723 if (!strcmp(refname, list->name)) {
724 found = 1;
725 break;
728 if (!found)
729 return 0;
730 fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
731 if (fd < 0)
732 return error("cannot delete '%s' from packed refs", refname);
734 for (list = packed_ref_list; list; list = list->next) {
735 char line[PATH_MAX + 100];
736 int len;
738 if (!strcmp(refname, list->name))
739 continue;
740 len = snprintf(line, sizeof(line), "%s %s\n",
741 sha1_to_hex(list->sha1), list->name);
742 /* this should not happen but just being defensive */
743 if (len > sizeof(line))
744 die("too long a refname '%s'", list->name);
745 write_or_die(fd, line, len);
747 return commit_lock_file(&packlock);
750 int delete_ref(const char *refname, unsigned char *sha1)
752 struct ref_lock *lock;
753 int err, i, ret = 0, flag = 0;
755 lock = lock_ref_sha1_basic(refname, sha1, &flag);
756 if (!lock)
757 return 1;
758 if (!(flag & REF_ISPACKED)) {
759 /* loose */
760 i = strlen(lock->lk->filename) - 5; /* .lock */
761 lock->lk->filename[i] = 0;
762 err = unlink(lock->lk->filename);
763 if (err) {
764 ret = 1;
765 error("unlink(%s) failed: %s",
766 lock->lk->filename, strerror(errno));
768 lock->lk->filename[i] = '.';
770 /* removing the loose one could have resurrected an earlier
771 * packed one. Also, if it was not loose we need to repack
772 * without it.
774 ret |= repack_without_ref(refname);
776 err = unlink(lock->log_file);
777 if (err && errno != ENOENT)
778 fprintf(stderr, "warning: unlink(%s) failed: %s",
779 lock->log_file, strerror(errno));
780 invalidate_cached_refs();
781 unlock_ref(lock);
782 return ret;
785 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
787 static const char renamed_ref[] = "RENAMED-REF";
788 unsigned char sha1[20], orig_sha1[20];
789 int flag = 0, logmoved = 0;
790 struct ref_lock *lock;
791 struct stat loginfo;
792 int log = !lstat(git_path("logs/%s", oldref), &loginfo);
794 if (S_ISLNK(loginfo.st_mode))
795 return error("reflog for %s is a symlink", oldref);
797 if (!resolve_ref(oldref, orig_sha1, 1, &flag))
798 return error("refname %s not found", oldref);
800 if (!is_refname_available(newref, oldref, get_packed_refs(), 0))
801 return 1;
803 if (!is_refname_available(newref, oldref, get_loose_refs(), 0))
804 return 1;
806 lock = lock_ref_sha1_basic(renamed_ref, NULL, NULL);
807 if (!lock)
808 return error("unable to lock %s", renamed_ref);
809 lock->force_write = 1;
810 if (write_ref_sha1(lock, orig_sha1, logmsg))
811 return error("unable to save current sha1 in %s", renamed_ref);
813 if (log && rename(git_path("logs/%s", oldref), git_path("tmp-renamed-log")))
814 return error("unable to move logfile logs/%s to tmp-renamed-log: %s",
815 oldref, strerror(errno));
817 if (delete_ref(oldref, orig_sha1)) {
818 error("unable to delete old %s", oldref);
819 goto rollback;
822 if (resolve_ref(newref, sha1, 1, &flag) && delete_ref(newref, sha1)) {
823 if (errno==EISDIR) {
824 if (remove_empty_directories(git_path("%s", newref))) {
825 error("Directory not empty: %s", newref);
826 goto rollback;
828 } else {
829 error("unable to delete existing %s", newref);
830 goto rollback;
834 if (log && safe_create_leading_directories(git_path("logs/%s", newref))) {
835 error("unable to create directory for %s", newref);
836 goto rollback;
839 retry:
840 if (log && rename(git_path("tmp-renamed-log"), git_path("logs/%s", newref))) {
841 #ifdef __MINGW32__
842 if (errno == EEXIST) {
843 struct stat st;
844 if (stat(git_path("logs/%s", newref), &st) == 0 && S_ISDIR(st.st_mode))
845 errno = EISDIR;
846 else
847 errno = EEXIST;
849 #endif
850 if (errno==EISDIR || errno==ENOTDIR) {
852 * rename(a, b) when b is an existing
853 * directory ought to result in ISDIR, but
854 * Solaris 5.8 gives ENOTDIR. Sheesh.
856 if (remove_empty_directories(git_path("logs/%s", newref))) {
857 error("Directory not empty: logs/%s", newref);
858 goto rollback;
860 goto retry;
861 } else {
862 error("unable to move logfile tmp-renamed-log to logs/%s: %s",
863 newref, strerror(errno));
864 goto rollback;
867 logmoved = log;
869 lock = lock_ref_sha1_basic(newref, NULL, NULL);
870 if (!lock) {
871 error("unable to lock %s for update", newref);
872 goto rollback;
875 lock->force_write = 1;
876 hashcpy(lock->old_sha1, orig_sha1);
877 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
878 error("unable to write current sha1 into %s", newref);
879 goto rollback;
882 if (!strncmp(oldref, "refs/heads/", 11) &&
883 !strncmp(newref, "refs/heads/", 11)) {
884 char oldsection[1024], newsection[1024];
886 snprintf(oldsection, 1024, "branch.%s", oldref + 11);
887 snprintf(newsection, 1024, "branch.%s", newref + 11);
888 if (git_config_rename_section(oldsection, newsection) < 0)
889 return 1;
892 return 0;
894 rollback:
895 lock = lock_ref_sha1_basic(oldref, NULL, NULL);
896 if (!lock) {
897 error("unable to lock %s for rollback", oldref);
898 goto rollbacklog;
901 lock->force_write = 1;
902 flag = log_all_ref_updates;
903 log_all_ref_updates = 0;
904 if (write_ref_sha1(lock, orig_sha1, NULL))
905 error("unable to write current sha1 into %s", oldref);
906 log_all_ref_updates = flag;
908 rollbacklog:
909 if (logmoved && rename(git_path("logs/%s", newref), git_path("logs/%s", oldref)))
910 error("unable to restore logfile %s from %s: %s",
911 oldref, newref, strerror(errno));
912 if (!logmoved && log &&
913 rename(git_path("tmp-renamed-log"), git_path("logs/%s", oldref)))
914 error("unable to restore logfile %s from tmp-renamed-log: %s",
915 oldref, strerror(errno));
917 return 1;
920 void unlock_ref(struct ref_lock *lock)
922 if (lock->lock_fd >= 0) {
923 close(lock->lock_fd);
924 /* Do not free lock->lk -- atexit() still looks at them */
925 if (lock->lk)
926 rollback_lock_file(lock->lk);
928 free(lock->ref_name);
929 free(lock->log_file);
930 free(lock);
933 static int log_ref_write(struct ref_lock *lock,
934 const unsigned char *sha1, const char *msg)
936 int logfd, written, oflags = O_APPEND | O_WRONLY;
937 unsigned maxlen, len;
938 char *logrec;
939 const char *committer;
941 if (log_all_ref_updates < 0)
942 log_all_ref_updates = !is_bare_repository();
944 if (log_all_ref_updates &&
945 (!strncmp(lock->ref_name, "refs/heads/", 11) ||
946 !strncmp(lock->ref_name, "refs/remotes/", 13))) {
947 if (safe_create_leading_directories(lock->log_file) < 0)
948 return error("unable to create directory for %s",
949 lock->log_file);
950 oflags |= O_CREAT;
953 logfd = open(lock->log_file, oflags, 0666);
954 if (logfd < 0) {
955 if (!(oflags & O_CREAT) && errno == ENOENT)
956 return 0;
958 #ifdef __MINGW32__
959 if ((oflags & O_CREAT) && errno == EACCES) {
960 struct stat st;
961 if (stat(lock->log_file, &st) == 0 && S_ISDIR(st.st_mode))
962 errno = EISDIR;
963 else
964 errno = EACCES;
966 #endif
967 if ((oflags & O_CREAT) && errno == EISDIR) {
968 if (remove_empty_directories(lock->log_file)) {
969 return error("There are still logs under '%s'",
970 lock->log_file);
972 logfd = open(lock->log_file, oflags, 0666);
975 if (logfd < 0)
976 return error("Unable to append to %s: %s",
977 lock->log_file, strerror(errno));
980 committer = git_committer_info(1);
981 if (msg) {
982 maxlen = strlen(committer) + strlen(msg) + 2*40 + 5;
983 logrec = xmalloc(maxlen);
984 len = snprintf(logrec, maxlen, "%s %s %s\t%s\n",
985 sha1_to_hex(lock->old_sha1),
986 sha1_to_hex(sha1),
987 committer,
988 msg);
990 else {
991 maxlen = strlen(committer) + 2*40 + 4;
992 logrec = xmalloc(maxlen);
993 len = snprintf(logrec, maxlen, "%s %s %s\n",
994 sha1_to_hex(lock->old_sha1),
995 sha1_to_hex(sha1),
996 committer);
998 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
999 free(logrec);
1000 close(logfd);
1001 if (written != len)
1002 return error("Unable to append to %s", lock->log_file);
1003 return 0;
1006 int write_ref_sha1(struct ref_lock *lock,
1007 const unsigned char *sha1, const char *logmsg)
1009 static char term = '\n';
1011 if (!lock)
1012 return -1;
1013 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
1014 unlock_ref(lock);
1015 return 0;
1017 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
1018 write_in_full(lock->lock_fd, &term, 1) != 1
1019 || close(lock->lock_fd) < 0) {
1020 error("Couldn't write %s", lock->lk->filename);
1021 unlock_ref(lock);
1022 return -1;
1024 invalidate_cached_refs();
1025 if (log_ref_write(lock, sha1, logmsg) < 0) {
1026 unlock_ref(lock);
1027 return -1;
1029 if (commit_lock_file(lock->lk)) {
1030 error("Couldn't set %s", lock->ref_name);
1031 unlock_ref(lock);
1032 return -1;
1034 lock->lock_fd = -1;
1035 unlock_ref(lock);
1036 return 0;
1039 int read_ref_at(const char *ref, unsigned long at_time, int cnt, unsigned char *sha1)
1041 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
1042 char *tz_c;
1043 int logfd, tz, reccnt = 0;
1044 struct stat st;
1045 unsigned long date;
1046 unsigned char logged_sha1[20];
1048 logfile = git_path("logs/%s", ref);
1049 logfd = open(logfile, O_RDONLY, 0);
1050 if (logfd < 0)
1051 die("Unable to read log %s: %s", logfile, strerror(errno));
1052 fstat(logfd, &st);
1053 if (!st.st_size)
1054 die("Log %s is empty.", logfile);
1055 logdata = xmmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, logfd, 0);
1056 close(logfd);
1058 lastrec = NULL;
1059 rec = logend = logdata + st.st_size;
1060 while (logdata < rec) {
1061 reccnt++;
1062 if (logdata < rec && *(rec-1) == '\n')
1063 rec--;
1064 lastgt = NULL;
1065 while (logdata < rec && *(rec-1) != '\n') {
1066 rec--;
1067 if (*rec == '>')
1068 lastgt = rec;
1070 if (!lastgt)
1071 die("Log %s is corrupt.", logfile);
1072 date = strtoul(lastgt + 1, &tz_c, 10);
1073 if (date <= at_time || cnt == 0) {
1074 if (lastrec) {
1075 if (get_sha1_hex(lastrec, logged_sha1))
1076 die("Log %s is corrupt.", logfile);
1077 if (get_sha1_hex(rec + 41, sha1))
1078 die("Log %s is corrupt.", logfile);
1079 if (hashcmp(logged_sha1, sha1)) {
1080 tz = strtoul(tz_c, NULL, 10);
1081 fprintf(stderr,
1082 "warning: Log %s has gap after %s.\n",
1083 logfile, show_rfc2822_date(date, tz));
1086 else if (date == at_time) {
1087 if (get_sha1_hex(rec + 41, sha1))
1088 die("Log %s is corrupt.", logfile);
1090 else {
1091 if (get_sha1_hex(rec + 41, logged_sha1))
1092 die("Log %s is corrupt.", logfile);
1093 if (hashcmp(logged_sha1, sha1)) {
1094 tz = strtoul(tz_c, NULL, 10);
1095 fprintf(stderr,
1096 "warning: Log %s unexpectedly ended on %s.\n",
1097 logfile, show_rfc2822_date(date, tz));
1100 munmap((void*)logdata, st.st_size);
1101 return 0;
1103 lastrec = rec;
1104 if (cnt > 0)
1105 cnt--;
1108 rec = logdata;
1109 while (rec < logend && *rec != '>' && *rec != '\n')
1110 rec++;
1111 if (rec == logend || *rec == '\n')
1112 die("Log %s is corrupt.", logfile);
1113 date = strtoul(rec + 1, &tz_c, 10);
1114 tz = strtoul(tz_c, NULL, 10);
1115 if (get_sha1_hex(logdata, sha1))
1116 die("Log %s is corrupt.", logfile);
1117 munmap((void*)logdata, st.st_size);
1118 if (at_time)
1119 fprintf(stderr, "warning: Log %s only goes back to %s.\n",
1120 logfile, show_rfc2822_date(date, tz));
1121 else
1122 fprintf(stderr, "warning: Log %s only has %d entries.\n",
1123 logfile, reccnt);
1124 return 0;
1127 int for_each_reflog_ent(const char *ref, each_reflog_ent_fn fn, void *cb_data)
1129 const char *logfile;
1130 FILE *logfp;
1131 char buf[1024];
1133 logfile = git_path("logs/%s", ref);
1134 logfp = fopen(logfile, "r");
1135 if (!logfp)
1136 return -1;
1137 while (fgets(buf, sizeof(buf), logfp)) {
1138 unsigned char osha1[20], nsha1[20];
1139 char *email_end, *message;
1140 unsigned long timestamp;
1141 int len, ret, tz;
1143 /* old SP new SP name <email> SP time TAB msg LF */
1144 len = strlen(buf);
1145 if (len < 83 || buf[len-1] != '\n' ||
1146 get_sha1_hex(buf, osha1) || buf[40] != ' ' ||
1147 get_sha1_hex(buf + 41, nsha1) || buf[81] != ' ' ||
1148 !(email_end = strchr(buf + 82, '>')) ||
1149 email_end[1] != ' ' ||
1150 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1151 !message || message[0] != ' ' ||
1152 (message[1] != '+' && message[1] != '-') ||
1153 !isdigit(message[2]) || !isdigit(message[3]) ||
1154 !isdigit(message[4]) || !isdigit(message[5]) ||
1155 message[6] != '\t')
1156 continue; /* corrupt? */
1157 email_end[1] = '\0';
1158 tz = strtol(message + 1, NULL, 10);
1159 message += 7;
1160 ret = fn(osha1, nsha1, buf+82, timestamp, tz, message, cb_data);
1161 if (ret)
1162 return ret;
1164 fclose(logfp);
1165 return 0;