verify_refname_available(): adjust constness in declaration
[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
bc5fd6d3 12/*
dde8a902
DT
13 * How to handle various characters in refnames:
14 * 0: An acceptable character for refs
5e650228
JH
15 * 1: End-of-component
16 * 2: ., look for a preceding . to reject .. in refs
17 * 3: {, look for a preceding @ to reject @{ in refs
53a8555e 18 * 4: A bad character: ASCII control characters, and
cd377f45
JK
19 * ":", "?", "[", "\", "^", "~", SP, or TAB
20 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
dde8a902
DT
21 */
22static unsigned char refname_disposition[256] = {
5e650228
JH
23 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
24 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
cd377f45 25 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
5e650228 26 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
dde8a902 27 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5e650228
JH
28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
dde8a902
DT
31};
32
33/*
34 * Try to read one refname component from the front of refname.
35 * Return the length of the component found, or -1 if the component is
36 * not legal. It is legal if it is something reasonable to have under
37 * ".git/refs/"; We do not like it if:
bc5fd6d3
MH
38 *
39 * - any path component of it begins with ".", or
40 * - it has double dots "..", or
53a8555e 41 * - it has ASCII control characters, or
cd377f45
JK
42 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
43 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
53a8555e
JK
44 * - it ends with a "/", or
45 * - it ends with ".lock", or
46 * - it contains a "@{" portion
bc5fd6d3 47 */
cd377f45 48static int check_refname_component(const char *refname, int *flags)
bc5fd6d3
MH
49{
50 const char *cp;
51 char last = '\0';
52
53 for (cp = refname; ; cp++) {
dde8a902
DT
54 int ch = *cp & 255;
55 unsigned char disp = refname_disposition[ch];
56 switch (disp) {
5e650228 57 case 1:
dde8a902 58 goto out;
5e650228 59 case 2:
dde8a902
DT
60 if (last == '.')
61 return -1; /* Refname contains "..". */
62 break;
5e650228 63 case 3:
dde8a902
DT
64 if (last == '@')
65 return -1; /* Refname contains "@{". */
bc5fd6d3 66 break;
5e650228 67 case 4:
dde8a902 68 return -1;
cd377f45
JK
69 case 5:
70 if (!(*flags & REFNAME_REFSPEC_PATTERN))
71 return -1; /* refspec can't be a pattern */
72
73 /*
74 * Unset the pattern flag so that we only accept
75 * a single asterisk for one side of refspec.
76 */
77 *flags &= ~ REFNAME_REFSPEC_PATTERN;
78 break;
dde8a902 79 }
bc5fd6d3
MH
80 last = ch;
81 }
dde8a902 82out:
bc5fd6d3 83 if (cp == refname)
dac529e4 84 return 0; /* Component has zero length. */
f3cc52d8
JN
85 if (refname[0] == '.')
86 return -1; /* Component starts with '.'. */
7108ad23
MH
87 if (cp - refname >= LOCK_SUFFIX_LEN &&
88 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
bc5fd6d3
MH
89 return -1; /* Refname ends with ".lock". */
90 return cp - refname;
91}
92
5e650228 93int check_refname_format(const char *refname, int flags)
bc5fd6d3
MH
94{
95 int component_len, component_count = 0;
96
9ba89f48
FC
97 if (!strcmp(refname, "@"))
98 /* Refname is a single character '@'. */
99 return -1;
100
bc5fd6d3
MH
101 while (1) {
102 /* We are at the start of a path component. */
cd377f45
JK
103 component_len = check_refname_component(refname, &flags);
104 if (component_len <= 0)
105 return -1;
106
bc5fd6d3
MH
107 component_count++;
108 if (refname[component_len] == '\0')
109 break;
110 /* Skip to next component. */
111 refname += component_len + 1;
112 }
113
114 if (refname[component_len - 1] == '.')
115 return -1; /* Refname ends with '.'. */
116 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
117 return -1; /* Refname has only one component. */
118 return 0;
119}
120
4cb77009 121int refname_is_safe(const char *refname)
d0f810f0 122{
39950fef
MH
123 const char *rest;
124
125 if (skip_prefix(refname, "refs/", &rest)) {
d0f810f0
RS
126 char *buf;
127 int result;
e40f3557
MH
128 size_t restlen = strlen(rest);
129
130 /* rest must not be empty, or start or end with "/" */
131 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
132 return 0;
d0f810f0 133
d0f810f0
RS
134 /*
135 * Does the refname try to escape refs/?
136 * For example: refs/foo/../bar is safe but refs/foo/../../bar
137 * is not.
138 */
e40f3557
MH
139 buf = xmallocz(restlen);
140 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
d0f810f0
RS
141 free(buf);
142 return result;
143 }
35db25c6
MH
144
145 do {
d0f810f0
RS
146 if (!isupper(*refname) && *refname != '_')
147 return 0;
148 refname++;
35db25c6 149 } while (*refname);
d0f810f0
RS
150 return 1;
151}
152
7bd9bcf3
MH
153char *resolve_refdup(const char *refname, int resolve_flags,
154 unsigned char *sha1, int *flags)
e1e22e37 155{
7bd9bcf3
MH
156 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
157 sha1, flags));
cddc4258
MH
158}
159
7bd9bcf3
MH
160/* The argument to filter_refs */
161struct ref_filter {
162 const char *pattern;
163 each_ref_fn *fn;
164 void *cb_data;
165};
432ad41e 166
7bd9bcf3 167int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
732134ed 168{
7bd9bcf3
MH
169 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
170 return 0;
171 return -1;
732134ed
MH
172}
173
7bd9bcf3 174int read_ref(const char *refname, unsigned char *sha1)
cddc4258 175{
7bd9bcf3 176 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
c774aab9
JP
177}
178
7bd9bcf3 179int ref_exists(const char *refname)
bc5fd6d3 180{
7bd9bcf3
MH
181 unsigned char sha1[20];
182 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
bc5fd6d3
MH
183}
184
7bd9bcf3
MH
185static int filter_refs(const char *refname, const struct object_id *oid,
186 int flags, void *data)
432ad41e 187{
7bd9bcf3
MH
188 struct ref_filter *filter = (struct ref_filter *)data;
189
190 if (wildmatch(filter->pattern, refname, 0, NULL))
191 return 0;
192 return filter->fn(refname, oid, flags, filter->cb_data);
432ad41e
MH
193}
194
7bd9bcf3 195enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
c774aab9 196{
7bd9bcf3 197 struct object *o = lookup_unknown_object(name);
c774aab9 198
7bd9bcf3
MH
199 if (o->type == OBJ_NONE) {
200 int type = sha1_object_info(name, NULL);
201 if (type < 0 || !object_as_type(o, type, 0))
202 return PEEL_INVALID;
203 }
bc5fd6d3 204
7bd9bcf3
MH
205 if (o->type != OBJ_TAG)
206 return PEEL_NON_TAG;
e1980c9d 207
7bd9bcf3
MH
208 o = deref_tag_noverify(o);
209 if (!o)
210 return PEEL_INVALID;
211
844a9ce4 212 hashcpy(sha1, o->oid.hash);
7bd9bcf3 213 return PEEL_PEELED;
e1980c9d
JH
214}
215
7bd9bcf3
MH
216struct warn_if_dangling_data {
217 FILE *fp;
218 const char *refname;
219 const struct string_list *refnames;
220 const char *msg_fmt;
221};
bc5fd6d3 222
7bd9bcf3
MH
223static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
224 int flags, void *cb_data)
225{
226 struct warn_if_dangling_data *d = cb_data;
227 const char *resolves_to;
228 struct object_id junk;
bc5fd6d3 229
7bd9bcf3
MH
230 if (!(flags & REF_ISSYMREF))
231 return 0;
bc5fd6d3 232
7bd9bcf3
MH
233 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
234 if (!resolves_to
235 || (d->refname
236 ? strcmp(resolves_to, d->refname)
237 : !string_list_has_string(d->refnames, resolves_to))) {
238 return 0;
239 }
bc5fd6d3 240
7bd9bcf3
MH
241 fprintf(d->fp, d->msg_fmt, refname);
242 fputc('\n', d->fp);
243 return 0;
bc5fd6d3
MH
244}
245
7bd9bcf3 246void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
f348ac92 247{
7bd9bcf3
MH
248 struct warn_if_dangling_data data;
249
250 data.fp = fp;
251 data.refname = refname;
252 data.refnames = NULL;
253 data.msg_fmt = msg_fmt;
254 for_each_rawref(warn_if_dangling_symref, &data);
f348ac92
MH
255}
256
7bd9bcf3 257void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
432ad41e 258{
7bd9bcf3 259 struct warn_if_dangling_data data;
432ad41e 260
7bd9bcf3
MH
261 data.fp = fp;
262 data.refname = NULL;
263 data.refnames = refnames;
264 data.msg_fmt = msg_fmt;
265 for_each_rawref(warn_if_dangling_symref, &data);
432ad41e
MH
266}
267
7bd9bcf3 268int for_each_tag_ref(each_ref_fn fn, void *cb_data)
432ad41e 269{
7bd9bcf3 270 return for_each_ref_in("refs/tags/", fn, cb_data);
432ad41e
MH
271}
272
7bd9bcf3 273int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
506a760d 274{
7bd9bcf3 275 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
432ad41e
MH
276}
277
7bd9bcf3 278int for_each_branch_ref(each_ref_fn fn, void *cb_data)
432ad41e 279{
7bd9bcf3 280 return for_each_ref_in("refs/heads/", fn, cb_data);
432ad41e
MH
281}
282
7bd9bcf3 283int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
202a56a9 284{
7bd9bcf3 285 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
202a56a9 286}
432ad41e 287
7bd9bcf3 288int for_each_remote_ref(each_ref_fn fn, void *cb_data)
e9c4c111 289{
7bd9bcf3 290 return for_each_ref_in("refs/remotes/", fn, cb_data);
202a56a9
MH
291}
292
7bd9bcf3 293int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
e9c4c111 294{
7bd9bcf3 295 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
662428f4 296}
c774aab9 297
7bd9bcf3
MH
298int head_ref_namespaced(each_ref_fn fn, void *cb_data)
299{
300 struct strbuf buf = STRBUF_INIT;
301 int ret = 0;
302 struct object_id oid;
303 int flag;
c774aab9 304
7bd9bcf3
MH
305 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
306 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
307 ret = fn(buf.buf, &oid, flag, cb_data);
308 strbuf_release(&buf);
c774aab9 309
7bd9bcf3 310 return ret;
e9c4c111 311}
c774aab9 312
7bd9bcf3
MH
313int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
314 const char *prefix, void *cb_data)
662428f4 315{
7bd9bcf3
MH
316 struct strbuf real_pattern = STRBUF_INIT;
317 struct ref_filter filter;
318 int ret;
d08bae7e 319
59556548 320 if (!prefix && !starts_with(pattern, "refs/"))
d08bae7e 321 strbuf_addstr(&real_pattern, "refs/");
b09fe971
IL
322 else if (prefix)
323 strbuf_addstr(&real_pattern, prefix);
d08bae7e
IL
324 strbuf_addstr(&real_pattern, pattern);
325
894a9d33 326 if (!has_glob_specials(pattern)) {
9517e6b8 327 /* Append implied '/' '*' if not present. */
00b6c178 328 strbuf_complete(&real_pattern, '/');
d08bae7e
IL
329 /* No need to check for '*', there is none. */
330 strbuf_addch(&real_pattern, '*');
331 }
332
333 filter.pattern = real_pattern.buf;
334 filter.fn = fn;
335 filter.cb_data = cb_data;
336 ret = for_each_ref(filter_refs, &filter);
337
338 strbuf_release(&real_pattern);
339 return ret;
340}
341
b09fe971
IL
342int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
343{
344 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
345}
346
4577e483 347const char *prettify_refname(const char *name)
a9c37a72 348{
a9c37a72 349 return name + (
59556548
CC
350 starts_with(name, "refs/heads/") ? 11 :
351 starts_with(name, "refs/tags/") ? 10 :
352 starts_with(name, "refs/remotes/") ? 13 :
a9c37a72
DB
353 0);
354}
355
54457fe5 356static const char *ref_rev_parse_rules[] = {
79803322
SP
357 "%.*s",
358 "refs/%.*s",
359 "refs/tags/%.*s",
360 "refs/heads/%.*s",
361 "refs/remotes/%.*s",
362 "refs/remotes/%.*s/HEAD",
363 NULL
364};
365
54457fe5 366int refname_match(const char *abbrev_name, const char *full_name)
79803322
SP
367{
368 const char **p;
369 const int abbrev_name_len = strlen(abbrev_name);
370
54457fe5 371 for (p = ref_rev_parse_rules; *p; p++) {
79803322
SP
372 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
373 return 1;
374 }
375 }
376
377 return 0;
378}
379
ff74f7f1
JH
380/*
381 * *string and *len will only be substituted, and *string returned (for
382 * later free()ing) if the string passed in is a magic short-hand form
383 * to name a branch.
384 */
385static char *substitute_branch_name(const char **string, int *len)
386{
387 struct strbuf buf = STRBUF_INIT;
cf99a761 388 int ret = interpret_branch_name(*string, *len, &buf);
ff74f7f1
JH
389
390 if (ret == *len) {
391 size_t size;
392 *string = strbuf_detach(&buf, &size);
393 *len = size;
394 return (char *)*string;
395 }
396
397 return NULL;
398}
399
400int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
401{
402 char *last_branch = substitute_branch_name(&str, &len);
403 const char **p, *r;
404 int refs_found = 0;
405
406 *ref = NULL;
407 for (p = ref_rev_parse_rules; *p; p++) {
408 char fullref[PATH_MAX];
409 unsigned char sha1_from_ref[20];
410 unsigned char *this_result;
411 int flag;
412
413 this_result = refs_found ? sha1_from_ref : sha1;
414 mksnpath(fullref, sizeof(fullref), *p, len, str);
7695d118
RS
415 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
416 this_result, &flag);
ff74f7f1
JH
417 if (r) {
418 if (!refs_found++)
419 *ref = xstrdup(r);
420 if (!warn_ambiguous_refs)
421 break;
55956350 422 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
ff74f7f1 423 warning("ignoring dangling symref %s.", fullref);
55956350
JH
424 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
425 warning("ignoring broken ref %s.", fullref);
426 }
ff74f7f1
JH
427 }
428 free(last_branch);
429 return refs_found;
430}
431
432int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
433{
434 char *last_branch = substitute_branch_name(&str, &len);
435 const char **p;
436 int logs_found = 0;
437
438 *log = NULL;
439 for (p = ref_rev_parse_rules; *p; p++) {
ff74f7f1
JH
440 unsigned char hash[20];
441 char path[PATH_MAX];
442 const char *ref, *it;
443
444 mksnpath(path, sizeof(path), *p, len, str);
7695d118
RS
445 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
446 hash, NULL);
ff74f7f1
JH
447 if (!ref)
448 continue;
4da58835 449 if (reflog_exists(path))
ff74f7f1 450 it = path;
4da58835 451 else if (strcmp(ref, path) && reflog_exists(ref))
ff74f7f1
JH
452 it = ref;
453 else
454 continue;
455 if (!logs_found++) {
456 *log = xstrdup(it);
457 hashcpy(sha1, hash);
458 }
7bd9bcf3
MH
459 if (!warn_ambiguous_refs)
460 break;
c0277d15 461 }
7bd9bcf3
MH
462 free(last_branch);
463 return logs_found;
2ddb5d17
BK
464}
465
266b1827
DT
466static int is_per_worktree_ref(const char *refname)
467{
ce414b33
DT
468 return !strcmp(refname, "HEAD") ||
469 starts_with(refname, "refs/bisect/");
266b1827
DT
470}
471
472static int is_pseudoref_syntax(const char *refname)
473{
474 const char *c;
475
476 for (c = refname; *c; c++) {
477 if (!isupper(*c) && *c != '-' && *c != '_')
478 return 0;
479 }
480
481 return 1;
482}
483
484enum ref_type ref_type(const char *refname)
485{
486 if (is_per_worktree_ref(refname))
487 return REF_TYPE_PER_WORKTREE;
488 if (is_pseudoref_syntax(refname))
489 return REF_TYPE_PSEUDOREF;
490 return REF_TYPE_NORMAL;
491}
492
74ec19d4
DT
493static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
494 const unsigned char *old_sha1, struct strbuf *err)
495{
496 const char *filename;
497 int fd;
498 static struct lock_file lock;
499 struct strbuf buf = STRBUF_INIT;
500 int ret = -1;
501
502 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
503
504 filename = git_path("%s", pseudoref);
505 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
506 if (fd < 0) {
0568c8e9 507 strbuf_addf(err, "could not open '%s' for writing: %s",
74ec19d4
DT
508 filename, strerror(errno));
509 return -1;
510 }
511
512 if (old_sha1) {
513 unsigned char actual_old_sha1[20];
2c3aed13
DT
514
515 if (read_ref(pseudoref, actual_old_sha1))
516 die("could not read ref '%s'", pseudoref);
74ec19d4 517 if (hashcmp(actual_old_sha1, old_sha1)) {
0568c8e9 518 strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
74ec19d4
DT
519 rollback_lock_file(&lock);
520 goto done;
521 }
522 }
523
524 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
0568c8e9 525 strbuf_addf(err, "could not write to '%s'", filename);
74ec19d4
DT
526 rollback_lock_file(&lock);
527 goto done;
528 }
529
530 commit_lock_file(&lock);
531 ret = 0;
532done:
533 strbuf_release(&buf);
534 return ret;
535}
536
537static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
538{
539 static struct lock_file lock;
540 const char *filename;
541
542 filename = git_path("%s", pseudoref);
543
544 if (old_sha1 && !is_null_sha1(old_sha1)) {
545 int fd;
546 unsigned char actual_old_sha1[20];
547
548 fd = hold_lock_file_for_update(&lock, filename,
549 LOCK_DIE_ON_ERROR);
550 if (fd < 0)
551 die_errno(_("Could not open '%s' for writing"), filename);
2c3aed13
DT
552 if (read_ref(pseudoref, actual_old_sha1))
553 die("could not read ref '%s'", pseudoref);
74ec19d4
DT
554 if (hashcmp(actual_old_sha1, old_sha1)) {
555 warning("Unexpected sha1 when deleting %s", pseudoref);
556 rollback_lock_file(&lock);
557 return -1;
a4c653df 558 }
74ec19d4
DT
559
560 unlink(filename);
561 rollback_lock_file(&lock);
562 } else {
563 unlink(filename);
4bd18c43 564 }
a4c653df 565
4bd18c43 566 return 0;
95fc7512 567}
d556fae2 568
fc1c2168
MH
569int delete_ref(const char *refname, const unsigned char *old_sha1,
570 unsigned int flags)
41b625b0 571{
7521cc46 572 struct ref_transaction *transaction;
a4c653df 573 struct strbuf err = STRBUF_INIT;
8b5157e4 574
74ec19d4 575 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
080cc646 576 return delete_pseudoref(refname, old_sha1);
d48744d1 577
7521cc46
RS
578 transaction = ref_transaction_begin(&err);
579 if (!transaction ||
fc67a082 580 ref_transaction_delete(transaction, refname, old_sha1,
fb5a6bb6 581 flags, NULL, &err) ||
db7516ab 582 ref_transaction_commit(transaction, &err)) {
7521cc46
RS
583 error("%s", err.buf);
584 ref_transaction_free(transaction);
585 strbuf_release(&err);
c0277d15 586 return 1;
41b625b0 587 }
7bd9bcf3
MH
588 ref_transaction_free(transaction);
589 strbuf_release(&err);
b531394d
BC
590 return 0;
591}
41b625b0 592
4cb77009 593int copy_reflog_msg(char *buf, const char *msg)
0ec29a47
JH
594{
595 char *cp = buf;
596 char c;
597 int wasspace = 1;
8b5157e4 598
0ec29a47
JH
599 *cp++ = '\t';
600 while ((c = *msg++)) {
601 if (wasspace && isspace(c))
602 continue;
603 wasspace = isspace(c);
604 if (wasspace)
605 c = ' ';
606 *cp++ = c;
a4c653df 607 }
0ec29a47
JH
608 while (buf < cp && isspace(cp[-1]))
609 cp--;
610 *cp++ = '\n';
611 return cp - buf;
612}
8b5157e4 613
4cb77009 614int should_autocreate_reflog(const char *refname)
4e2bef57
DT
615{
616 if (!log_all_ref_updates)
617 return 0;
618 return starts_with(refname, "refs/heads/") ||
619 starts_with(refname, "refs/remotes/") ||
620 starts_with(refname, "refs/notes/") ||
621 !strcmp(refname, "HEAD");
622}
623
e7e0f26e 624int is_branch(const char *refname)
c3b0dec5 625{
59556548 626 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
41b625b0
NP
627}
628
4207ed28
RS
629struct read_ref_at_cb {
630 const char *refname;
631 unsigned long at_time;
632 int cnt;
633 int reccnt;
634 unsigned char *sha1;
635 int found_it;
636
637 unsigned char osha1[20];
638 unsigned char nsha1[20];
639 int tz;
640 unsigned long date;
641 char **msg;
642 unsigned long *cutoff_time;
643 int *cutoff_tz;
644 int *cutoff_cnt;
645};
646
647static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
648 const char *email, unsigned long timestamp, int tz,
649 const char *message, void *cb_data)
650{
651 struct read_ref_at_cb *cb = cb_data;
652
653 cb->reccnt++;
654 cb->tz = tz;
655 cb->date = timestamp;
656
657 if (timestamp <= cb->at_time || cb->cnt == 0) {
658 if (cb->msg)
659 *cb->msg = xstrdup(message);
660 if (cb->cutoff_time)
661 *cb->cutoff_time = timestamp;
662 if (cb->cutoff_tz)
663 *cb->cutoff_tz = tz;
664 if (cb->cutoff_cnt)
665 *cb->cutoff_cnt = cb->reccnt - 1;
666 /*
667 * we have not yet updated cb->[n|o]sha1 so they still
668 * hold the values for the previous record.
669 */
670 if (!is_null_sha1(cb->osha1)) {
671 hashcpy(cb->sha1, nsha1);
672 if (hashcmp(cb->osha1, nsha1))
673 warning("Log for ref %s has gap after %s.",
a5481a6c 674 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
4207ed28
RS
675 }
676 else if (cb->date == cb->at_time)
677 hashcpy(cb->sha1, nsha1);
678 else if (hashcmp(nsha1, cb->sha1))
679 warning("Log for ref %s unexpectedly ended on %s.",
680 cb->refname, show_date(cb->date, cb->tz,
a5481a6c 681 DATE_MODE(RFC2822)));
4207ed28
RS
682 hashcpy(cb->osha1, osha1);
683 hashcpy(cb->nsha1, nsha1);
684 cb->found_it = 1;
685 return 1;
686 }
687 hashcpy(cb->osha1, osha1);
688 hashcpy(cb->nsha1, nsha1);
689 if (cb->cnt > 0)
690 cb->cnt--;
691 return 0;
692}
693
694static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
695 const char *email, unsigned long timestamp,
696 int tz, const char *message, void *cb_data)
697{
698 struct read_ref_at_cb *cb = cb_data;
699
700 if (cb->msg)
701 *cb->msg = xstrdup(message);
702 if (cb->cutoff_time)
703 *cb->cutoff_time = timestamp;
704 if (cb->cutoff_tz)
705 *cb->cutoff_tz = tz;
706 if (cb->cutoff_cnt)
707 *cb->cutoff_cnt = cb->reccnt;
708 hashcpy(cb->sha1, osha1);
709 if (is_null_sha1(cb->sha1))
710 hashcpy(cb->sha1, nsha1);
711 /* We just want the first entry */
712 return 1;
16d7cc90
JH
713}
714
c41a87dd 715int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
dfefa935
MH
716 unsigned char *sha1, char **msg,
717 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
d556fae2 718{
4207ed28 719 struct read_ref_at_cb cb;
d556fae2 720
4207ed28
RS
721 memset(&cb, 0, sizeof(cb));
722 cb.refname = refname;
723 cb.at_time = at_time;
724 cb.cnt = cnt;
725 cb.msg = msg;
726 cb.cutoff_time = cutoff_time;
727 cb.cutoff_tz = cutoff_tz;
728 cb.cutoff_cnt = cutoff_cnt;
729 cb.sha1 = sha1;
730
731 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
732
c41a87dd
DA
733 if (!cb.reccnt) {
734 if (flags & GET_SHA1_QUIETLY)
735 exit(128);
736 else
737 die("Log for %s is empty.", refname);
738 }
4207ed28
RS
739 if (cb.found_it)
740 return 0;
741
742 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
d556fae2 743
16d7cc90 744 return 1;
d556fae2 745}
2ff81662 746
93a644ea 747struct ref_transaction *ref_transaction_begin(struct strbuf *err)
caa4046c 748{
5a603b04
JN
749 assert(err);
750
caa4046c
MH
751 return xcalloc(1, sizeof(struct ref_transaction));
752}
753
026bd1d3 754void ref_transaction_free(struct ref_transaction *transaction)
caa4046c
MH
755{
756 int i;
757
1b07255c
RS
758 if (!transaction)
759 return;
760
db7516ab
RS
761 for (i = 0; i < transaction->nr; i++) {
762 free(transaction->updates[i]->msg);
88615910 763 free(transaction->updates[i]);
db7516ab 764 }
caa4046c
MH
765 free(transaction->updates);
766 free(transaction);
767}
768
caa4046c
MH
769static struct ref_update *add_update(struct ref_transaction *transaction,
770 const char *refname)
771{
96ffc06f
JK
772 struct ref_update *update;
773 FLEX_ALLOC_STR(update, refname, refname);
caa4046c
MH
774 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
775 transaction->updates[transaction->nr++] = update;
776 return update;
777}
778
8e34800e
RS
779int ref_transaction_update(struct ref_transaction *transaction,
780 const char *refname,
781 const unsigned char *new_sha1,
782 const unsigned char *old_sha1,
1d147bdf 783 unsigned int flags, const char *msg,
8e34800e 784 struct strbuf *err)
caa4046c 785{
8e34800e 786 struct ref_update *update;
caa4046c 787
5a603b04
JN
788 assert(err);
789
2bdc785f
RS
790 if (transaction->state != REF_TRANSACTION_OPEN)
791 die("BUG: update called for transaction that is not open");
792
c52ce248
MH
793 if ((flags & REF_ISPRUNING) && !(flags & REF_NODEREF))
794 die("BUG: REF_ISPRUNING set without REF_NODEREF");
795
16180334 796 if (new_sha1 && !is_null_sha1(new_sha1) &&
d0f810f0 797 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
0568c8e9 798 strbuf_addf(err, "refusing to update ref with bad name '%s'",
d0f810f0
RS
799 refname);
800 return -1;
801 }
802
8e34800e 803 update = add_update(transaction, refname);
16180334
MH
804 if (new_sha1) {
805 hashcpy(update->new_sha1, new_sha1);
806 flags |= REF_HAVE_NEW;
807 }
1d147bdf 808 if (old_sha1) {
caa4046c 809 hashcpy(update->old_sha1, old_sha1);
8df4e511
MH
810 flags |= REF_HAVE_OLD;
811 }
812 update->flags = flags;
db7516ab
RS
813 if (msg)
814 update->msg = xstrdup(msg);
8e34800e 815 return 0;
caa4046c
MH
816}
817
b416af5b
RS
818int ref_transaction_create(struct ref_transaction *transaction,
819 const char *refname,
820 const unsigned char *new_sha1,
fec14ec3 821 unsigned int flags, const char *msg,
b416af5b 822 struct strbuf *err)
caa4046c 823{
f04c5b55
MH
824 if (!new_sha1 || is_null_sha1(new_sha1))
825 die("BUG: create called without valid new_sha1");
bc9f2925 826 return ref_transaction_update(transaction, refname, new_sha1,
1d147bdf 827 null_sha1, flags, msg, err);
caa4046c
MH
828}
829
8c8bdc0d
RS
830int ref_transaction_delete(struct ref_transaction *transaction,
831 const char *refname,
832 const unsigned char *old_sha1,
fb5a6bb6 833 unsigned int flags, const char *msg,
8c8bdc0d 834 struct strbuf *err)
caa4046c 835{
60294596
MH
836 if (old_sha1 && is_null_sha1(old_sha1))
837 die("BUG: delete called with old_sha1 set to zeros");
1d147bdf 838 return ref_transaction_update(transaction, refname,
fb5a6bb6 839 null_sha1, old_sha1,
1d147bdf 840 flags, msg, err);
caa4046c
MH
841}
842
16180334
MH
843int ref_transaction_verify(struct ref_transaction *transaction,
844 const char *refname,
845 const unsigned char *old_sha1,
846 unsigned int flags,
847 struct strbuf *err)
848{
849 if (!old_sha1)
850 die("BUG: verify called with old_sha1 set to NULL");
851 return ref_transaction_update(transaction, refname,
852 NULL, old_sha1,
853 flags, NULL, err);
854}
855
4b7b520b
MH
856int update_ref(const char *msg, const char *refname,
857 const unsigned char *new_sha1, const unsigned char *old_sha1,
fec14ec3 858 unsigned int flags, enum action_on_err onerr)
4738a333 859{
74ec19d4 860 struct ref_transaction *t = NULL;
b4d75ac1 861 struct strbuf err = STRBUF_INIT;
74ec19d4 862 int ret = 0;
b4d75ac1 863
74ec19d4
DT
864 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
865 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
866 } else {
867 t = ref_transaction_begin(&err);
868 if (!t ||
869 ref_transaction_update(t, refname, new_sha1, old_sha1,
870 flags, msg, &err) ||
871 ref_transaction_commit(t, &err)) {
872 ret = 1;
873 ref_transaction_free(t);
874 }
875 }
876 if (ret) {
b4d75ac1
RS
877 const char *str = "update_ref failed for ref '%s': %s";
878
b4d75ac1
RS
879 switch (onerr) {
880 case UPDATE_REFS_MSG_ON_ERR:
881 error(str, refname, err.buf);
882 break;
883 case UPDATE_REFS_DIE_ON_ERR:
884 die(str, refname, err.buf);
885 break;
886 case UPDATE_REFS_QUIET_ON_ERR:
887 break;
888 }
889 strbuf_release(&err);
4738a333 890 return 1;
b4d75ac1
RS
891 }
892 strbuf_release(&err);
74ec19d4
DT
893 if (t)
894 ref_transaction_free(t);
b4d75ac1 895 return 0;
4738a333
BK
896}
897
dfefa935 898char *shorten_unambiguous_ref(const char *refname, int strict)
7c2b3029
JK
899{
900 int i;
901 static char **scanf_fmts;
902 static int nr_rules;
903 char *short_name;
904
7c2b3029 905 if (!nr_rules) {
4346663a
MH
906 /*
907 * Pre-generate scanf formats from ref_rev_parse_rules[].
908 * Generate a format suitable for scanf from a
909 * ref_rev_parse_rules rule by interpolating "%s" at the
910 * location of the "%.*s".
911 */
7c2b3029 912 size_t total_len = 0;
84d5633f 913 size_t offset = 0;
7c2b3029
JK
914
915 /* the rule list is NULL terminated, count them first */
a4165851 916 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
7902fe03
MH
917 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
918 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
7c2b3029 919
50a6c8ef 920 scanf_fmts = xmalloc(st_add(st_mult(nr_rules, sizeof(char *)), total_len));
7c2b3029 921
84d5633f 922 offset = 0;
7c2b3029 923 for (i = 0; i < nr_rules; i++) {
4346663a 924 assert(offset < total_len);
84d5633f 925 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4346663a
MH
926 offset += snprintf(scanf_fmts[i], total_len - offset,
927 ref_rev_parse_rules[i], 2, "%s") + 1;
7c2b3029
JK
928 }
929 }
930
931 /* bail out if there are no rules */
932 if (!nr_rules)
dfefa935 933 return xstrdup(refname);
7c2b3029 934
dfefa935
MH
935 /* buffer for scanf result, at most refname must fit */
936 short_name = xstrdup(refname);
7c2b3029
JK
937
938 /* skip first rule, it will always match */
939 for (i = nr_rules - 1; i > 0 ; --i) {
940 int j;
6e7b3309 941 int rules_to_fail = i;
7c2b3029
JK
942 int short_name_len;
943
dfefa935 944 if (1 != sscanf(refname, scanf_fmts[i], short_name))
7c2b3029
JK
945 continue;
946
947 short_name_len = strlen(short_name);
948
6e7b3309
BW
949 /*
950 * in strict mode, all (except the matched one) rules
951 * must fail to resolve to a valid non-ambiguous ref
952 */
953 if (strict)
954 rules_to_fail = nr_rules;
955
7c2b3029
JK
956 /*
957 * check if the short name resolves to a valid ref,
958 * but use only rules prior to the matched one
959 */
6e7b3309 960 for (j = 0; j < rules_to_fail; j++) {
7c2b3029 961 const char *rule = ref_rev_parse_rules[j];
7c2b3029
JK
962 char refname[PATH_MAX];
963
6e7b3309
BW
964 /* skip matched rule */
965 if (i == j)
966 continue;
967
7c2b3029
JK
968 /*
969 * the short name is ambiguous, if it resolves
970 * (with this previous rule) to a valid ref
971 * read_ref() returns 0 on success
972 */
973 mksnpath(refname, sizeof(refname),
974 rule, short_name_len, short_name);
c6893323 975 if (ref_exists(refname))
7c2b3029
JK
976 break;
977 }
978
979 /*
980 * short name is non-ambiguous if all previous rules
981 * haven't resolved to a valid ref
982 */
6e7b3309 983 if (j == rules_to_fail)
7c2b3029
JK
984 return short_name;
985 }
986
987 free(short_name);
dfefa935 988 return xstrdup(refname);
7c2b3029 989}
daebaa78
JH
990
991static struct string_list *hide_refs;
992
993int parse_hide_refs_config(const char *var, const char *value, const char *section)
994{
995 if (!strcmp("transfer.hiderefs", var) ||
996 /* NEEDSWORK: use parse_config_key() once both are merged */
59556548 997 (starts_with(var, section) && var[strlen(section)] == '.' &&
daebaa78
JH
998 !strcmp(var + strlen(section), ".hiderefs"))) {
999 char *ref;
1000 int len;
1001
1002 if (!value)
1003 return config_error_nonbool(var);
1004 ref = xstrdup(value);
1005 len = strlen(ref);
1006 while (len && ref[len - 1] == '/')
1007 ref[--len] = '\0';
1008 if (!hide_refs) {
1009 hide_refs = xcalloc(1, sizeof(*hide_refs));
1010 hide_refs->strdup_strings = 1;
1011 }
1012 string_list_append(hide_refs, ref);
1013 }
1014 return 0;
1015}
1016
78a766ab 1017int ref_is_hidden(const char *refname, const char *refname_full)
daebaa78 1018{
2bc31d16 1019 int i;
daebaa78
JH
1020
1021 if (!hide_refs)
1022 return 0;
2bc31d16
JK
1023 for (i = hide_refs->nr - 1; i >= 0; i--) {
1024 const char *match = hide_refs->items[i].string;
78a766ab 1025 const char *subject;
2bc31d16 1026 int neg = 0;
daebaa78 1027 int len;
2bc31d16
JK
1028
1029 if (*match == '!') {
1030 neg = 1;
1031 match++;
1032 }
1033
78a766ab
LF
1034 if (*match == '^') {
1035 subject = refname_full;
1036 match++;
1037 } else {
1038 subject = refname;
1039 }
1040
1041 /* refname can be NULL when namespaces are used. */
1042 if (!subject || !starts_with(subject, match))
daebaa78 1043 continue;
2bc31d16 1044 len = strlen(match);
78a766ab 1045 if (!subject[len] || subject[len] == '/')
2bc31d16 1046 return !neg;
daebaa78
JH
1047 }
1048 return 0;
1049}
fa5b1830 1050
0845122c
DT
1051const char *find_descendant_ref(const char *dirname,
1052 const struct string_list *extras,
1053 const struct string_list *skip)
fa5b1830 1054{
0845122c 1055 int pos;
fa5b1830 1056
0845122c
DT
1057 if (!extras)
1058 return NULL;
fa5b1830
MH
1059
1060 /*
0845122c
DT
1061 * Look at the place where dirname would be inserted into
1062 * extras. If there is an entry at that position that starts
1063 * with dirname (remember, dirname includes the trailing
1064 * slash) and is not in skip, then we have a conflict.
fa5b1830 1065 */
0845122c
DT
1066 for (pos = string_list_find_insert_index(extras, dirname, 0);
1067 pos < extras->nr; pos++) {
1068 const char *extra_refname = extras->items[pos].string;
fa5b1830 1069
0845122c
DT
1070 if (!starts_with(extra_refname, dirname))
1071 break;
1072
1073 if (!skip || !string_list_has_string(skip, extra_refname))
1074 return extra_refname;
fa5b1830 1075 }
0845122c
DT
1076 return NULL;
1077}
fa5b1830 1078
0845122c
DT
1079int rename_ref_available(const char *oldname, const char *newname)
1080{
1081 struct string_list skip = STRING_LIST_INIT_NODUP;
1082 struct strbuf err = STRBUF_INIT;
1083 int ret;
fa5b1830 1084
0845122c
DT
1085 string_list_insert(&skip, oldname);
1086 ret = !verify_refname_available(newname, NULL, &skip, &err);
1087 if (!ret)
1088 error("%s", err.buf);
1089
1090 string_list_clear(&skip, 0);
1091 strbuf_release(&err);
1092 return ret;
fa5b1830 1093}
2bf68ed5
DT
1094
1095int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1096{
1097 struct object_id oid;
1098 int flag;
1099
1100 if (submodule) {
1101 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1102 return fn("HEAD", &oid, 0, cb_data);
1103
1104 return 0;
1105 }
1106
1107 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1108 return fn("HEAD", &oid, flag, cb_data);
1109
1110 return 0;
1111}
1112
1113int head_ref(each_ref_fn fn, void *cb_data)
1114{
1115 return head_ref_submodule(NULL, fn, cb_data);
1116}
93770590
DT
1117
1118int for_each_ref(each_ref_fn fn, void *cb_data)
1119{
1120 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1121}
1122
1123int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1124{
1125 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1126}
1127
1128int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1129{
1130 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1131}
1132
1133int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1134{
1135 unsigned int flag = 0;
1136
1137 if (broken)
1138 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1139 return do_for_each_ref(NULL, prefix, fn, 0, flag, cb_data);
1140}
1141
1142int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1143 each_ref_fn fn, void *cb_data)
1144{
1145 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1146}
1147
1148int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1149{
1150 return do_for_each_ref(NULL, git_replace_ref_base, fn,
1151 strlen(git_replace_ref_base), 0, cb_data);
1152}
1153
1154int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1155{
1156 struct strbuf buf = STRBUF_INIT;
1157 int ret;
1158 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1159 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1160 strbuf_release(&buf);
1161 return ret;
1162}
1163
1164int for_each_rawref(each_ref_fn fn, void *cb_data)
1165{
1166 return do_for_each_ref(NULL, "", fn, 0,
1167 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1168}
2d0663b2
DT
1169
1170/* This function needs to return a meaningful errno on failure */
1171const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1172 unsigned char *sha1, int *flags)
1173{
1174 static struct strbuf sb_refname = STRBUF_INIT;
1175 int unused_flags;
1176 int symref_count;
1177
1178 if (!flags)
1179 flags = &unused_flags;
1180
1181 *flags = 0;
1182
1183 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1184 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1185 !refname_is_safe(refname)) {
1186 errno = EINVAL;
1187 return NULL;
1188 }
1189
1190 /*
1191 * dwim_ref() uses REF_ISBROKEN to distinguish between
1192 * missing refs and refs that were present but invalid,
1193 * to complain about the latter to stderr.
1194 *
1195 * We don't know whether the ref exists, so don't set
1196 * REF_ISBROKEN yet.
1197 */
1198 *flags |= REF_BAD_NAME;
1199 }
1200
1201 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1202 unsigned int read_flags = 0;
1203
1204 if (read_raw_ref(refname, sha1, &sb_refname, &read_flags)) {
1205 *flags |= read_flags;
1206 if (errno != ENOENT || (resolve_flags & RESOLVE_REF_READING))
1207 return NULL;
1208 hashclr(sha1);
1209 if (*flags & REF_BAD_NAME)
1210 *flags |= REF_ISBROKEN;
1211 return refname;
1212 }
1213
1214 *flags |= read_flags;
1215
1216 if (!(read_flags & REF_ISSYMREF)) {
1217 if (*flags & REF_BAD_NAME) {
1218 hashclr(sha1);
1219 *flags |= REF_ISBROKEN;
1220 }
1221 return refname;
1222 }
1223
1224 refname = sb_refname.buf;
1225 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1226 hashclr(sha1);
1227 return refname;
1228 }
1229 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1230 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1231 !refname_is_safe(refname)) {
1232 errno = EINVAL;
1233 return NULL;
1234 }
1235
1236 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1237 }
1238 }
1239
1240 errno = ELOOP;
1241 return NULL;
1242}