Document git-diff whitespace flags -b and -w
[git/git.git] / refs.c
CommitLineData
95fc7512
DB
1#include "refs.h"
2#include "cache.h"
cf0adba7
JH
3#include "object.h"
4#include "tag.h"
95fc7512
DB
5
6#include <errno.h>
7
f4204ab9
JH
8/* ISSYMREF=01 and ISPACKED=02 are public interfaces */
9#define REF_KNOWS_PEELED 04
10
e1e22e37
LT
11struct ref_list {
12 struct ref_list *next;
f4204ab9 13 unsigned char flag; /* ISSYMREF? ISPACKED? */
e1e22e37 14 unsigned char sha1[20];
f4204ab9 15 unsigned char peeled[20];
e1e22e37
LT
16 char name[FLEX_ARRAY];
17};
18
f4204ab9 19static const char *parse_ref_line(char *line, unsigned char *sha1)
e1e22e37
LT
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;
f4204ab9
JH
38 if (isspace(*line))
39 return NULL;
e1e22e37
LT
40 if (line[len] != '\n')
41 return NULL;
42 line[len] = 0;
cf0adba7 43
e1e22e37
LT
44 return line;
45}
46
8da19775 47static struct ref_list *add_ref(const char *name, const unsigned char *sha1,
f4204ab9
JH
48 int flag, struct ref_list *list,
49 struct ref_list **new_entry)
e1e22e37
LT
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? */
f4204ab9
JH
61 if (!cmp) {
62 if (new_entry)
63 *new_entry = entry;
e1e22e37 64 return list;
f4204ab9 65 }
e1e22e37
LT
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);
f4204ab9 73 hashclr(entry->peeled);
e1e22e37 74 memcpy(entry->name, name, len);
8da19775 75 entry->flag = flag;
e1e22e37
LT
76 entry->next = *p;
77 *p = entry;
f4204ab9
JH
78 if (new_entry)
79 *new_entry = entry;
e1e22e37
LT
80 return list;
81}
82
5e290ff7
JH
83/*
84 * Future: need to be in "struct repository"
85 * when doing a full libification.
86 */
87struct cached_refs {
88 char did_loose;
89 char did_packed;
90 struct ref_list *loose;
91 struct ref_list *packed;
92} cached_refs;
93
94static 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
103static void invalidate_cached_refs(void)
e1e22e37 104{
5e290ff7
JH
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}
e1e22e37 114
f4204ab9
JH
115static 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
5e290ff7
JH
150static struct ref_list *get_packed_refs(void)
151{
152 if (!cached_refs.did_packed) {
e1e22e37 153 FILE *f = fopen(git_path("packed-refs"), "r");
f4204ab9 154 cached_refs.packed = NULL;
e1e22e37 155 if (f) {
f4204ab9 156 read_packed_refs(f, &cached_refs);
e1e22e37 157 fclose(f);
e1e22e37 158 }
5e290ff7 159 cached_refs.did_packed = 1;
e1e22e37 160 }
5e290ff7 161 return cached_refs.packed;
e1e22e37
LT
162}
163
164static 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);
ed378ec7 171 char *ref = xmalloc(baselen + 257);
e1e22e37 172
ed378ec7 173 memcpy(ref, base, baselen);
e1e22e37 174 if (baselen && base[baselen-1] != '/')
ed378ec7 175 ref[baselen++] = '/';
e1e22e37
LT
176
177 while ((de = readdir(dir)) != NULL) {
178 unsigned char sha1[20];
179 struct stat st;
8da19775 180 int flag;
e1e22e37
LT
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;
ed378ec7
LT
190 memcpy(ref + baselen, de->d_name, namelen+1);
191 if (stat(git_path("%s", ref), &st) < 0)
e1e22e37
LT
192 continue;
193 if (S_ISDIR(st.st_mode)) {
ed378ec7 194 list = get_ref_dir(ref, list);
e1e22e37
LT
195 continue;
196 }
8da19775 197 if (!resolve_ref(ref, sha1, 1, &flag)) {
ed378ec7 198 error("%s points nowhere!", ref);
e1e22e37
LT
199 continue;
200 }
f4204ab9 201 list = add_ref(ref, sha1, flag, list, NULL);
e1e22e37 202 }
ed378ec7 203 free(ref);
e1e22e37
LT
204 closedir(dir);
205 }
206 return list;
207}
208
209static struct ref_list *get_loose_refs(void)
210{
5e290ff7
JH
211 if (!cached_refs.did_loose) {
212 cached_refs.loose = get_ref_dir("refs", NULL);
213 cached_refs.did_loose = 1;
e1e22e37 214 }
5e290ff7 215 return cached_refs.loose;
e1e22e37
LT
216}
217
ca8db142
LT
218/* We allow "recursive" symbolic refs. Only within reason, though */
219#define MAXDEPTH 5
220
8da19775 221const char *resolve_ref(const char *ref, unsigned char *sha1, int reading, int *flag)
8a65ff76 222{
a876ed83
JH
223 int depth = MAXDEPTH, len;
224 char buffer[256];
ed378ec7 225 static char ref_buffer[256];
ca8db142 226
8da19775
JH
227 if (flag)
228 *flag = 0;
229
a876ed83 230 for (;;) {
ed378ec7 231 const char *path = git_path("%s", ref);
a876ed83
JH
232 struct stat st;
233 char *buf;
234 int fd;
8a65ff76 235
a876ed83
JH
236 if (--depth < 0)
237 return NULL;
ca8db142 238
a876ed83
JH
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) {
434cd0cd
LT
247 struct ref_list *list = get_packed_refs();
248 while (list) {
f4204ab9 249 if (!strcmp(ref, list->name)) {
434cd0cd 250 hashcpy(sha1, list->sha1);
8da19775
JH
251 if (flag)
252 *flag |= REF_ISPACKED;
434cd0cd
LT
253 return ref;
254 }
255 list = list->next;
256 }
a876ed83
JH
257 if (reading || errno != ENOENT)
258 return NULL;
e702496e 259 hashclr(sha1);
ed378ec7 260 return ref;
a876ed83 261 }
ca8db142 262
a876ed83
JH
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)) {
ed378ec7
LT
267 buffer[len] = 0;
268 strcpy(ref_buffer, buffer);
269 ref = ref_buffer;
8da19775
JH
270 if (flag)
271 *flag |= REF_ISSYMREF;
a876ed83
JH
272 continue;
273 }
ca8db142 274 }
a876ed83 275
7a21632f
DS
276 /* Is it a directory? */
277 if (S_ISDIR(st.st_mode)) {
278 errno = EISDIR;
279 return NULL;
280 }
281
a876ed83
JH
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]))
ed378ec7
LT
302 len--;
303 buf[len] = 0;
304 memcpy(ref_buffer, buf, len + 1);
305 ref = ref_buffer;
8da19775
JH
306 if (flag)
307 *flag |= REF_ISSYMREF;
8a65ff76 308 }
a876ed83
JH
309 if (len < 40 || get_sha1_hex(buffer, sha1))
310 return NULL;
ed378ec7 311 return ref;
a876ed83
JH
312}
313
ed378ec7 314int create_symref(const char *ref_target, const char *refs_heads_master)
8098a178 315{
8098a178
JH
316 const char *lockpath;
317 char ref[1000];
318 int fd, len, written;
ed378ec7 319 const char *git_HEAD = git_path("%s", ref_target);
8098a178 320
9f0bb90d
JH
321#ifndef NO_SYMLINK_HEAD
322 if (prefer_symlink_refs) {
f8348be3
JS
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 }
303958dc
JS
328#endif
329
8098a178
JH
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 }
138086a7
JH
349 if (adjust_shared_perm(git_HEAD)) {
350 unlink(lockpath);
351 error("Unable to fix permissions on %s", lockpath);
352 return -4;
353 }
8098a178 354 return 0;
8098a178
JH
355}
356
ed378ec7 357int read_ref(const char *ref, unsigned char *sha1)
a876ed83 358{
8da19775 359 if (resolve_ref(ref, sha1, 1, NULL))
a876ed83
JH
360 return 0;
361 return -1;
8a65ff76
LT
362}
363
ef06b918
JH
364static 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
cf0adba7
JH
378int 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();
cf0adba7
JH
389
390 while (list) {
f4204ab9
JH
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;
cf0adba7
JH
398 }
399 list = list->next;
400 }
cf0adba7
JH
401 }
402
f4204ab9 403 /* fallback - callers should not call this for unpacked refs */
cf0adba7
JH
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
8da19775
JH
415static int do_for_each_ref(const char *base, each_ref_fn fn, int trim,
416 void *cb_data)
8a65ff76 417{
e1e22e37
LT
418 int retval;
419 struct ref_list *packed = get_packed_refs();
420 struct ref_list *loose = get_loose_refs();
8a65ff76 421
e1e22e37
LT
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;
6cada6a9 428 }
e1e22e37
LT
429 if (cmp > 0) {
430 entry = loose;
431 loose = loose->next;
432 } else {
433 entry = packed;
434 packed = packed->next;
435 }
ef06b918 436 retval = do_one_ref(base, fn, trim, cb_data, entry);
e1e22e37
LT
437 if (retval)
438 return retval;
439 }
8a65ff76 440
ef06b918
JH
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;
8a65ff76 445 }
e1e22e37 446 return 0;
8a65ff76
LT
447}
448
cb5d709f 449int head_ref(each_ref_fn fn, void *cb_data)
723c31fe
LT
450{
451 unsigned char sha1[20];
8da19775
JH
452 int flag;
453
454 if (resolve_ref("HEAD", sha1, 1, &flag))
455 return fn("HEAD", sha1, flag, cb_data);
2f34ba32 456 return 0;
723c31fe
LT
457}
458
cb5d709f 459int for_each_ref(each_ref_fn fn, void *cb_data)
8a65ff76 460{
cb5d709f 461 return do_for_each_ref("refs/", fn, 0, cb_data);
a62be77f
SE
462}
463
cb5d709f 464int for_each_tag_ref(each_ref_fn fn, void *cb_data)
a62be77f 465{
cb5d709f 466 return do_for_each_ref("refs/tags/", fn, 10, cb_data);
a62be77f
SE
467}
468
cb5d709f 469int for_each_branch_ref(each_ref_fn fn, void *cb_data)
a62be77f 470{
cb5d709f 471 return do_for_each_ref("refs/heads/", fn, 11, cb_data);
a62be77f
SE
472}
473
cb5d709f 474int for_each_remote_ref(each_ref_fn fn, void *cb_data)
a62be77f 475{
cb5d709f 476 return do_for_each_ref("refs/remotes/", fn, 13, cb_data);
8a65ff76
LT
477}
478
cb5d709f
JH
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 */
95fc7512
DB
484int get_ref_sha1(const char *ref, unsigned char *sha1)
485{
95fc7512
DB
486 if (check_ref_format(ref))
487 return -1;
ed378ec7 488 return read_ref(mkpath("refs/%s", ref), sha1);
95fc7512
DB
489}
490
03feddd6
JH
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
501static inline int bad_ref_char(int ch)
502{
503 return (((unsigned) ch) <= ' ' ||
68283999
JH
504 ch == '~' || ch == '^' || ch == ':' ||
505 /* 2.13 Pattern Matching Notation */
506 ch == '?' || ch == '*' || ch == '[');
03feddd6
JH
507}
508
95fc7512
DB
509int check_ref_format(const char *ref)
510{
03feddd6
JH
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 }
95fc7512
DB
541}
542
e5f38ec3 543static struct ref_lock *verify_lock(struct ref_lock *lock,
4bd18c43
SP
544 const unsigned char *old_sha1, int mustexist)
545{
8da19775 546 if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
434cd0cd 547 error("Can't verify ref %s", lock->ref_name);
4bd18c43
SP
548 unlock_ref(lock);
549 return NULL;
550 }
a89fccd2 551 if (hashcmp(lock->old_sha1, old_sha1)) {
434cd0cd 552 error("Ref %s is at %s but expected %s", lock->ref_name,
4bd18c43
SP
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
bc7127ef
JH
560static 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) &&
28bed6ea 583 !remove_empty_dir_recursive(path, len + namlen))
bc7127ef
JH
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
598static 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
c0277d15 613static struct ref_lock *lock_ref_sha1_basic(const char *ref, const unsigned char *old_sha1, int *flag)
4bd18c43 614{
434cd0cd 615 char *ref_file;
ed378ec7 616 const char *orig_ref = ref;
4bd18c43 617 struct ref_lock *lock;
732232a1 618 struct stat st;
5cc3cef9 619 int last_errno = 0;
4431fcc4 620 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
4bd18c43
SP
621
622 lock = xcalloc(1, sizeof(struct ref_lock));
623 lock->lock_fd = -1;
624
c0277d15 625 ref = resolve_ref(ref, lock->old_sha1, mustexist, flag);
bc7127ef
JH
626 if (!ref && errno == EISDIR) {
627 /* we are trying to lock foo but we used to
628 * have foo/bar which now does not exist;
629 * it is normal for the empty directory 'foo'
630 * to remain.
631 */
632 ref_file = git_path("%s", orig_ref);
5cc3cef9
JH
633 if (remove_empty_directories(ref_file)) {
634 last_errno = errno;
635 error("there are still refs under '%s'", orig_ref);
636 goto error_return;
637 }
c0277d15 638 ref = resolve_ref(orig_ref, lock->old_sha1, mustexist, flag);
bc7127ef 639 }
ed378ec7 640 if (!ref) {
5cc3cef9 641 last_errno = errno;
818f477c 642 error("unable to resolve reference %s: %s",
ed378ec7 643 orig_ref, strerror(errno));
5cc3cef9 644 goto error_return;
4bd18c43 645 }
22a3844e
JH
646 if (is_null_sha1(lock->old_sha1)) {
647 /* The ref did not exist and we are creating it.
648 * Make sure there is no existing ref that is packed
649 * whose name begins with our refname, nor a ref whose
650 * name is a proper prefix of our refname.
651 */
652 int namlen = strlen(ref); /* e.g. 'foo/bar' */
653 struct ref_list *list = get_packed_refs();
654 while (list) {
655 /* list->name could be 'foo' or 'foo/bar/baz' */
656 int len = strlen(list->name);
657 int cmplen = (namlen < len) ? namlen : len;
658 const char *lead = (namlen < len) ? list->name : ref;
659
660 if (!strncmp(ref, list->name, cmplen) &&
661 lead[cmplen] == '/') {
662 error("'%s' exists; cannot create '%s'",
663 list->name, ref);
664 goto error_return;
665 }
666 list = list->next;
667 }
668 }
669
c33d5174 670 lock->lk = xcalloc(1, sizeof(struct lock_file));
4bd18c43 671
434cd0cd 672 lock->ref_name = xstrdup(ref);
ed378ec7 673 lock->log_file = xstrdup(git_path("logs/%s", ref));
7c1a278d 674 ref_file = git_path("%s", ref);
434cd0cd 675 lock->force_write = lstat(ref_file, &st) && errno == ENOENT;
4bd18c43 676
5cc3cef9
JH
677 if (safe_create_leading_directories(ref_file)) {
678 last_errno = errno;
679 error("unable to create directory for %s", ref_file);
680 goto error_return;
681 }
434cd0cd 682 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, 1);
4bd18c43
SP
683
684 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
5cc3cef9
JH
685
686 error_return:
687 unlock_ref(lock);
688 errno = last_errno;
689 return NULL;
4bd18c43
SP
690}
691
4431fcc4 692struct ref_lock *lock_ref_sha1(const char *ref, const unsigned char *old_sha1)
95fc7512 693{
53cce84c 694 char refpath[PATH_MAX];
95fc7512 695 if (check_ref_format(ref))
4bd18c43 696 return NULL;
53cce84c 697 strcpy(refpath, mkpath("refs/%s", ref));
c0277d15 698 return lock_ref_sha1_basic(refpath, old_sha1, NULL);
4bd18c43
SP
699}
700
4431fcc4 701struct ref_lock *lock_any_ref_for_update(const char *ref, const unsigned char *old_sha1)
4bd18c43 702{
c0277d15
JH
703 return lock_ref_sha1_basic(ref, old_sha1, NULL);
704}
705
26a063a1
JH
706static struct lock_file packlock;
707
c0277d15
JH
708static int repack_without_ref(const char *refname)
709{
710 struct ref_list *list, *packed_ref_list;
711 int fd;
712 int found = 0;
c0277d15
JH
713
714 packed_ref_list = get_packed_refs();
715 for (list = packed_ref_list; list; list = list->next) {
716 if (!strcmp(refname, list->name)) {
717 found = 1;
718 break;
719 }
720 }
721 if (!found)
722 return 0;
723 memset(&packlock, 0, sizeof(packlock));
724 fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
725 if (fd < 0)
726 return error("cannot delete '%s' from packed refs", refname);
727
728 for (list = packed_ref_list; list; list = list->next) {
729 char line[PATH_MAX + 100];
730 int len;
731
732 if (!strcmp(refname, list->name))
733 continue;
734 len = snprintf(line, sizeof(line), "%s %s\n",
735 sha1_to_hex(list->sha1), list->name);
736 /* this should not happen but just being defensive */
737 if (len > sizeof(line))
738 die("too long a refname '%s'", list->name);
739 write_or_die(fd, line, len);
740 }
741 return commit_lock_file(&packlock);
742}
743
744int delete_ref(const char *refname, unsigned char *sha1)
745{
746 struct ref_lock *lock;
747 int err, i, ret = 0, flag = 0;
748
749 lock = lock_ref_sha1_basic(refname, sha1, &flag);
750 if (!lock)
751 return 1;
752 if (!(flag & REF_ISPACKED)) {
753 /* loose */
754 i = strlen(lock->lk->filename) - 5; /* .lock */
755 lock->lk->filename[i] = 0;
756 err = unlink(lock->lk->filename);
757 if (err) {
758 ret = 1;
759 error("unlink(%s) failed: %s",
760 lock->lk->filename, strerror(errno));
761 }
762 lock->lk->filename[i] = '.';
763 }
764 /* removing the loose one could have resurrected an earlier
765 * packed one. Also, if it was not loose we need to repack
766 * without it.
767 */
768 ret |= repack_without_ref(refname);
769
770 err = unlink(lock->log_file);
771 if (err && errno != ENOENT)
772 fprintf(stderr, "warning: unlink(%s) failed: %s",
773 lock->log_file, strerror(errno));
774 invalidate_cached_refs();
775 unlock_ref(lock);
776 return ret;
4bd18c43
SP
777}
778
e5f38ec3 779void unlock_ref(struct ref_lock *lock)
4bd18c43
SP
780{
781 if (lock->lock_fd >= 0) {
782 close(lock->lock_fd);
c33d5174
JH
783 /* Do not free lock->lk -- atexit() still looks at them */
784 if (lock->lk)
785 rollback_lock_file(lock->lk);
4bd18c43 786 }
434cd0cd 787 free(lock->ref_name);
4cac42b1 788 free(lock->log_file);
4bd18c43
SP
789 free(lock);
790}
791
6de08ae6
SP
792static int log_ref_write(struct ref_lock *lock,
793 const unsigned char *sha1, const char *msg)
794{
795 int logfd, written, oflags = O_APPEND | O_WRONLY;
796 unsigned maxlen, len;
797 char *logrec;
ff4c8485 798 const char *committer;
6de08ae6 799
4057deb5
JH
800 if (log_all_ref_updates &&
801 !strncmp(lock->ref_name, "refs/heads/", 11)) {
6de08ae6
SP
802 if (safe_create_leading_directories(lock->log_file) < 0)
803 return error("unable to create directory for %s",
804 lock->log_file);
805 oflags |= O_CREAT;
806 }
807
808 logfd = open(lock->log_file, oflags, 0666);
809 if (logfd < 0) {
1974bf62 810 if (!(oflags & O_CREAT) && errno == ENOENT)
6de08ae6 811 return 0;
3b463c3f
JH
812
813 if ((oflags & O_CREAT) && errno == EISDIR) {
814 if (remove_empty_directories(lock->log_file)) {
815 return error("There are still logs under '%s'",
816 lock->log_file);
817 }
818 logfd = open(lock->log_file, oflags, 0666);
819 }
820
821 if (logfd < 0)
822 return error("Unable to append to %s: %s",
823 lock->log_file, strerror(errno));
6de08ae6
SP
824 }
825
ff4c8485 826 committer = git_committer_info(1);
6de08ae6 827 if (msg) {
ff4c8485 828 maxlen = strlen(committer) + strlen(msg) + 2*40 + 5;
6de08ae6
SP
829 logrec = xmalloc(maxlen);
830 len = snprintf(logrec, maxlen, "%s %s %s\t%s\n",
831 sha1_to_hex(lock->old_sha1),
832 sha1_to_hex(sha1),
ff4c8485 833 committer,
6de08ae6 834 msg);
e5f38ec3
JH
835 }
836 else {
ff4c8485 837 maxlen = strlen(committer) + 2*40 + 4;
6de08ae6
SP
838 logrec = xmalloc(maxlen);
839 len = snprintf(logrec, maxlen, "%s %s %s\n",
840 sha1_to_hex(lock->old_sha1),
841 sha1_to_hex(sha1),
ff4c8485 842 committer);
6de08ae6
SP
843 }
844 written = len <= maxlen ? write(logfd, logrec, len) : -1;
845 free(logrec);
846 close(logfd);
847 if (written != len)
848 return error("Unable to append to %s", lock->log_file);
849 return 0;
850}
851
4bd18c43
SP
852int write_ref_sha1(struct ref_lock *lock,
853 const unsigned char *sha1, const char *logmsg)
854{
855 static char term = '\n';
856
857 if (!lock)
95fc7512 858 return -1;
a89fccd2 859 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
4bd18c43
SP
860 unlock_ref(lock);
861 return 0;
95fc7512 862 }
4bd18c43
SP
863 if (write(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
864 write(lock->lock_fd, &term, 1) != 1
865 || close(lock->lock_fd) < 0) {
c33d5174 866 error("Couldn't write %s", lock->lk->filename);
4bd18c43
SP
867 unlock_ref(lock);
868 return -1;
869 }
5e290ff7 870 invalidate_cached_refs();
6de08ae6
SP
871 if (log_ref_write(lock, sha1, logmsg) < 0) {
872 unlock_ref(lock);
873 return -1;
874 }
c33d5174 875 if (commit_lock_file(lock->lk)) {
434cd0cd 876 error("Couldn't set %s", lock->ref_name);
4bd18c43
SP
877 unlock_ref(lock);
878 return -1;
879 }
880 lock->lock_fd = -1;
881 unlock_ref(lock);
882 return 0;
95fc7512 883}
d556fae2 884
ab2a1a32 885int read_ref_at(const char *ref, unsigned long at_time, int cnt, unsigned char *sha1)
d556fae2 886{
e5229042 887 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
d556fae2
SP
888 char *tz_c;
889 int logfd, tz;
890 struct stat st;
891 unsigned long date;
e5229042 892 unsigned char logged_sha1[20];
d556fae2
SP
893
894 logfile = git_path("logs/%s", ref);
895 logfd = open(logfile, O_RDONLY, 0);
896 if (logfd < 0)
897 die("Unable to read log %s: %s", logfile, strerror(errno));
898 fstat(logfd, &st);
899 if (!st.st_size)
900 die("Log %s is empty.", logfile);
901 logdata = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, logfd, 0);
902 close(logfd);
903
e5229042 904 lastrec = NULL;
d556fae2
SP
905 rec = logend = logdata + st.st_size;
906 while (logdata < rec) {
907 if (logdata < rec && *(rec-1) == '\n')
908 rec--;
e5229042
SP
909 lastgt = NULL;
910 while (logdata < rec && *(rec-1) != '\n') {
d556fae2 911 rec--;
e5229042
SP
912 if (*rec == '>')
913 lastgt = rec;
914 }
915 if (!lastgt)
d556fae2 916 die("Log %s is corrupt.", logfile);
e5229042 917 date = strtoul(lastgt + 1, &tz_c, 10);
ab2a1a32 918 if (date <= at_time || cnt == 0) {
e5229042
SP
919 if (lastrec) {
920 if (get_sha1_hex(lastrec, logged_sha1))
921 die("Log %s is corrupt.", logfile);
922 if (get_sha1_hex(rec + 41, sha1))
923 die("Log %s is corrupt.", logfile);
a89fccd2 924 if (hashcmp(logged_sha1, sha1)) {
e5229042
SP
925 tz = strtoul(tz_c, NULL, 10);
926 fprintf(stderr,
927 "warning: Log %s has gap after %s.\n",
928 logfile, show_rfc2822_date(date, tz));
929 }
e5f38ec3
JH
930 }
931 else if (date == at_time) {
e5229042
SP
932 if (get_sha1_hex(rec + 41, sha1))
933 die("Log %s is corrupt.", logfile);
e5f38ec3
JH
934 }
935 else {
e5229042
SP
936 if (get_sha1_hex(rec + 41, logged_sha1))
937 die("Log %s is corrupt.", logfile);
a89fccd2 938 if (hashcmp(logged_sha1, sha1)) {
e5229042
SP
939 tz = strtoul(tz_c, NULL, 10);
940 fprintf(stderr,
941 "warning: Log %s unexpectedly ended on %s.\n",
942 logfile, show_rfc2822_date(date, tz));
943 }
944 }
d556fae2
SP
945 munmap((void*)logdata, st.st_size);
946 return 0;
947 }
e5229042 948 lastrec = rec;
ab2a1a32
JH
949 if (cnt > 0)
950 cnt--;
d556fae2
SP
951 }
952
e5229042
SP
953 rec = logdata;
954 while (rec < logend && *rec != '>' && *rec != '\n')
955 rec++;
956 if (rec == logend || *rec == '\n')
d556fae2 957 die("Log %s is corrupt.", logfile);
e5229042 958 date = strtoul(rec + 1, &tz_c, 10);
d556fae2
SP
959 tz = strtoul(tz_c, NULL, 10);
960 if (get_sha1_hex(logdata, sha1))
961 die("Log %s is corrupt.", logfile);
962 munmap((void*)logdata, st.st_size);
963 fprintf(stderr, "warning: Log %s only goes back to %s.\n",
964 logfile, show_rfc2822_date(date, tz));
965 return 0;
966}