reflog-walk: convert struct reflog_info to struct object_id
[git/git.git] / refs.c
CommitLineData
7bd9bcf3
MH
1/*
2 * The backend-independent part of the reference module.
3 */
4
95fc7512 5#include "cache.h"
697cc8ef 6#include "lockfile.h"
85023577 7#include "refs.h"
4cb77009 8#include "refs/refs-internal.h"
cf0adba7
JH
9#include "object.h"
10#include "tag.h"
3581d793 11
3dce444f
RS
12/*
13 * List of all available backends
14 */
15static struct ref_storage_be *refs_backends = &refs_be_files;
16
17static struct ref_storage_be *find_ref_storage_backend(const char *name)
18{
19 struct ref_storage_be *be;
20 for (be = refs_backends; be; be = be->next)
21 if (!strcmp(be->name, name))
22 return be;
23 return NULL;
24}
25
26int ref_storage_backend_exists(const char *name)
27{
28 return find_ref_storage_backend(name) != NULL;
29}
30
bc5fd6d3 31/*
dde8a902
DT
32 * How to handle various characters in refnames:
33 * 0: An acceptable character for refs
5e650228
JH
34 * 1: End-of-component
35 * 2: ., look for a preceding . to reject .. in refs
36 * 3: {, look for a preceding @ to reject @{ in refs
53a8555e 37 * 4: A bad character: ASCII control characters, and
cd377f45
JK
38 * ":", "?", "[", "\", "^", "~", SP, or TAB
39 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
dde8a902
DT
40 */
41static unsigned char refname_disposition[256] = {
5e650228
JH
42 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
43 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
cd377f45 44 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
5e650228 45 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
dde8a902 46 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5e650228
JH
47 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
48 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
49 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
dde8a902
DT
50};
51
52/*
53 * Try to read one refname component from the front of refname.
54 * Return the length of the component found, or -1 if the component is
55 * not legal. It is legal if it is something reasonable to have under
56 * ".git/refs/"; We do not like it if:
bc5fd6d3
MH
57 *
58 * - any path component of it begins with ".", or
59 * - it has double dots "..", or
53a8555e 60 * - it has ASCII control characters, or
cd377f45
JK
61 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
62 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
53a8555e
JK
63 * - it ends with a "/", or
64 * - it ends with ".lock", or
65 * - it contains a "@{" portion
bc5fd6d3 66 */
cd377f45 67static int check_refname_component(const char *refname, int *flags)
bc5fd6d3
MH
68{
69 const char *cp;
70 char last = '\0';
71
72 for (cp = refname; ; cp++) {
dde8a902
DT
73 int ch = *cp & 255;
74 unsigned char disp = refname_disposition[ch];
75 switch (disp) {
5e650228 76 case 1:
dde8a902 77 goto out;
5e650228 78 case 2:
dde8a902
DT
79 if (last == '.')
80 return -1; /* Refname contains "..". */
81 break;
5e650228 82 case 3:
dde8a902
DT
83 if (last == '@')
84 return -1; /* Refname contains "@{". */
bc5fd6d3 85 break;
5e650228 86 case 4:
dde8a902 87 return -1;
cd377f45
JK
88 case 5:
89 if (!(*flags & REFNAME_REFSPEC_PATTERN))
90 return -1; /* refspec can't be a pattern */
91
92 /*
93 * Unset the pattern flag so that we only accept
94 * a single asterisk for one side of refspec.
95 */
96 *flags &= ~ REFNAME_REFSPEC_PATTERN;
97 break;
dde8a902 98 }
bc5fd6d3
MH
99 last = ch;
100 }
dde8a902 101out:
bc5fd6d3 102 if (cp == refname)
dac529e4 103 return 0; /* Component has zero length. */
f3cc52d8
JN
104 if (refname[0] == '.')
105 return -1; /* Component starts with '.'. */
7108ad23
MH
106 if (cp - refname >= LOCK_SUFFIX_LEN &&
107 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
bc5fd6d3
MH
108 return -1; /* Refname ends with ".lock". */
109 return cp - refname;
110}
111
5e650228 112int check_refname_format(const char *refname, int flags)
bc5fd6d3
MH
113{
114 int component_len, component_count = 0;
115
9ba89f48
FC
116 if (!strcmp(refname, "@"))
117 /* Refname is a single character '@'. */
118 return -1;
119
bc5fd6d3
MH
120 while (1) {
121 /* We are at the start of a path component. */
cd377f45
JK
122 component_len = check_refname_component(refname, &flags);
123 if (component_len <= 0)
124 return -1;
125
bc5fd6d3
MH
126 component_count++;
127 if (refname[component_len] == '\0')
128 break;
129 /* Skip to next component. */
130 refname += component_len + 1;
131 }
132
133 if (refname[component_len - 1] == '.')
134 return -1; /* Refname ends with '.'. */
135 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
136 return -1; /* Refname has only one component. */
137 return 0;
138}
139
4cb77009 140int refname_is_safe(const char *refname)
d0f810f0 141{
39950fef
MH
142 const char *rest;
143
144 if (skip_prefix(refname, "refs/", &rest)) {
d0f810f0
RS
145 char *buf;
146 int result;
e40f3557
MH
147 size_t restlen = strlen(rest);
148
149 /* rest must not be empty, or start or end with "/" */
150 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
151 return 0;
d0f810f0 152
d0f810f0
RS
153 /*
154 * Does the refname try to escape refs/?
155 * For example: refs/foo/../bar is safe but refs/foo/../../bar
156 * is not.
157 */
e40f3557
MH
158 buf = xmallocz(restlen);
159 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
d0f810f0
RS
160 free(buf);
161 return result;
162 }
35db25c6
MH
163
164 do {
d0f810f0
RS
165 if (!isupper(*refname) && *refname != '_')
166 return 0;
167 refname++;
35db25c6 168 } while (*refname);
d0f810f0
RS
169 return 1;
170}
171
7bd9bcf3
MH
172char *resolve_refdup(const char *refname, int resolve_flags,
173 unsigned char *sha1, int *flags)
e1e22e37 174{
7bd9bcf3
MH
175 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
176 sha1, flags));
cddc4258
MH
177}
178
7bd9bcf3
MH
179/* The argument to filter_refs */
180struct ref_filter {
181 const char *pattern;
182 each_ref_fn *fn;
183 void *cb_data;
184};
432ad41e 185
7bd9bcf3 186int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
732134ed 187{
7bd9bcf3
MH
188 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
189 return 0;
190 return -1;
732134ed
MH
191}
192
7bd9bcf3 193int read_ref(const char *refname, unsigned char *sha1)
cddc4258 194{
7bd9bcf3 195 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
c774aab9
JP
196}
197
7bd9bcf3 198int ref_exists(const char *refname)
bc5fd6d3 199{
7bd9bcf3
MH
200 unsigned char sha1[20];
201 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
bc5fd6d3
MH
202}
203
7bd9bcf3
MH
204static int filter_refs(const char *refname, const struct object_id *oid,
205 int flags, void *data)
432ad41e 206{
7bd9bcf3
MH
207 struct ref_filter *filter = (struct ref_filter *)data;
208
209 if (wildmatch(filter->pattern, refname, 0, NULL))
210 return 0;
211 return filter->fn(refname, oid, flags, filter->cb_data);
432ad41e
MH
212}
213
7bd9bcf3 214enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
c774aab9 215{
7bd9bcf3 216 struct object *o = lookup_unknown_object(name);
c774aab9 217
7bd9bcf3
MH
218 if (o->type == OBJ_NONE) {
219 int type = sha1_object_info(name, NULL);
220 if (type < 0 || !object_as_type(o, type, 0))
221 return PEEL_INVALID;
222 }
bc5fd6d3 223
7bd9bcf3
MH
224 if (o->type != OBJ_TAG)
225 return PEEL_NON_TAG;
e1980c9d 226
7bd9bcf3
MH
227 o = deref_tag_noverify(o);
228 if (!o)
229 return PEEL_INVALID;
230
844a9ce4 231 hashcpy(sha1, o->oid.hash);
7bd9bcf3 232 return PEEL_PEELED;
e1980c9d
JH
233}
234
7bd9bcf3
MH
235struct warn_if_dangling_data {
236 FILE *fp;
237 const char *refname;
238 const struct string_list *refnames;
239 const char *msg_fmt;
240};
bc5fd6d3 241
7bd9bcf3
MH
242static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
243 int flags, void *cb_data)
244{
245 struct warn_if_dangling_data *d = cb_data;
246 const char *resolves_to;
247 struct object_id junk;
bc5fd6d3 248
7bd9bcf3
MH
249 if (!(flags & REF_ISSYMREF))
250 return 0;
bc5fd6d3 251
7bd9bcf3
MH
252 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
253 if (!resolves_to
254 || (d->refname
255 ? strcmp(resolves_to, d->refname)
256 : !string_list_has_string(d->refnames, resolves_to))) {
257 return 0;
258 }
bc5fd6d3 259
7bd9bcf3
MH
260 fprintf(d->fp, d->msg_fmt, refname);
261 fputc('\n', d->fp);
262 return 0;
bc5fd6d3
MH
263}
264
7bd9bcf3 265void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
f348ac92 266{
7bd9bcf3
MH
267 struct warn_if_dangling_data data;
268
269 data.fp = fp;
270 data.refname = refname;
271 data.refnames = NULL;
272 data.msg_fmt = msg_fmt;
273 for_each_rawref(warn_if_dangling_symref, &data);
f348ac92
MH
274}
275
7bd9bcf3 276void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
432ad41e 277{
7bd9bcf3 278 struct warn_if_dangling_data data;
432ad41e 279
7bd9bcf3
MH
280 data.fp = fp;
281 data.refname = NULL;
282 data.refnames = refnames;
283 data.msg_fmt = msg_fmt;
284 for_each_rawref(warn_if_dangling_symref, &data);
432ad41e
MH
285}
286
7bd9bcf3 287int for_each_tag_ref(each_ref_fn fn, void *cb_data)
432ad41e 288{
7bd9bcf3 289 return for_each_ref_in("refs/tags/", fn, cb_data);
432ad41e
MH
290}
291
7bd9bcf3 292int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
506a760d 293{
7bd9bcf3 294 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
432ad41e
MH
295}
296
7bd9bcf3 297int for_each_branch_ref(each_ref_fn fn, void *cb_data)
432ad41e 298{
7bd9bcf3 299 return for_each_ref_in("refs/heads/", fn, cb_data);
432ad41e
MH
300}
301
7bd9bcf3 302int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
202a56a9 303{
7bd9bcf3 304 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
202a56a9 305}
432ad41e 306
7bd9bcf3 307int for_each_remote_ref(each_ref_fn fn, void *cb_data)
e9c4c111 308{
7bd9bcf3 309 return for_each_ref_in("refs/remotes/", fn, cb_data);
202a56a9
MH
310}
311
7bd9bcf3 312int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
e9c4c111 313{
7bd9bcf3 314 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
662428f4 315}
c774aab9 316
7bd9bcf3
MH
317int head_ref_namespaced(each_ref_fn fn, void *cb_data)
318{
319 struct strbuf buf = STRBUF_INIT;
320 int ret = 0;
321 struct object_id oid;
322 int flag;
c774aab9 323
7bd9bcf3
MH
324 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
325 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
326 ret = fn(buf.buf, &oid, flag, cb_data);
327 strbuf_release(&buf);
c774aab9 328
7bd9bcf3 329 return ret;
e9c4c111 330}
c774aab9 331
7bd9bcf3
MH
332int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
333 const char *prefix, void *cb_data)
662428f4 334{
7bd9bcf3
MH
335 struct strbuf real_pattern = STRBUF_INIT;
336 struct ref_filter filter;
337 int ret;
d08bae7e 338
59556548 339 if (!prefix && !starts_with(pattern, "refs/"))
d08bae7e 340 strbuf_addstr(&real_pattern, "refs/");
b09fe971
IL
341 else if (prefix)
342 strbuf_addstr(&real_pattern, prefix);
d08bae7e
IL
343 strbuf_addstr(&real_pattern, pattern);
344
894a9d33 345 if (!has_glob_specials(pattern)) {
9517e6b8 346 /* Append implied '/' '*' if not present. */
00b6c178 347 strbuf_complete(&real_pattern, '/');
d08bae7e
IL
348 /* No need to check for '*', there is none. */
349 strbuf_addch(&real_pattern, '*');
350 }
351
352 filter.pattern = real_pattern.buf;
353 filter.fn = fn;
354 filter.cb_data = cb_data;
355 ret = for_each_ref(filter_refs, &filter);
356
357 strbuf_release(&real_pattern);
358 return ret;
359}
360
b09fe971
IL
361int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
362{
363 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
364}
365
4577e483 366const char *prettify_refname(const char *name)
a9c37a72 367{
a9c37a72 368 return name + (
59556548
CC
369 starts_with(name, "refs/heads/") ? 11 :
370 starts_with(name, "refs/tags/") ? 10 :
371 starts_with(name, "refs/remotes/") ? 13 :
a9c37a72
DB
372 0);
373}
374
54457fe5 375static const char *ref_rev_parse_rules[] = {
79803322
SP
376 "%.*s",
377 "refs/%.*s",
378 "refs/tags/%.*s",
379 "refs/heads/%.*s",
380 "refs/remotes/%.*s",
381 "refs/remotes/%.*s/HEAD",
382 NULL
383};
384
54457fe5 385int refname_match(const char *abbrev_name, const char *full_name)
79803322
SP
386{
387 const char **p;
388 const int abbrev_name_len = strlen(abbrev_name);
389
54457fe5 390 for (p = ref_rev_parse_rules; *p; p++) {
79803322
SP
391 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
392 return 1;
393 }
394 }
395
396 return 0;
397}
398
ff74f7f1
JH
399/*
400 * *string and *len will only be substituted, and *string returned (for
401 * later free()ing) if the string passed in is a magic short-hand form
402 * to name a branch.
403 */
404static char *substitute_branch_name(const char **string, int *len)
405{
406 struct strbuf buf = STRBUF_INIT;
cf99a761 407 int ret = interpret_branch_name(*string, *len, &buf);
ff74f7f1
JH
408
409 if (ret == *len) {
410 size_t size;
411 *string = strbuf_detach(&buf, &size);
412 *len = size;
413 return (char *)*string;
414 }
415
416 return NULL;
417}
418
419int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
420{
421 char *last_branch = substitute_branch_name(&str, &len);
41da7111
NTND
422 int refs_found = expand_ref(str, len, sha1, ref);
423 free(last_branch);
424 return refs_found;
425}
426
427int expand_ref(const char *str, int len, unsigned char *sha1, char **ref)
428{
ff74f7f1
JH
429 const char **p, *r;
430 int refs_found = 0;
431
432 *ref = NULL;
433 for (p = ref_rev_parse_rules; *p; p++) {
434 char fullref[PATH_MAX];
435 unsigned char sha1_from_ref[20];
436 unsigned char *this_result;
437 int flag;
438
439 this_result = refs_found ? sha1_from_ref : sha1;
440 mksnpath(fullref, sizeof(fullref), *p, len, str);
7695d118
RS
441 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
442 this_result, &flag);
ff74f7f1
JH
443 if (r) {
444 if (!refs_found++)
445 *ref = xstrdup(r);
446 if (!warn_ambiguous_refs)
447 break;
55956350 448 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
ff74f7f1 449 warning("ignoring dangling symref %s.", fullref);
55956350
JH
450 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
451 warning("ignoring broken ref %s.", fullref);
452 }
ff74f7f1 453 }
ff74f7f1
JH
454 return refs_found;
455}
456
457int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
458{
459 char *last_branch = substitute_branch_name(&str, &len);
460 const char **p;
461 int logs_found = 0;
462
463 *log = NULL;
464 for (p = ref_rev_parse_rules; *p; p++) {
ff74f7f1
JH
465 unsigned char hash[20];
466 char path[PATH_MAX];
467 const char *ref, *it;
468
469 mksnpath(path, sizeof(path), *p, len, str);
7695d118
RS
470 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
471 hash, NULL);
ff74f7f1
JH
472 if (!ref)
473 continue;
4da58835 474 if (reflog_exists(path))
ff74f7f1 475 it = path;
4da58835 476 else if (strcmp(ref, path) && reflog_exists(ref))
ff74f7f1
JH
477 it = ref;
478 else
479 continue;
480 if (!logs_found++) {
481 *log = xstrdup(it);
482 hashcpy(sha1, hash);
483 }
7bd9bcf3
MH
484 if (!warn_ambiguous_refs)
485 break;
c0277d15 486 }
7bd9bcf3
MH
487 free(last_branch);
488 return logs_found;
2ddb5d17
BK
489}
490
266b1827
DT
491static int is_per_worktree_ref(const char *refname)
492{
ce414b33
DT
493 return !strcmp(refname, "HEAD") ||
494 starts_with(refname, "refs/bisect/");
266b1827
DT
495}
496
497static int is_pseudoref_syntax(const char *refname)
498{
499 const char *c;
500
501 for (c = refname; *c; c++) {
502 if (!isupper(*c) && *c != '-' && *c != '_')
503 return 0;
504 }
505
506 return 1;
507}
508
509enum ref_type ref_type(const char *refname)
510{
511 if (is_per_worktree_ref(refname))
512 return REF_TYPE_PER_WORKTREE;
513 if (is_pseudoref_syntax(refname))
514 return REF_TYPE_PSEUDOREF;
515 return REF_TYPE_NORMAL;
516}
517
74ec19d4
DT
518static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
519 const unsigned char *old_sha1, struct strbuf *err)
520{
521 const char *filename;
522 int fd;
523 static struct lock_file lock;
524 struct strbuf buf = STRBUF_INIT;
525 int ret = -1;
526
527 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
528
529 filename = git_path("%s", pseudoref);
530 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
531 if (fd < 0) {
0568c8e9 532 strbuf_addf(err, "could not open '%s' for writing: %s",
74ec19d4
DT
533 filename, strerror(errno));
534 return -1;
535 }
536
537 if (old_sha1) {
538 unsigned char actual_old_sha1[20];
2c3aed13
DT
539
540 if (read_ref(pseudoref, actual_old_sha1))
541 die("could not read ref '%s'", pseudoref);
74ec19d4 542 if (hashcmp(actual_old_sha1, old_sha1)) {
0568c8e9 543 strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
74ec19d4
DT
544 rollback_lock_file(&lock);
545 goto done;
546 }
547 }
548
549 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
0568c8e9 550 strbuf_addf(err, "could not write to '%s'", filename);
74ec19d4
DT
551 rollback_lock_file(&lock);
552 goto done;
553 }
554
555 commit_lock_file(&lock);
556 ret = 0;
557done:
558 strbuf_release(&buf);
559 return ret;
560}
561
562static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
563{
564 static struct lock_file lock;
565 const char *filename;
566
567 filename = git_path("%s", pseudoref);
568
569 if (old_sha1 && !is_null_sha1(old_sha1)) {
570 int fd;
571 unsigned char actual_old_sha1[20];
572
573 fd = hold_lock_file_for_update(&lock, filename,
574 LOCK_DIE_ON_ERROR);
575 if (fd < 0)
576 die_errno(_("Could not open '%s' for writing"), filename);
2c3aed13
DT
577 if (read_ref(pseudoref, actual_old_sha1))
578 die("could not read ref '%s'", pseudoref);
74ec19d4
DT
579 if (hashcmp(actual_old_sha1, old_sha1)) {
580 warning("Unexpected sha1 when deleting %s", pseudoref);
581 rollback_lock_file(&lock);
582 return -1;
a4c653df 583 }
74ec19d4
DT
584
585 unlink(filename);
586 rollback_lock_file(&lock);
587 } else {
588 unlink(filename);
4bd18c43 589 }
a4c653df 590
4bd18c43 591 return 0;
95fc7512 592}
d556fae2 593
fc1c2168
MH
594int delete_ref(const char *refname, const unsigned char *old_sha1,
595 unsigned int flags)
41b625b0 596{
7521cc46 597 struct ref_transaction *transaction;
a4c653df 598 struct strbuf err = STRBUF_INIT;
8b5157e4 599
74ec19d4 600 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
080cc646 601 return delete_pseudoref(refname, old_sha1);
d48744d1 602
7521cc46
RS
603 transaction = ref_transaction_begin(&err);
604 if (!transaction ||
fc67a082 605 ref_transaction_delete(transaction, refname, old_sha1,
fb5a6bb6 606 flags, NULL, &err) ||
db7516ab 607 ref_transaction_commit(transaction, &err)) {
7521cc46
RS
608 error("%s", err.buf);
609 ref_transaction_free(transaction);
610 strbuf_release(&err);
c0277d15 611 return 1;
41b625b0 612 }
7bd9bcf3
MH
613 ref_transaction_free(transaction);
614 strbuf_release(&err);
b531394d
BC
615 return 0;
616}
41b625b0 617
4cb77009 618int copy_reflog_msg(char *buf, const char *msg)
0ec29a47
JH
619{
620 char *cp = buf;
621 char c;
622 int wasspace = 1;
8b5157e4 623
0ec29a47
JH
624 *cp++ = '\t';
625 while ((c = *msg++)) {
626 if (wasspace && isspace(c))
627 continue;
628 wasspace = isspace(c);
629 if (wasspace)
630 c = ' ';
631 *cp++ = c;
a4c653df 632 }
0ec29a47
JH
633 while (buf < cp && isspace(cp[-1]))
634 cp--;
635 *cp++ = '\n';
636 return cp - buf;
637}
8b5157e4 638
4cb77009 639int should_autocreate_reflog(const char *refname)
4e2bef57 640{
341fb286
CW
641 switch (log_all_ref_updates) {
642 case LOG_REFS_ALWAYS:
643 return 1;
644 case LOG_REFS_NORMAL:
645 return starts_with(refname, "refs/heads/") ||
646 starts_with(refname, "refs/remotes/") ||
647 starts_with(refname, "refs/notes/") ||
648 !strcmp(refname, "HEAD");
649 default:
4e2bef57 650 return 0;
341fb286 651 }
4e2bef57
DT
652}
653
e7e0f26e 654int is_branch(const char *refname)
c3b0dec5 655{
59556548 656 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
41b625b0
NP
657}
658
4207ed28
RS
659struct read_ref_at_cb {
660 const char *refname;
661 unsigned long at_time;
662 int cnt;
663 int reccnt;
664 unsigned char *sha1;
665 int found_it;
666
667 unsigned char osha1[20];
668 unsigned char nsha1[20];
669 int tz;
670 unsigned long date;
671 char **msg;
672 unsigned long *cutoff_time;
673 int *cutoff_tz;
674 int *cutoff_cnt;
675};
676
677static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
678 const char *email, unsigned long timestamp, int tz,
679 const char *message, void *cb_data)
680{
681 struct read_ref_at_cb *cb = cb_data;
682
683 cb->reccnt++;
684 cb->tz = tz;
685 cb->date = timestamp;
686
687 if (timestamp <= cb->at_time || cb->cnt == 0) {
688 if (cb->msg)
689 *cb->msg = xstrdup(message);
690 if (cb->cutoff_time)
691 *cb->cutoff_time = timestamp;
692 if (cb->cutoff_tz)
693 *cb->cutoff_tz = tz;
694 if (cb->cutoff_cnt)
695 *cb->cutoff_cnt = cb->reccnt - 1;
696 /*
697 * we have not yet updated cb->[n|o]sha1 so they still
698 * hold the values for the previous record.
699 */
700 if (!is_null_sha1(cb->osha1)) {
701 hashcpy(cb->sha1, nsha1);
702 if (hashcmp(cb->osha1, nsha1))
703 warning("Log for ref %s has gap after %s.",
a5481a6c 704 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
4207ed28
RS
705 }
706 else if (cb->date == cb->at_time)
707 hashcpy(cb->sha1, nsha1);
708 else if (hashcmp(nsha1, cb->sha1))
709 warning("Log for ref %s unexpectedly ended on %s.",
710 cb->refname, show_date(cb->date, cb->tz,
a5481a6c 711 DATE_MODE(RFC2822)));
4207ed28
RS
712 hashcpy(cb->osha1, osha1);
713 hashcpy(cb->nsha1, nsha1);
714 cb->found_it = 1;
715 return 1;
716 }
717 hashcpy(cb->osha1, osha1);
718 hashcpy(cb->nsha1, nsha1);
719 if (cb->cnt > 0)
720 cb->cnt--;
721 return 0;
722}
723
724static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
725 const char *email, unsigned long timestamp,
726 int tz, const char *message, void *cb_data)
727{
728 struct read_ref_at_cb *cb = cb_data;
729
730 if (cb->msg)
731 *cb->msg = xstrdup(message);
732 if (cb->cutoff_time)
733 *cb->cutoff_time = timestamp;
734 if (cb->cutoff_tz)
735 *cb->cutoff_tz = tz;
736 if (cb->cutoff_cnt)
737 *cb->cutoff_cnt = cb->reccnt;
738 hashcpy(cb->sha1, osha1);
739 if (is_null_sha1(cb->sha1))
740 hashcpy(cb->sha1, nsha1);
741 /* We just want the first entry */
742 return 1;
16d7cc90
JH
743}
744
c41a87dd 745int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
dfefa935
MH
746 unsigned char *sha1, char **msg,
747 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
d556fae2 748{
4207ed28 749 struct read_ref_at_cb cb;
d556fae2 750
4207ed28
RS
751 memset(&cb, 0, sizeof(cb));
752 cb.refname = refname;
753 cb.at_time = at_time;
754 cb.cnt = cnt;
755 cb.msg = msg;
756 cb.cutoff_time = cutoff_time;
757 cb.cutoff_tz = cutoff_tz;
758 cb.cutoff_cnt = cutoff_cnt;
759 cb.sha1 = sha1;
760
761 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
762
c41a87dd
DA
763 if (!cb.reccnt) {
764 if (flags & GET_SHA1_QUIETLY)
765 exit(128);
766 else
767 die("Log for %s is empty.", refname);
768 }
4207ed28
RS
769 if (cb.found_it)
770 return 0;
771
772 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
d556fae2 773
16d7cc90 774 return 1;
d556fae2 775}
2ff81662 776
93a644ea 777struct ref_transaction *ref_transaction_begin(struct strbuf *err)
caa4046c 778{
5a603b04
JN
779 assert(err);
780
caa4046c
MH
781 return xcalloc(1, sizeof(struct ref_transaction));
782}
783
026bd1d3 784void ref_transaction_free(struct ref_transaction *transaction)
caa4046c
MH
785{
786 int i;
787
1b07255c
RS
788 if (!transaction)
789 return;
790
db7516ab
RS
791 for (i = 0; i < transaction->nr; i++) {
792 free(transaction->updates[i]->msg);
88615910 793 free(transaction->updates[i]);
db7516ab 794 }
caa4046c
MH
795 free(transaction->updates);
796 free(transaction);
797}
798
71564516
MH
799struct ref_update *ref_transaction_add_update(
800 struct ref_transaction *transaction,
801 const char *refname, unsigned int flags,
802 const unsigned char *new_sha1,
803 const unsigned char *old_sha1,
804 const char *msg)
caa4046c 805{
96ffc06f 806 struct ref_update *update;
71564516
MH
807
808 if (transaction->state != REF_TRANSACTION_OPEN)
809 die("BUG: update called for transaction that is not open");
810
811 if ((flags & REF_ISPRUNING) && !(flags & REF_NODEREF))
812 die("BUG: REF_ISPRUNING set without REF_NODEREF");
813
96ffc06f 814 FLEX_ALLOC_STR(update, refname, refname);
caa4046c
MH
815 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
816 transaction->updates[transaction->nr++] = update;
71564516
MH
817
818 update->flags = flags;
819
820 if (flags & REF_HAVE_NEW)
821 hashcpy(update->new_sha1, new_sha1);
822 if (flags & REF_HAVE_OLD)
823 hashcpy(update->old_sha1, old_sha1);
13092a91 824 update->msg = xstrdup_or_null(msg);
caa4046c
MH
825 return update;
826}
827
8e34800e
RS
828int ref_transaction_update(struct ref_transaction *transaction,
829 const char *refname,
830 const unsigned char *new_sha1,
831 const unsigned char *old_sha1,
1d147bdf 832 unsigned int flags, const char *msg,
8e34800e 833 struct strbuf *err)
caa4046c 834{
5a603b04
JN
835 assert(err);
836
8a679de6
MH
837 if ((new_sha1 && !is_null_sha1(new_sha1)) ?
838 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
839 !refname_is_safe(refname)) {
0568c8e9 840 strbuf_addf(err, "refusing to update ref with bad name '%s'",
d0f810f0
RS
841 refname);
842 return -1;
843 }
844
71564516
MH
845 flags |= (new_sha1 ? REF_HAVE_NEW : 0) | (old_sha1 ? REF_HAVE_OLD : 0);
846
847 ref_transaction_add_update(transaction, refname, flags,
848 new_sha1, old_sha1, msg);
8e34800e 849 return 0;
caa4046c
MH
850}
851
b416af5b
RS
852int ref_transaction_create(struct ref_transaction *transaction,
853 const char *refname,
854 const unsigned char *new_sha1,
fec14ec3 855 unsigned int flags, const char *msg,
b416af5b 856 struct strbuf *err)
caa4046c 857{
f04c5b55
MH
858 if (!new_sha1 || is_null_sha1(new_sha1))
859 die("BUG: create called without valid new_sha1");
bc9f2925 860 return ref_transaction_update(transaction, refname, new_sha1,
1d147bdf 861 null_sha1, flags, msg, err);
caa4046c
MH
862}
863
8c8bdc0d
RS
864int ref_transaction_delete(struct ref_transaction *transaction,
865 const char *refname,
866 const unsigned char *old_sha1,
fb5a6bb6 867 unsigned int flags, const char *msg,
8c8bdc0d 868 struct strbuf *err)
caa4046c 869{
60294596
MH
870 if (old_sha1 && is_null_sha1(old_sha1))
871 die("BUG: delete called with old_sha1 set to zeros");
1d147bdf 872 return ref_transaction_update(transaction, refname,
fb5a6bb6 873 null_sha1, old_sha1,
1d147bdf 874 flags, msg, err);
caa4046c
MH
875}
876
16180334
MH
877int ref_transaction_verify(struct ref_transaction *transaction,
878 const char *refname,
879 const unsigned char *old_sha1,
880 unsigned int flags,
881 struct strbuf *err)
882{
883 if (!old_sha1)
884 die("BUG: verify called with old_sha1 set to NULL");
885 return ref_transaction_update(transaction, refname,
886 NULL, old_sha1,
887 flags, NULL, err);
888}
889
8f6dc7e3 890int update_ref_oid(const char *msg, const char *refname,
891 const struct object_id *new_oid, const struct object_id *old_oid,
892 unsigned int flags, enum action_on_err onerr)
893{
894 return update_ref(msg, refname, new_oid ? new_oid->hash : NULL,
895 old_oid ? old_oid->hash : NULL, flags, onerr);
896}
897
4b7b520b
MH
898int update_ref(const char *msg, const char *refname,
899 const unsigned char *new_sha1, const unsigned char *old_sha1,
fec14ec3 900 unsigned int flags, enum action_on_err onerr)
4738a333 901{
74ec19d4 902 struct ref_transaction *t = NULL;
b4d75ac1 903 struct strbuf err = STRBUF_INIT;
74ec19d4 904 int ret = 0;
b4d75ac1 905
74ec19d4
DT
906 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
907 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
908 } else {
909 t = ref_transaction_begin(&err);
910 if (!t ||
911 ref_transaction_update(t, refname, new_sha1, old_sha1,
912 flags, msg, &err) ||
913 ref_transaction_commit(t, &err)) {
914 ret = 1;
915 ref_transaction_free(t);
916 }
917 }
918 if (ret) {
b4d75ac1
RS
919 const char *str = "update_ref failed for ref '%s': %s";
920
b4d75ac1
RS
921 switch (onerr) {
922 case UPDATE_REFS_MSG_ON_ERR:
923 error(str, refname, err.buf);
924 break;
925 case UPDATE_REFS_DIE_ON_ERR:
926 die(str, refname, err.buf);
927 break;
928 case UPDATE_REFS_QUIET_ON_ERR:
929 break;
930 }
931 strbuf_release(&err);
4738a333 932 return 1;
b4d75ac1
RS
933 }
934 strbuf_release(&err);
74ec19d4
DT
935 if (t)
936 ref_transaction_free(t);
b4d75ac1 937 return 0;
4738a333
BK
938}
939
dfefa935 940char *shorten_unambiguous_ref(const char *refname, int strict)
7c2b3029
JK
941{
942 int i;
943 static char **scanf_fmts;
944 static int nr_rules;
945 char *short_name;
946
7c2b3029 947 if (!nr_rules) {
4346663a
MH
948 /*
949 * Pre-generate scanf formats from ref_rev_parse_rules[].
950 * Generate a format suitable for scanf from a
951 * ref_rev_parse_rules rule by interpolating "%s" at the
952 * location of the "%.*s".
953 */
7c2b3029 954 size_t total_len = 0;
84d5633f 955 size_t offset = 0;
7c2b3029
JK
956
957 /* the rule list is NULL terminated, count them first */
a4165851 958 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
7902fe03
MH
959 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
960 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
7c2b3029 961
50492f7b 962 scanf_fmts = xmalloc(st_add(st_mult(sizeof(char *), nr_rules), total_len));
7c2b3029 963
84d5633f 964 offset = 0;
7c2b3029 965 for (i = 0; i < nr_rules; i++) {
4346663a 966 assert(offset < total_len);
84d5633f 967 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4346663a
MH
968 offset += snprintf(scanf_fmts[i], total_len - offset,
969 ref_rev_parse_rules[i], 2, "%s") + 1;
7c2b3029
JK
970 }
971 }
972
973 /* bail out if there are no rules */
974 if (!nr_rules)
dfefa935 975 return xstrdup(refname);
7c2b3029 976
dfefa935
MH
977 /* buffer for scanf result, at most refname must fit */
978 short_name = xstrdup(refname);
7c2b3029
JK
979
980 /* skip first rule, it will always match */
981 for (i = nr_rules - 1; i > 0 ; --i) {
982 int j;
6e7b3309 983 int rules_to_fail = i;
7c2b3029
JK
984 int short_name_len;
985
dfefa935 986 if (1 != sscanf(refname, scanf_fmts[i], short_name))
7c2b3029
JK
987 continue;
988
989 short_name_len = strlen(short_name);
990
6e7b3309
BW
991 /*
992 * in strict mode, all (except the matched one) rules
993 * must fail to resolve to a valid non-ambiguous ref
994 */
995 if (strict)
996 rules_to_fail = nr_rules;
997
7c2b3029
JK
998 /*
999 * check if the short name resolves to a valid ref,
1000 * but use only rules prior to the matched one
1001 */
6e7b3309 1002 for (j = 0; j < rules_to_fail; j++) {
7c2b3029 1003 const char *rule = ref_rev_parse_rules[j];
7c2b3029
JK
1004 char refname[PATH_MAX];
1005
6e7b3309
BW
1006 /* skip matched rule */
1007 if (i == j)
1008 continue;
1009
7c2b3029
JK
1010 /*
1011 * the short name is ambiguous, if it resolves
1012 * (with this previous rule) to a valid ref
1013 * read_ref() returns 0 on success
1014 */
1015 mksnpath(refname, sizeof(refname),
1016 rule, short_name_len, short_name);
c6893323 1017 if (ref_exists(refname))
7c2b3029
JK
1018 break;
1019 }
1020
1021 /*
1022 * short name is non-ambiguous if all previous rules
1023 * haven't resolved to a valid ref
1024 */
6e7b3309 1025 if (j == rules_to_fail)
7c2b3029
JK
1026 return short_name;
1027 }
1028
1029 free(short_name);
dfefa935 1030 return xstrdup(refname);
7c2b3029 1031}
daebaa78
JH
1032
1033static struct string_list *hide_refs;
1034
1035int parse_hide_refs_config(const char *var, const char *value, const char *section)
1036{
1037 if (!strcmp("transfer.hiderefs", var) ||
1038 /* NEEDSWORK: use parse_config_key() once both are merged */
59556548 1039 (starts_with(var, section) && var[strlen(section)] == '.' &&
daebaa78
JH
1040 !strcmp(var + strlen(section), ".hiderefs"))) {
1041 char *ref;
1042 int len;
1043
1044 if (!value)
1045 return config_error_nonbool(var);
1046 ref = xstrdup(value);
1047 len = strlen(ref);
1048 while (len && ref[len - 1] == '/')
1049 ref[--len] = '\0';
1050 if (!hide_refs) {
1051 hide_refs = xcalloc(1, sizeof(*hide_refs));
1052 hide_refs->strdup_strings = 1;
1053 }
1054 string_list_append(hide_refs, ref);
1055 }
1056 return 0;
1057}
1058
78a766ab 1059int ref_is_hidden(const char *refname, const char *refname_full)
daebaa78 1060{
2bc31d16 1061 int i;
daebaa78
JH
1062
1063 if (!hide_refs)
1064 return 0;
2bc31d16
JK
1065 for (i = hide_refs->nr - 1; i >= 0; i--) {
1066 const char *match = hide_refs->items[i].string;
78a766ab 1067 const char *subject;
2bc31d16 1068 int neg = 0;
daebaa78 1069 int len;
2bc31d16
JK
1070
1071 if (*match == '!') {
1072 neg = 1;
1073 match++;
1074 }
1075
78a766ab
LF
1076 if (*match == '^') {
1077 subject = refname_full;
1078 match++;
1079 } else {
1080 subject = refname;
1081 }
1082
1083 /* refname can be NULL when namespaces are used. */
1084 if (!subject || !starts_with(subject, match))
daebaa78 1085 continue;
2bc31d16 1086 len = strlen(match);
78a766ab 1087 if (!subject[len] || subject[len] == '/')
2bc31d16 1088 return !neg;
daebaa78
JH
1089 }
1090 return 0;
1091}
fa5b1830 1092
0845122c
DT
1093const char *find_descendant_ref(const char *dirname,
1094 const struct string_list *extras,
1095 const struct string_list *skip)
fa5b1830 1096{
0845122c 1097 int pos;
fa5b1830 1098
0845122c
DT
1099 if (!extras)
1100 return NULL;
fa5b1830
MH
1101
1102 /*
0845122c
DT
1103 * Look at the place where dirname would be inserted into
1104 * extras. If there is an entry at that position that starts
1105 * with dirname (remember, dirname includes the trailing
1106 * slash) and is not in skip, then we have a conflict.
fa5b1830 1107 */
0845122c
DT
1108 for (pos = string_list_find_insert_index(extras, dirname, 0);
1109 pos < extras->nr; pos++) {
1110 const char *extra_refname = extras->items[pos].string;
fa5b1830 1111
0845122c
DT
1112 if (!starts_with(extra_refname, dirname))
1113 break;
1114
1115 if (!skip || !string_list_has_string(skip, extra_refname))
1116 return extra_refname;
fa5b1830 1117 }
0845122c
DT
1118 return NULL;
1119}
fa5b1830 1120
ff3a299c 1121int rename_ref_available(const char *old_refname, const char *new_refname)
0845122c
DT
1122{
1123 struct string_list skip = STRING_LIST_INIT_NODUP;
1124 struct strbuf err = STRBUF_INIT;
ff3a299c 1125 int ok;
fa5b1830 1126
ff3a299c
DT
1127 string_list_insert(&skip, old_refname);
1128 ok = !verify_refname_available(new_refname, NULL, &skip, &err);
1129 if (!ok)
0845122c
DT
1130 error("%s", err.buf);
1131
1132 string_list_clear(&skip, 0);
1133 strbuf_release(&err);
ff3a299c 1134 return ok;
fa5b1830 1135}
2bf68ed5
DT
1136
1137int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1138{
1139 struct object_id oid;
1140 int flag;
1141
1142 if (submodule) {
1143 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1144 return fn("HEAD", &oid, 0, cb_data);
1145
1146 return 0;
1147 }
1148
1149 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1150 return fn("HEAD", &oid, flag, cb_data);
1151
1152 return 0;
1153}
1154
1155int head_ref(each_ref_fn fn, void *cb_data)
1156{
1157 return head_ref_submodule(NULL, fn, cb_data);
1158}
93770590 1159
4c4de895
MH
1160/*
1161 * Call fn for each reference in the specified submodule for which the
1162 * refname begins with prefix. If trim is non-zero, then trim that
1163 * many characters off the beginning of each refname before passing
1164 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1165 * include broken references in the iteration. If fn ever returns a
1166 * non-zero value, stop the iteration and return that value;
1167 * otherwise, return 0.
1168 */
1169static int do_for_each_ref(const char *submodule, const char *prefix,
1170 each_ref_fn fn, int trim, int flags, void *cb_data)
1171{
00eebe35 1172 struct ref_store *refs = get_ref_store(submodule);
4c4de895
MH
1173 struct ref_iterator *iter;
1174
00eebe35
MH
1175 if (!refs)
1176 return 0;
1177
1a769003 1178 iter = refs->be->iterator_begin(refs, prefix, flags);
4c4de895
MH
1179 iter = prefix_ref_iterator_begin(iter, prefix, trim);
1180
1181 return do_for_each_ref_iterator(iter, fn, cb_data);
1182}
1183
93770590
DT
1184int for_each_ref(each_ref_fn fn, void *cb_data)
1185{
1186 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1187}
1188
1189int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1190{
1191 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1192}
1193
1194int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1195{
1196 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1197}
1198
1199int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1200{
1201 unsigned int flag = 0;
1202
1203 if (broken)
1204 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1205 return do_for_each_ref(NULL, prefix, fn, 0, flag, cb_data);
1206}
1207
1208int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1209 each_ref_fn fn, void *cb_data)
1210{
1211 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1212}
1213
1214int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1215{
1216 return do_for_each_ref(NULL, git_replace_ref_base, fn,
1217 strlen(git_replace_ref_base), 0, cb_data);
1218}
1219
1220int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1221{
1222 struct strbuf buf = STRBUF_INIT;
1223 int ret;
1224 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1225 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1226 strbuf_release(&buf);
1227 return ret;
1228}
1229
1230int for_each_rawref(each_ref_fn fn, void *cb_data)
1231{
1232 return do_for_each_ref(NULL, "", fn, 0,
1233 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1234}
2d0663b2
DT
1235
1236/* This function needs to return a meaningful errno on failure */
bd40dcda
MH
1237static const char *resolve_ref_recursively(struct ref_store *refs,
1238 const char *refname,
1239 int resolve_flags,
1240 unsigned char *sha1, int *flags)
2d0663b2
DT
1241{
1242 static struct strbuf sb_refname = STRBUF_INIT;
1243 int unused_flags;
1244 int symref_count;
1245
1246 if (!flags)
1247 flags = &unused_flags;
1248
1249 *flags = 0;
1250
1251 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1252 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1253 !refname_is_safe(refname)) {
1254 errno = EINVAL;
1255 return NULL;
1256 }
1257
1258 /*
1259 * dwim_ref() uses REF_ISBROKEN to distinguish between
1260 * missing refs and refs that were present but invalid,
1261 * to complain about the latter to stderr.
1262 *
1263 * We don't know whether the ref exists, so don't set
1264 * REF_ISBROKEN yet.
1265 */
1266 *flags |= REF_BAD_NAME;
1267 }
1268
1269 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1270 unsigned int read_flags = 0;
1271
e1e33b72
MH
1272 if (refs->be->read_raw_ref(refs, refname,
1273 sha1, &sb_refname, &read_flags)) {
2d0663b2
DT
1274 *flags |= read_flags;
1275 if (errno != ENOENT || (resolve_flags & RESOLVE_REF_READING))
1276 return NULL;
1277 hashclr(sha1);
1278 if (*flags & REF_BAD_NAME)
1279 *flags |= REF_ISBROKEN;
1280 return refname;
1281 }
1282
1283 *flags |= read_flags;
1284
1285 if (!(read_flags & REF_ISSYMREF)) {
1286 if (*flags & REF_BAD_NAME) {
1287 hashclr(sha1);
1288 *flags |= REF_ISBROKEN;
1289 }
1290 return refname;
1291 }
1292
1293 refname = sb_refname.buf;
1294 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1295 hashclr(sha1);
1296 return refname;
1297 }
1298 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1299 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1300 !refname_is_safe(refname)) {
1301 errno = EINVAL;
1302 return NULL;
1303 }
1304
1305 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1306 }
1307 }
1308
1309 errno = ELOOP;
1310 return NULL;
1311}
00eebe35 1312
6fb5acfd
DT
1313/* backend functions */
1314int refs_init_db(struct strbuf *err)
1315{
1316 struct ref_store *refs = get_ref_store(NULL);
1317
1318 return refs->be->init_db(refs, err);
1319}
1320
bd40dcda
MH
1321const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1322 unsigned char *sha1, int *flags)
1323{
1324 return resolve_ref_recursively(get_ref_store(NULL), refname,
1325 resolve_flags, sha1, flags);
1326}
1327
a8355bb7
MH
1328int resolve_gitlink_ref(const char *submodule, const char *refname,
1329 unsigned char *sha1)
424dcc76 1330{
a8355bb7 1331 size_t len = strlen(submodule);
424dcc76
MH
1332 struct ref_store *refs;
1333 int flags;
1334
a8355bb7 1335 while (len && submodule[len - 1] == '/')
424dcc76 1336 len--;
48a8475f 1337
424dcc76
MH
1338 if (!len)
1339 return -1;
1340
a8355bb7 1341 if (submodule[len]) {
48a8475f 1342 /* We need to strip off one or more trailing slashes */
a8355bb7 1343 char *stripped = xmemdupz(submodule, len);
48a8475f
MH
1344
1345 refs = get_ref_store(stripped);
1346 free(stripped);
1347 } else {
a8355bb7 1348 refs = get_ref_store(submodule);
48a8475f
MH
1349 }
1350
424dcc76
MH
1351 if (!refs)
1352 return -1;
1353
1354 if (!resolve_ref_recursively(refs, refname, 0, sha1, &flags) ||
1355 is_null_sha1(sha1))
1356 return -1;
1357 return 0;
1358}
1359
00eebe35
MH
1360/* A pointer to the ref_store for the main repository: */
1361static struct ref_store *main_ref_store;
1362
1363/* A linked list of ref_stores for submodules: */
1364static struct ref_store *submodule_ref_stores;
1365
1366void base_ref_store_init(struct ref_store *refs,
1367 const struct ref_storage_be *be,
1368 const char *submodule)
1369{
1370 refs->be = be;
1371 if (!submodule) {
1372 if (main_ref_store)
1373 die("BUG: main_ref_store initialized twice");
1374
1375 refs->submodule = "";
1376 refs->next = NULL;
1377 main_ref_store = refs;
1378 } else {
1379 if (lookup_ref_store(submodule))
1380 die("BUG: ref_store for submodule '%s' initialized twice",
1381 submodule);
1382
1383 refs->submodule = xstrdup(submodule);
1384 refs->next = submodule_ref_stores;
1385 submodule_ref_stores = refs;
1386 }
1387}
1388
1389struct ref_store *ref_store_init(const char *submodule)
1390{
1391 const char *be_name = "files";
1392 struct ref_storage_be *be = find_ref_storage_backend(be_name);
1393
1394 if (!be)
1395 die("BUG: reference backend %s is unknown", be_name);
1396
1397 if (!submodule || !*submodule)
1398 return be->init(NULL);
1399 else
1400 return be->init(submodule);
1401}
1402
1403struct ref_store *lookup_ref_store(const char *submodule)
1404{
1405 struct ref_store *refs;
1406
1407 if (!submodule || !*submodule)
1408 return main_ref_store;
1409
1410 for (refs = submodule_ref_stores; refs; refs = refs->next) {
1411 if (!strcmp(submodule, refs->submodule))
1412 return refs;
1413 }
1414
1415 return NULL;
1416}
1417
1418struct ref_store *get_ref_store(const char *submodule)
1419{
1420 struct ref_store *refs;
1421
1422 if (!submodule || !*submodule) {
1423 refs = lookup_ref_store(NULL);
1424
1425 if (!refs)
1426 refs = ref_store_init(NULL);
1427 } else {
1428 refs = lookup_ref_store(submodule);
1429
1430 if (!refs) {
1431 struct strbuf submodule_sb = STRBUF_INIT;
1432
1433 strbuf_addstr(&submodule_sb, submodule);
1434 if (is_nonbare_repository_dir(&submodule_sb))
1435 refs = ref_store_init(submodule);
1436 strbuf_release(&submodule_sb);
1437 }
1438 }
1439
1440 return refs;
1441}
1442
1443void assert_main_repository(struct ref_store *refs, const char *caller)
1444{
1445 if (*refs->submodule)
1446 die("BUG: %s called for a submodule", caller);
1447}
127b42a1
RS
1448
1449/* backend functions */
8231527e
MH
1450int pack_refs(unsigned int flags)
1451{
1452 struct ref_store *refs = get_ref_store(NULL);
1453
1454 return refs->be->pack_refs(refs, flags);
1455}
1456
bd427cf2
MH
1457int peel_ref(const char *refname, unsigned char *sha1)
1458{
1459 struct ref_store *refs = get_ref_store(NULL);
1460
1461 return refs->be->peel_ref(refs, refname, sha1);
1462}
1463
284689ba
MH
1464int create_symref(const char *ref_target, const char *refs_heads_master,
1465 const char *logmsg)
1466{
1467 struct ref_store *refs = get_ref_store(NULL);
1468
1469 return refs->be->create_symref(refs, ref_target, refs_heads_master,
1470 logmsg);
1471}
1472
127b42a1
RS
1473int ref_transaction_commit(struct ref_transaction *transaction,
1474 struct strbuf *err)
1475{
1476 struct ref_store *refs = get_ref_store(NULL);
1477
1478 return refs->be->transaction_commit(refs, transaction, err);
1479}
62665823
MH
1480
1481int verify_refname_available(const char *refname,
1482 const struct string_list *extra,
1483 const struct string_list *skip,
1484 struct strbuf *err)
1485{
1486 struct ref_store *refs = get_ref_store(NULL);
1487
1488 return refs->be->verify_refname_available(refs, refname, extra, skip, err);
1489}
e3688bd6
DT
1490
1491int for_each_reflog(each_ref_fn fn, void *cb_data)
1492{
1493 struct ref_store *refs = get_ref_store(NULL);
1494 struct ref_iterator *iter;
1495
1496 iter = refs->be->reflog_iterator_begin(refs);
1497
1498 return do_for_each_ref_iterator(iter, fn, cb_data);
1499}
1500
1501int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
1502 void *cb_data)
1503{
1504 struct ref_store *refs = get_ref_store(NULL);
1505
1506 return refs->be->for_each_reflog_ent_reverse(refs, refname,
1507 fn, cb_data);
1508}
1509
1510int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
1511 void *cb_data)
1512{
1513 struct ref_store *refs = get_ref_store(NULL);
1514
1515 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
1516}
1517
1518int reflog_exists(const char *refname)
1519{
1520 struct ref_store *refs = get_ref_store(NULL);
1521
1522 return refs->be->reflog_exists(refs, refname);
1523}
1524
1525int safe_create_reflog(const char *refname, int force_create,
1526 struct strbuf *err)
1527{
1528 struct ref_store *refs = get_ref_store(NULL);
1529
1530 return refs->be->create_reflog(refs, refname, force_create, err);
1531}
1532
1533int delete_reflog(const char *refname)
1534{
1535 struct ref_store *refs = get_ref_store(NULL);
1536
1537 return refs->be->delete_reflog(refs, refname);
1538}
1539
1540int reflog_expire(const char *refname, const unsigned char *sha1,
1541 unsigned int flags,
1542 reflog_expiry_prepare_fn prepare_fn,
1543 reflog_expiry_should_prune_fn should_prune_fn,
1544 reflog_expiry_cleanup_fn cleanup_fn,
1545 void *policy_cb_data)
1546{
1547 struct ref_store *refs = get_ref_store(NULL);
1548
1549 return refs->be->reflog_expire(refs, refname, sha1, flags,
1550 prepare_fn, should_prune_fn,
1551 cleanup_fn, policy_cb_data);
1552}
fc681463
DT
1553
1554int initial_ref_transaction_commit(struct ref_transaction *transaction,
1555 struct strbuf *err)
1556{
1557 struct ref_store *refs = get_ref_store(NULL);
1558
1559 return refs->be->initial_transaction_commit(refs, transaction, err);
1560}
a27dcf89
DT
1561
1562int delete_refs(struct string_list *refnames, unsigned int flags)
1563{
1564 struct ref_store *refs = get_ref_store(NULL);
1565
1566 return refs->be->delete_refs(refs, refnames, flags);
1567}
9b6b40d9
DT
1568
1569int rename_ref(const char *oldref, const char *newref, const char *logmsg)
1570{
1571 struct ref_store *refs = get_ref_store(NULL);
1572
1573 return refs->be->rename_ref(refs, oldref, newref, logmsg);
1574}