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