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