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