Clean up "git-branch.sh" and add remove recursive dir test cases.
[git/git.git] / refs.c
CommitLineData
95fc7512
DB
1#include "refs.h"
2#include "cache.h"
3
4#include <errno.h>
5
e1e22e37
LT
6struct ref_list {
7 struct ref_list *next;
8da19775 8 unsigned char flag; /* ISSYMREF? ISPACKED? */
e1e22e37
LT
9 unsigned char sha1[20];
10 char name[FLEX_ARRAY];
11};
12
13static const char *parse_ref_line(char *line, unsigned char *sha1)
14{
15 /*
16 * 42: the answer to everything.
17 *
18 * In this case, it happens to be the answer to
19 * 40 (length of sha1 hex representation)
20 * +1 (space in between hex and name)
21 * +1 (newline at the end of the line)
22 */
23 int len = strlen(line) - 42;
24
25 if (len <= 0)
26 return NULL;
27 if (get_sha1_hex(line, sha1) < 0)
28 return NULL;
29 if (!isspace(line[40]))
30 return NULL;
31 line += 41;
434cd0cd
LT
32 if (isspace(*line))
33 return NULL;
e1e22e37
LT
34 if (line[len] != '\n')
35 return NULL;
36 line[len] = 0;
37 return line;
38}
39
8da19775
JH
40static struct ref_list *add_ref(const char *name, const unsigned char *sha1,
41 int flag, struct ref_list *list)
e1e22e37
LT
42{
43 int len;
44 struct ref_list **p = &list, *entry;
45
46 /* Find the place to insert the ref into.. */
47 while ((entry = *p) != NULL) {
48 int cmp = strcmp(entry->name, name);
49 if (cmp > 0)
50 break;
51
52 /* Same as existing entry? */
53 if (!cmp)
54 return list;
55 p = &entry->next;
56 }
57
58 /* Allocate it and add it in.. */
59 len = strlen(name) + 1;
60 entry = xmalloc(sizeof(struct ref_list) + len);
61 hashcpy(entry->sha1, sha1);
62 memcpy(entry->name, name, len);
8da19775 63 entry->flag = flag;
e1e22e37
LT
64 entry->next = *p;
65 *p = entry;
66 return list;
67}
68
5e290ff7
JH
69/*
70 * Future: need to be in "struct repository"
71 * when doing a full libification.
72 */
73struct cached_refs {
74 char did_loose;
75 char did_packed;
76 struct ref_list *loose;
77 struct ref_list *packed;
78} cached_refs;
79
80static void free_ref_list(struct ref_list *list)
81{
82 struct ref_list *next;
83 for ( ; list; list = next) {
84 next = list->next;
85 free(list);
86 }
87}
88
89static void invalidate_cached_refs(void)
e1e22e37 90{
5e290ff7
JH
91 struct cached_refs *ca = &cached_refs;
92
93 if (ca->did_loose && ca->loose)
94 free_ref_list(ca->loose);
95 if (ca->did_packed && ca->packed)
96 free_ref_list(ca->packed);
97 ca->loose = ca->packed = NULL;
98 ca->did_loose = ca->did_packed = 0;
99}
e1e22e37 100
5e290ff7
JH
101static struct ref_list *get_packed_refs(void)
102{
103 if (!cached_refs.did_packed) {
104 struct ref_list *refs = NULL;
e1e22e37
LT
105 FILE *f = fopen(git_path("packed-refs"), "r");
106 if (f) {
107 struct ref_list *list = NULL;
108 char refline[PATH_MAX];
109 while (fgets(refline, sizeof(refline), f)) {
110 unsigned char sha1[20];
111 const char *name = parse_ref_line(refline, sha1);
112 if (!name)
113 continue;
8da19775 114 list = add_ref(name, sha1, REF_ISPACKED, list);
e1e22e37
LT
115 }
116 fclose(f);
117 refs = list;
118 }
5e290ff7
JH
119 cached_refs.packed = refs;
120 cached_refs.did_packed = 1;
e1e22e37 121 }
5e290ff7 122 return cached_refs.packed;
e1e22e37
LT
123}
124
125static struct ref_list *get_ref_dir(const char *base, struct ref_list *list)
126{
127 DIR *dir = opendir(git_path("%s", base));
128
129 if (dir) {
130 struct dirent *de;
131 int baselen = strlen(base);
ed378ec7 132 char *ref = xmalloc(baselen + 257);
e1e22e37 133
ed378ec7 134 memcpy(ref, base, baselen);
e1e22e37 135 if (baselen && base[baselen-1] != '/')
ed378ec7 136 ref[baselen++] = '/';
e1e22e37
LT
137
138 while ((de = readdir(dir)) != NULL) {
139 unsigned char sha1[20];
140 struct stat st;
8da19775 141 int flag;
e1e22e37
LT
142 int namelen;
143
144 if (de->d_name[0] == '.')
145 continue;
146 namelen = strlen(de->d_name);
147 if (namelen > 255)
148 continue;
149 if (has_extension(de->d_name, ".lock"))
150 continue;
ed378ec7
LT
151 memcpy(ref + baselen, de->d_name, namelen+1);
152 if (stat(git_path("%s", ref), &st) < 0)
e1e22e37
LT
153 continue;
154 if (S_ISDIR(st.st_mode)) {
ed378ec7 155 list = get_ref_dir(ref, list);
e1e22e37
LT
156 continue;
157 }
8da19775 158 if (!resolve_ref(ref, sha1, 1, &flag)) {
ed378ec7 159 error("%s points nowhere!", ref);
e1e22e37
LT
160 continue;
161 }
8da19775 162 list = add_ref(ref, sha1, flag, list);
e1e22e37 163 }
ed378ec7 164 free(ref);
e1e22e37
LT
165 closedir(dir);
166 }
167 return list;
168}
169
170static struct ref_list *get_loose_refs(void)
171{
5e290ff7
JH
172 if (!cached_refs.did_loose) {
173 cached_refs.loose = get_ref_dir("refs", NULL);
174 cached_refs.did_loose = 1;
e1e22e37 175 }
5e290ff7 176 return cached_refs.loose;
e1e22e37
LT
177}
178
ca8db142
LT
179/* We allow "recursive" symbolic refs. Only within reason, though */
180#define MAXDEPTH 5
181
8da19775 182const char *resolve_ref(const char *ref, unsigned char *sha1, int reading, int *flag)
8a65ff76 183{
a876ed83
JH
184 int depth = MAXDEPTH, len;
185 char buffer[256];
ed378ec7 186 static char ref_buffer[256];
ca8db142 187
8da19775
JH
188 if (flag)
189 *flag = 0;
190
a876ed83 191 for (;;) {
ed378ec7 192 const char *path = git_path("%s", ref);
a876ed83
JH
193 struct stat st;
194 char *buf;
195 int fd;
8a65ff76 196
a876ed83
JH
197 if (--depth < 0)
198 return NULL;
ca8db142 199
a876ed83
JH
200 /* Special case: non-existing file.
201 * Not having the refs/heads/new-branch is OK
202 * if we are writing into it, so is .git/HEAD
203 * that points at refs/heads/master still to be
204 * born. It is NOT OK if we are resolving for
205 * reading.
206 */
207 if (lstat(path, &st) < 0) {
434cd0cd
LT
208 struct ref_list *list = get_packed_refs();
209 while (list) {
210 if (!strcmp(ref, list->name)) {
211 hashcpy(sha1, list->sha1);
8da19775
JH
212 if (flag)
213 *flag |= REF_ISPACKED;
434cd0cd
LT
214 return ref;
215 }
216 list = list->next;
217 }
a876ed83
JH
218 if (reading || errno != ENOENT)
219 return NULL;
e702496e 220 hashclr(sha1);
ed378ec7 221 return ref;
a876ed83 222 }
ca8db142 223
a876ed83
JH
224 /* Follow "normalized" - ie "refs/.." symlinks by hand */
225 if (S_ISLNK(st.st_mode)) {
226 len = readlink(path, buffer, sizeof(buffer)-1);
227 if (len >= 5 && !memcmp("refs/", buffer, 5)) {
ed378ec7
LT
228 buffer[len] = 0;
229 strcpy(ref_buffer, buffer);
230 ref = ref_buffer;
8da19775
JH
231 if (flag)
232 *flag |= REF_ISSYMREF;
a876ed83
JH
233 continue;
234 }
ca8db142 235 }
a876ed83
JH
236
237 /*
238 * Anything else, just open it and try to use it as
239 * a ref
240 */
241 fd = open(path, O_RDONLY);
242 if (fd < 0)
243 return NULL;
244 len = read(fd, buffer, sizeof(buffer)-1);
245 close(fd);
246
247 /*
248 * Is it a symbolic ref?
249 */
250 if (len < 4 || memcmp("ref:", buffer, 4))
251 break;
252 buf = buffer + 4;
253 len -= 4;
254 while (len && isspace(*buf))
255 buf++, len--;
256 while (len && isspace(buf[len-1]))
ed378ec7
LT
257 len--;
258 buf[len] = 0;
259 memcpy(ref_buffer, buf, len + 1);
260 ref = ref_buffer;
8da19775
JH
261 if (flag)
262 *flag |= REF_ISSYMREF;
8a65ff76 263 }
a876ed83
JH
264 if (len < 40 || get_sha1_hex(buffer, sha1))
265 return NULL;
ed378ec7 266 return ref;
a876ed83
JH
267}
268
ed378ec7 269int create_symref(const char *ref_target, const char *refs_heads_master)
8098a178 270{
8098a178
JH
271 const char *lockpath;
272 char ref[1000];
273 int fd, len, written;
ed378ec7 274 const char *git_HEAD = git_path("%s", ref_target);
8098a178 275
9f0bb90d
JH
276#ifndef NO_SYMLINK_HEAD
277 if (prefer_symlink_refs) {
f8348be3
JS
278 unlink(git_HEAD);
279 if (!symlink(refs_heads_master, git_HEAD))
280 return 0;
281 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
282 }
303958dc
JS
283#endif
284
8098a178
JH
285 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
286 if (sizeof(ref) <= len) {
287 error("refname too long: %s", refs_heads_master);
288 return -1;
289 }
290 lockpath = mkpath("%s.lock", git_HEAD);
291 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
292 written = write(fd, ref, len);
293 close(fd);
294 if (written != len) {
295 unlink(lockpath);
296 error("Unable to write to %s", lockpath);
297 return -2;
298 }
299 if (rename(lockpath, git_HEAD) < 0) {
300 unlink(lockpath);
301 error("Unable to create %s", git_HEAD);
302 return -3;
303 }
138086a7
JH
304 if (adjust_shared_perm(git_HEAD)) {
305 unlink(lockpath);
306 error("Unable to fix permissions on %s", lockpath);
307 return -4;
308 }
8098a178 309 return 0;
8098a178
JH
310}
311
ed378ec7 312int read_ref(const char *ref, unsigned char *sha1)
a876ed83 313{
8da19775 314 if (resolve_ref(ref, sha1, 1, NULL))
a876ed83
JH
315 return 0;
316 return -1;
8a65ff76
LT
317}
318
8da19775
JH
319static int do_for_each_ref(const char *base, each_ref_fn fn, int trim,
320 void *cb_data)
8a65ff76 321{
e1e22e37
LT
322 int retval;
323 struct ref_list *packed = get_packed_refs();
324 struct ref_list *loose = get_loose_refs();
8a65ff76 325
e1e22e37
LT
326 while (packed && loose) {
327 struct ref_list *entry;
328 int cmp = strcmp(packed->name, loose->name);
329 if (!cmp) {
330 packed = packed->next;
331 continue;
6cada6a9 332 }
e1e22e37
LT
333 if (cmp > 0) {
334 entry = loose;
335 loose = loose->next;
336 } else {
337 entry = packed;
338 packed = packed->next;
339 }
340 if (strncmp(base, entry->name, trim))
341 continue;
b37a562a
LT
342 if (is_null_sha1(entry->sha1))
343 continue;
344 if (!has_sha1_file(entry->sha1)) {
345 error("%s does not point to a valid object!", entry->name);
346 continue;
347 }
8da19775
JH
348 retval = fn(entry->name + trim, entry->sha1,
349 entry->flag, cb_data);
e1e22e37
LT
350 if (retval)
351 return retval;
352 }
8a65ff76 353
e1e22e37
LT
354 packed = packed ? packed : loose;
355 while (packed) {
356 if (!strncmp(base, packed->name, trim)) {
8da19775
JH
357 retval = fn(packed->name + trim, packed->sha1,
358 packed->flag, cb_data);
8a65ff76 359 if (retval)
e1e22e37 360 return retval;
8a65ff76 361 }
e1e22e37 362 packed = packed->next;
8a65ff76 363 }
e1e22e37 364 return 0;
8a65ff76
LT
365}
366
cb5d709f 367int head_ref(each_ref_fn fn, void *cb_data)
723c31fe
LT
368{
369 unsigned char sha1[20];
8da19775
JH
370 int flag;
371
372 if (resolve_ref("HEAD", sha1, 1, &flag))
373 return fn("HEAD", sha1, flag, cb_data);
2f34ba32 374 return 0;
723c31fe
LT
375}
376
cb5d709f 377int for_each_ref(each_ref_fn fn, void *cb_data)
8a65ff76 378{
cb5d709f 379 return do_for_each_ref("refs/", fn, 0, cb_data);
a62be77f
SE
380}
381
cb5d709f 382int for_each_tag_ref(each_ref_fn fn, void *cb_data)
a62be77f 383{
cb5d709f 384 return do_for_each_ref("refs/tags/", fn, 10, cb_data);
a62be77f
SE
385}
386
cb5d709f 387int for_each_branch_ref(each_ref_fn fn, void *cb_data)
a62be77f 388{
cb5d709f 389 return do_for_each_ref("refs/heads/", fn, 11, cb_data);
a62be77f
SE
390}
391
cb5d709f 392int for_each_remote_ref(each_ref_fn fn, void *cb_data)
a62be77f 393{
cb5d709f 394 return do_for_each_ref("refs/remotes/", fn, 13, cb_data);
8a65ff76
LT
395}
396
cb5d709f
JH
397/* NEEDSWORK: This is only used by ssh-upload and it should go; the
398 * caller should do resolve_ref or read_ref like everybody else. Or
399 * maybe everybody else should use get_ref_sha1() instead of doing
400 * read_ref().
401 */
95fc7512
DB
402int get_ref_sha1(const char *ref, unsigned char *sha1)
403{
95fc7512
DB
404 if (check_ref_format(ref))
405 return -1;
ed378ec7 406 return read_ref(mkpath("refs/%s", ref), sha1);
95fc7512
DB
407}
408
03feddd6
JH
409/*
410 * Make sure "ref" is something reasonable to have under ".git/refs/";
411 * We do not like it if:
412 *
413 * - any path component of it begins with ".", or
414 * - it has double dots "..", or
415 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
416 * - it ends with a "/".
417 */
418
419static inline int bad_ref_char(int ch)
420{
421 return (((unsigned) ch) <= ' ' ||
68283999
JH
422 ch == '~' || ch == '^' || ch == ':' ||
423 /* 2.13 Pattern Matching Notation */
424 ch == '?' || ch == '*' || ch == '[');
03feddd6
JH
425}
426
95fc7512
DB
427int check_ref_format(const char *ref)
428{
03feddd6
JH
429 int ch, level;
430 const char *cp = ref;
431
432 level = 0;
433 while (1) {
434 while ((ch = *cp++) == '/')
435 ; /* tolerate duplicated slashes */
436 if (!ch)
437 return -1; /* should not end with slashes */
438
439 /* we are at the beginning of the path component */
440 if (ch == '.' || bad_ref_char(ch))
441 return -1;
442
443 /* scan the rest of the path component */
444 while ((ch = *cp++) != 0) {
445 if (bad_ref_char(ch))
446 return -1;
447 if (ch == '/')
448 break;
449 if (ch == '.' && *cp == '.')
450 return -1;
451 }
452 level++;
453 if (!ch) {
454 if (level < 2)
455 return -1; /* at least of form "heads/blah" */
456 return 0;
457 }
458 }
95fc7512
DB
459}
460
e5f38ec3 461static struct ref_lock *verify_lock(struct ref_lock *lock,
4bd18c43
SP
462 const unsigned char *old_sha1, int mustexist)
463{
8da19775 464 if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
434cd0cd 465 error("Can't verify ref %s", lock->ref_name);
4bd18c43
SP
466 unlock_ref(lock);
467 return NULL;
468 }
a89fccd2 469 if (hashcmp(lock->old_sha1, old_sha1)) {
434cd0cd 470 error("Ref %s is at %s but expected %s", lock->ref_name,
4bd18c43
SP
471 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
472 unlock_ref(lock);
473 return NULL;
474 }
475 return lock;
476}
477
bc7127ef
JH
478static int remove_empty_dir_recursive(char *path, int len)
479{
480 DIR *dir = opendir(path);
481 struct dirent *e;
482 int ret = 0;
483
484 if (!dir)
485 return -1;
486 if (path[len-1] != '/')
487 path[len++] = '/';
488 while ((e = readdir(dir)) != NULL) {
489 struct stat st;
490 int namlen;
491 if ((e->d_name[0] == '.') &&
492 ((e->d_name[1] == 0) ||
493 ((e->d_name[1] == '.') && e->d_name[2] == 0)))
494 continue; /* "." and ".." */
495
496 namlen = strlen(e->d_name);
497 if ((len + namlen < PATH_MAX) &&
498 strcpy(path + len, e->d_name) &&
499 !lstat(path, &st) &&
500 S_ISDIR(st.st_mode) &&
28bed6ea 501 !remove_empty_dir_recursive(path, len + namlen))
bc7127ef
JH
502 continue; /* happy */
503
504 /* path too long, stat fails, or non-directory still exists */
505 ret = -1;
506 break;
507 }
508 closedir(dir);
509 if (!ret) {
510 path[len] = 0;
511 ret = rmdir(path);
512 }
513 return ret;
514}
515
516static int remove_empty_directories(char *file)
517{
518 /* we want to create a file but there is a directory there;
519 * if that is an empty directory (or a directory that contains
520 * only empty directories), remove them.
521 */
522 char path[PATH_MAX];
523 int len = strlen(file);
524
525 if (len >= PATH_MAX) /* path too long ;-) */
526 return -1;
527 strcpy(path, file);
528 return remove_empty_dir_recursive(path, len);
529}
530
c0277d15 531static struct ref_lock *lock_ref_sha1_basic(const char *ref, const unsigned char *old_sha1, int *flag)
4bd18c43 532{
434cd0cd 533 char *ref_file;
ed378ec7 534 const char *orig_ref = ref;
4bd18c43 535 struct ref_lock *lock;
732232a1 536 struct stat st;
5cc3cef9 537 int last_errno = 0;
4431fcc4 538 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
4bd18c43
SP
539
540 lock = xcalloc(1, sizeof(struct ref_lock));
541 lock->lock_fd = -1;
542
c0277d15 543 ref = resolve_ref(ref, lock->old_sha1, mustexist, flag);
bc7127ef
JH
544 if (!ref && errno == EISDIR) {
545 /* we are trying to lock foo but we used to
546 * have foo/bar which now does not exist;
547 * it is normal for the empty directory 'foo'
548 * to remain.
549 */
550 ref_file = git_path("%s", orig_ref);
5cc3cef9
JH
551 if (remove_empty_directories(ref_file)) {
552 last_errno = errno;
553 error("there are still refs under '%s'", orig_ref);
554 goto error_return;
555 }
c0277d15 556 ref = resolve_ref(orig_ref, lock->old_sha1, mustexist, flag);
bc7127ef 557 }
ed378ec7 558 if (!ref) {
5cc3cef9 559 last_errno = errno;
818f477c 560 error("unable to resolve reference %s: %s",
ed378ec7 561 orig_ref, strerror(errno));
5cc3cef9 562 goto error_return;
4bd18c43 563 }
22a3844e
JH
564 if (is_null_sha1(lock->old_sha1)) {
565 /* The ref did not exist and we are creating it.
566 * Make sure there is no existing ref that is packed
567 * whose name begins with our refname, nor a ref whose
568 * name is a proper prefix of our refname.
569 */
570 int namlen = strlen(ref); /* e.g. 'foo/bar' */
571 struct ref_list *list = get_packed_refs();
572 while (list) {
573 /* list->name could be 'foo' or 'foo/bar/baz' */
574 int len = strlen(list->name);
575 int cmplen = (namlen < len) ? namlen : len;
576 const char *lead = (namlen < len) ? list->name : ref;
577
578 if (!strncmp(ref, list->name, cmplen) &&
579 lead[cmplen] == '/') {
580 error("'%s' exists; cannot create '%s'",
581 list->name, ref);
582 goto error_return;
583 }
584 list = list->next;
585 }
586 }
587
c33d5174 588 lock->lk = xcalloc(1, sizeof(struct lock_file));
4bd18c43 589
434cd0cd 590 lock->ref_name = xstrdup(ref);
ed378ec7 591 lock->log_file = xstrdup(git_path("logs/%s", ref));
7c1a278d 592 ref_file = git_path("%s", ref);
434cd0cd 593 lock->force_write = lstat(ref_file, &st) && errno == ENOENT;
4bd18c43 594
5cc3cef9
JH
595 if (safe_create_leading_directories(ref_file)) {
596 last_errno = errno;
597 error("unable to create directory for %s", ref_file);
598 goto error_return;
599 }
434cd0cd 600 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, 1);
4bd18c43
SP
601
602 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
5cc3cef9
JH
603
604 error_return:
605 unlock_ref(lock);
606 errno = last_errno;
607 return NULL;
4bd18c43
SP
608}
609
4431fcc4 610struct ref_lock *lock_ref_sha1(const char *ref, const unsigned char *old_sha1)
95fc7512 611{
53cce84c 612 char refpath[PATH_MAX];
95fc7512 613 if (check_ref_format(ref))
4bd18c43 614 return NULL;
53cce84c 615 strcpy(refpath, mkpath("refs/%s", ref));
c0277d15 616 return lock_ref_sha1_basic(refpath, old_sha1, NULL);
4bd18c43
SP
617}
618
4431fcc4 619struct ref_lock *lock_any_ref_for_update(const char *ref, const unsigned char *old_sha1)
4bd18c43 620{
c0277d15
JH
621 return lock_ref_sha1_basic(ref, old_sha1, NULL);
622}
623
624static int repack_without_ref(const char *refname)
625{
626 struct ref_list *list, *packed_ref_list;
627 int fd;
628 int found = 0;
629 struct lock_file packlock;
630
631 packed_ref_list = get_packed_refs();
632 for (list = packed_ref_list; list; list = list->next) {
633 if (!strcmp(refname, list->name)) {
634 found = 1;
635 break;
636 }
637 }
638 if (!found)
639 return 0;
640 memset(&packlock, 0, sizeof(packlock));
641 fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
642 if (fd < 0)
643 return error("cannot delete '%s' from packed refs", refname);
644
645 for (list = packed_ref_list; list; list = list->next) {
646 char line[PATH_MAX + 100];
647 int len;
648
649 if (!strcmp(refname, list->name))
650 continue;
651 len = snprintf(line, sizeof(line), "%s %s\n",
652 sha1_to_hex(list->sha1), list->name);
653 /* this should not happen but just being defensive */
654 if (len > sizeof(line))
655 die("too long a refname '%s'", list->name);
656 write_or_die(fd, line, len);
657 }
658 return commit_lock_file(&packlock);
659}
660
661int delete_ref(const char *refname, unsigned char *sha1)
662{
663 struct ref_lock *lock;
664 int err, i, ret = 0, flag = 0;
665
666 lock = lock_ref_sha1_basic(refname, sha1, &flag);
667 if (!lock)
668 return 1;
669 if (!(flag & REF_ISPACKED)) {
670 /* loose */
671 i = strlen(lock->lk->filename) - 5; /* .lock */
672 lock->lk->filename[i] = 0;
673 err = unlink(lock->lk->filename);
674 if (err) {
675 ret = 1;
676 error("unlink(%s) failed: %s",
677 lock->lk->filename, strerror(errno));
678 }
679 lock->lk->filename[i] = '.';
680 }
681 /* removing the loose one could have resurrected an earlier
682 * packed one. Also, if it was not loose we need to repack
683 * without it.
684 */
685 ret |= repack_without_ref(refname);
686
687 err = unlink(lock->log_file);
688 if (err && errno != ENOENT)
689 fprintf(stderr, "warning: unlink(%s) failed: %s",
690 lock->log_file, strerror(errno));
691 invalidate_cached_refs();
692 unlock_ref(lock);
693 return ret;
4bd18c43
SP
694}
695
e5f38ec3 696void unlock_ref(struct ref_lock *lock)
4bd18c43
SP
697{
698 if (lock->lock_fd >= 0) {
699 close(lock->lock_fd);
c33d5174
JH
700 /* Do not free lock->lk -- atexit() still looks at them */
701 if (lock->lk)
702 rollback_lock_file(lock->lk);
4bd18c43 703 }
434cd0cd 704 free(lock->ref_name);
4cac42b1 705 free(lock->log_file);
4bd18c43
SP
706 free(lock);
707}
708
6de08ae6
SP
709static int log_ref_write(struct ref_lock *lock,
710 const unsigned char *sha1, const char *msg)
711{
712 int logfd, written, oflags = O_APPEND | O_WRONLY;
713 unsigned maxlen, len;
714 char *logrec;
ff4c8485 715 const char *committer;
6de08ae6
SP
716
717 if (log_all_ref_updates) {
718 if (safe_create_leading_directories(lock->log_file) < 0)
719 return error("unable to create directory for %s",
720 lock->log_file);
721 oflags |= O_CREAT;
722 }
723
724 logfd = open(lock->log_file, oflags, 0666);
725 if (logfd < 0) {
726 if (!log_all_ref_updates && errno == ENOENT)
727 return 0;
728 return error("Unable to append to %s: %s",
729 lock->log_file, strerror(errno));
730 }
731
ff4c8485 732 committer = git_committer_info(1);
6de08ae6 733 if (msg) {
ff4c8485 734 maxlen = strlen(committer) + strlen(msg) + 2*40 + 5;
6de08ae6
SP
735 logrec = xmalloc(maxlen);
736 len = snprintf(logrec, maxlen, "%s %s %s\t%s\n",
737 sha1_to_hex(lock->old_sha1),
738 sha1_to_hex(sha1),
ff4c8485 739 committer,
6de08ae6 740 msg);
e5f38ec3
JH
741 }
742 else {
ff4c8485 743 maxlen = strlen(committer) + 2*40 + 4;
6de08ae6
SP
744 logrec = xmalloc(maxlen);
745 len = snprintf(logrec, maxlen, "%s %s %s\n",
746 sha1_to_hex(lock->old_sha1),
747 sha1_to_hex(sha1),
ff4c8485 748 committer);
6de08ae6
SP
749 }
750 written = len <= maxlen ? write(logfd, logrec, len) : -1;
751 free(logrec);
752 close(logfd);
753 if (written != len)
754 return error("Unable to append to %s", lock->log_file);
755 return 0;
756}
757
4bd18c43
SP
758int write_ref_sha1(struct ref_lock *lock,
759 const unsigned char *sha1, const char *logmsg)
760{
761 static char term = '\n';
762
763 if (!lock)
95fc7512 764 return -1;
a89fccd2 765 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
4bd18c43
SP
766 unlock_ref(lock);
767 return 0;
95fc7512 768 }
4bd18c43
SP
769 if (write(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
770 write(lock->lock_fd, &term, 1) != 1
771 || close(lock->lock_fd) < 0) {
c33d5174 772 error("Couldn't write %s", lock->lk->filename);
4bd18c43
SP
773 unlock_ref(lock);
774 return -1;
775 }
5e290ff7 776 invalidate_cached_refs();
6de08ae6
SP
777 if (log_ref_write(lock, sha1, logmsg) < 0) {
778 unlock_ref(lock);
779 return -1;
780 }
c33d5174 781 if (commit_lock_file(lock->lk)) {
434cd0cd 782 error("Couldn't set %s", lock->ref_name);
4bd18c43
SP
783 unlock_ref(lock);
784 return -1;
785 }
786 lock->lock_fd = -1;
787 unlock_ref(lock);
788 return 0;
95fc7512 789}
d556fae2
SP
790
791int read_ref_at(const char *ref, unsigned long at_time, unsigned char *sha1)
792{
e5229042 793 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
d556fae2
SP
794 char *tz_c;
795 int logfd, tz;
796 struct stat st;
797 unsigned long date;
e5229042 798 unsigned char logged_sha1[20];
d556fae2
SP
799
800 logfile = git_path("logs/%s", ref);
801 logfd = open(logfile, O_RDONLY, 0);
802 if (logfd < 0)
803 die("Unable to read log %s: %s", logfile, strerror(errno));
804 fstat(logfd, &st);
805 if (!st.st_size)
806 die("Log %s is empty.", logfile);
807 logdata = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, logfd, 0);
808 close(logfd);
809
e5229042 810 lastrec = NULL;
d556fae2
SP
811 rec = logend = logdata + st.st_size;
812 while (logdata < rec) {
813 if (logdata < rec && *(rec-1) == '\n')
814 rec--;
e5229042
SP
815 lastgt = NULL;
816 while (logdata < rec && *(rec-1) != '\n') {
d556fae2 817 rec--;
e5229042
SP
818 if (*rec == '>')
819 lastgt = rec;
820 }
821 if (!lastgt)
d556fae2 822 die("Log %s is corrupt.", logfile);
e5229042 823 date = strtoul(lastgt + 1, &tz_c, 10);
d556fae2 824 if (date <= at_time) {
e5229042
SP
825 if (lastrec) {
826 if (get_sha1_hex(lastrec, logged_sha1))
827 die("Log %s is corrupt.", logfile);
828 if (get_sha1_hex(rec + 41, sha1))
829 die("Log %s is corrupt.", logfile);
a89fccd2 830 if (hashcmp(logged_sha1, sha1)) {
e5229042
SP
831 tz = strtoul(tz_c, NULL, 10);
832 fprintf(stderr,
833 "warning: Log %s has gap after %s.\n",
834 logfile, show_rfc2822_date(date, tz));
835 }
e5f38ec3
JH
836 }
837 else if (date == at_time) {
e5229042
SP
838 if (get_sha1_hex(rec + 41, sha1))
839 die("Log %s is corrupt.", logfile);
e5f38ec3
JH
840 }
841 else {
e5229042
SP
842 if (get_sha1_hex(rec + 41, logged_sha1))
843 die("Log %s is corrupt.", logfile);
a89fccd2 844 if (hashcmp(logged_sha1, sha1)) {
e5229042
SP
845 tz = strtoul(tz_c, NULL, 10);
846 fprintf(stderr,
847 "warning: Log %s unexpectedly ended on %s.\n",
848 logfile, show_rfc2822_date(date, tz));
849 }
850 }
d556fae2
SP
851 munmap((void*)logdata, st.st_size);
852 return 0;
853 }
e5229042 854 lastrec = rec;
d556fae2
SP
855 }
856
e5229042
SP
857 rec = logdata;
858 while (rec < logend && *rec != '>' && *rec != '\n')
859 rec++;
860 if (rec == logend || *rec == '\n')
d556fae2 861 die("Log %s is corrupt.", logfile);
e5229042 862 date = strtoul(rec + 1, &tz_c, 10);
d556fae2
SP
863 tz = strtoul(tz_c, NULL, 10);
864 if (get_sha1_hex(logdata, sha1))
865 die("Log %s is corrupt.", logfile);
866 munmap((void*)logdata, st.st_size);
867 fprintf(stderr, "warning: Log %s only goes back to %s.\n",
868 logfile, show_rfc2822_date(date, tz));
869 return 0;
870}