ca0280f7eb6898a0fb7a5f2ccc2ec42f94860189
1/*
2 * The backend-independent part of the reference module.
3 */
4
5#include "cache.h"
6#include "lockfile.h"
7#include "refs.h"
8#include "refs/refs-internal.h"
9#include "object.h"
10#include "tag.h"
11
12/*
13 * How to handle various characters in refnames:
14 * 0: An acceptable character for refs
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
18 * 4: A bad character: ASCII control characters, and
19 * ":", "?", "[", "\", "^", "~", SP, or TAB
20 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
21 */
22static unsigned char refname_disposition[256] = {
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,
25 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
26 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
27 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
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
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:
38 *
39 * - any path component of it begins with ".", or
40 * - it has double dots "..", or
41 * - it has ASCII control characters, or
42 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
43 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
44 * - it ends with a "/", or
45 * - it ends with ".lock", or
46 * - it contains a "@{" portion
47 */
48static int check_refname_component(const char *refname, int *flags)
49{
50 const char *cp;
51 char last = '\0';
52
53 for (cp = refname; ; cp++) {
54 int ch = *cp & 255;
55 unsigned char disp = refname_disposition[ch];
56 switch (disp) {
57 case 1:
58 goto out;
59 case 2:
60 if (last == '.')
61 return -1; /* Refname contains "..". */
62 break;
63 case 3:
64 if (last == '@')
65 return -1; /* Refname contains "@{". */
66 break;
67 case 4:
68 return -1;
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;
79 }
80 last = ch;
81 }
82out:
83 if (cp == refname)
84 return 0; /* Component has zero length. */
85 if (refname[0] == '.')
86 return -1; /* Component starts with '.'. */
87 if (cp - refname >= LOCK_SUFFIX_LEN &&
88 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
89 return -1; /* Refname ends with ".lock". */
90 return cp - refname;
91}
92
93int check_refname_format(const char *refname, int flags)
94{
95 int component_len, component_count = 0;
96
97 if (!strcmp(refname, "@"))
98 /* Refname is a single character '@'. */
99 return -1;
100
101 while (1) {
102 /* We are at the start of a path component. */
103 component_len = check_refname_component(refname, &flags);
104 if (component_len <= 0)
105 return -1;
106
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
121int refname_is_safe(const char *refname)
122{
123 const char *rest;
124
125 if (skip_prefix(refname, "refs/", &rest)) {
126 char *buf;
127 int result;
128
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 */
134 buf = xmallocz(strlen(rest));
135 result = !normalize_path_copy(buf, rest);
136 free(buf);
137 return result;
138 }
139
140 do {
141 if (!isupper(*refname) && *refname != '_')
142 return 0;
143 refname++;
144 } while (*refname);
145 return 1;
146}
147
148char *resolve_refdup(const char *refname, int resolve_flags,
149 unsigned char *sha1, int *flags)
150{
151 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
152 sha1, flags));
153}
154
155/* The argument to filter_refs */
156struct ref_filter {
157 const char *pattern;
158 each_ref_fn *fn;
159 void *cb_data;
160};
161
162int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
163{
164 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
165 return 0;
166 return -1;
167}
168
169int read_ref(const char *refname, unsigned char *sha1)
170{
171 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
172}
173
174int ref_exists(const char *refname)
175{
176 unsigned char sha1[20];
177 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
178}
179
180static int filter_refs(const char *refname, const struct object_id *oid,
181 int flags, void *data)
182{
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);
188}
189
190enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
191{
192 struct object *o = lookup_unknown_object(name);
193
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 }
199
200 if (o->type != OBJ_TAG)
201 return PEEL_NON_TAG;
202
203 o = deref_tag_noverify(o);
204 if (!o)
205 return PEEL_INVALID;
206
207 hashcpy(sha1, o->oid.hash);
208 return PEEL_PEELED;
209}
210
211struct warn_if_dangling_data {
212 FILE *fp;
213 const char *refname;
214 const struct string_list *refnames;
215 const char *msg_fmt;
216};
217
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;
224
225 if (!(flags & REF_ISSYMREF))
226 return 0;
227
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 }
235
236 fprintf(d->fp, d->msg_fmt, refname);
237 fputc('\n', d->fp);
238 return 0;
239}
240
241void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
242{
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);
250}
251
252void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
253{
254 struct warn_if_dangling_data data;
255
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);
261}
262
263int for_each_tag_ref(each_ref_fn fn, void *cb_data)
264{
265 return for_each_ref_in("refs/tags/", fn, cb_data);
266}
267
268int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
269{
270 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
271}
272
273int for_each_branch_ref(each_ref_fn fn, void *cb_data)
274{
275 return for_each_ref_in("refs/heads/", fn, cb_data);
276}
277
278int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
279{
280 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
281}
282
283int for_each_remote_ref(each_ref_fn fn, void *cb_data)
284{
285 return for_each_ref_in("refs/remotes/", fn, cb_data);
286}
287
288int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
289{
290 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
291}
292
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;
299
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);
304
305 return ret;
306}
307
308int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
309 const char *prefix, void *cb_data)
310{
311 struct strbuf real_pattern = STRBUF_INIT;
312 struct ref_filter filter;
313 int ret;
314
315 if (!prefix && !starts_with(pattern, "refs/"))
316 strbuf_addstr(&real_pattern, "refs/");
317 else if (prefix)
318 strbuf_addstr(&real_pattern, prefix);
319 strbuf_addstr(&real_pattern, pattern);
320
321 if (!has_glob_specials(pattern)) {
322 /* Append implied '/' '*' if not present. */
323 strbuf_complete(&real_pattern, '/');
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
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
342const char *prettify_refname(const char *name)
343{
344 return name + (
345 starts_with(name, "refs/heads/") ? 11 :
346 starts_with(name, "refs/tags/") ? 10 :
347 starts_with(name, "refs/remotes/") ? 13 :
348 0);
349}
350
351static const char *ref_rev_parse_rules[] = {
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
361int refname_match(const char *abbrev_name, const char *full_name)
362{
363 const char **p;
364 const int abbrev_name_len = strlen(abbrev_name);
365
366 for (p = ref_rev_parse_rules; *p; p++) {
367 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
368 return 1;
369 }
370 }
371
372 return 0;
373}
374
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;
383 int ret = interpret_branch_name(*string, *len, &buf);
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);
410 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
411 this_result, &flag);
412 if (r) {
413 if (!refs_found++)
414 *ref = xstrdup(r);
415 if (!warn_ambiguous_refs)
416 break;
417 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
418 warning("ignoring dangling symref %s.", fullref);
419 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
420 warning("ignoring broken ref %s.", fullref);
421 }
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++) {
435 unsigned char hash[20];
436 char path[PATH_MAX];
437 const char *ref, *it;
438
439 mksnpath(path, sizeof(path), *p, len, str);
440 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
441 hash, NULL);
442 if (!ref)
443 continue;
444 if (reflog_exists(path))
445 it = path;
446 else if (strcmp(ref, path) && reflog_exists(ref))
447 it = ref;
448 else
449 continue;
450 if (!logs_found++) {
451 *log = xstrdup(it);
452 hashcpy(sha1, hash);
453 }
454 if (!warn_ambiguous_refs)
455 break;
456 }
457 free(last_branch);
458 return logs_found;
459}
460
461static int is_per_worktree_ref(const char *refname)
462{
463 return !strcmp(refname, "HEAD") ||
464 starts_with(refname, "refs/bisect/");
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
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];
509
510 if (read_ref(pseudoref, actual_old_sha1))
511 die("could not read ref '%s'", pseudoref);
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);
547 if (read_ref(pseudoref, actual_old_sha1))
548 die("could not read ref '%s'", pseudoref);
549 if (hashcmp(actual_old_sha1, old_sha1)) {
550 warning("Unexpected sha1 when deleting %s", pseudoref);
551 rollback_lock_file(&lock);
552 return -1;
553 }
554
555 unlink(filename);
556 rollback_lock_file(&lock);
557 } else {
558 unlink(filename);
559 }
560
561 return 0;
562}
563
564int delete_ref(const char *refname, const unsigned char *old_sha1,
565 unsigned int flags)
566{
567 struct ref_transaction *transaction;
568 struct strbuf err = STRBUF_INIT;
569
570 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
571 return delete_pseudoref(refname, old_sha1);
572
573 transaction = ref_transaction_begin(&err);
574 if (!transaction ||
575 ref_transaction_delete(transaction, refname, old_sha1,
576 flags, NULL, &err) ||
577 ref_transaction_commit(transaction, &err)) {
578 error("%s", err.buf);
579 ref_transaction_free(transaction);
580 strbuf_release(&err);
581 return 1;
582 }
583 ref_transaction_free(transaction);
584 strbuf_release(&err);
585 return 0;
586}
587
588int copy_reflog_msg(char *buf, const char *msg)
589{
590 char *cp = buf;
591 char c;
592 int wasspace = 1;
593
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;
602 }
603 while (buf < cp && isspace(cp[-1]))
604 cp--;
605 *cp++ = '\n';
606 return cp - buf;
607}
608
609int should_autocreate_reflog(const char *refname)
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
619int is_branch(const char *refname)
620{
621 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
622}
623
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.",
669 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
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,
676 DATE_MODE(RFC2822)));
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;
708}
709
710int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
711 unsigned char *sha1, char **msg,
712 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
713{
714 struct read_ref_at_cb cb;
715
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
728 if (!cb.reccnt) {
729 if (flags & GET_SHA1_QUIETLY)
730 exit(128);
731 else
732 die("Log for %s is empty.", refname);
733 }
734 if (cb.found_it)
735 return 0;
736
737 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
738
739 return 1;
740}
741
742struct ref_transaction *ref_transaction_begin(struct strbuf *err)
743{
744 assert(err);
745
746 return xcalloc(1, sizeof(struct ref_transaction));
747}
748
749void ref_transaction_free(struct ref_transaction *transaction)
750{
751 int i;
752
753 if (!transaction)
754 return;
755
756 for (i = 0; i < transaction->nr; i++) {
757 free(transaction->updates[i]->msg);
758 free(transaction->updates[i]);
759 }
760 free(transaction->updates);
761 free(transaction);
762}
763
764static struct ref_update *add_update(struct ref_transaction *transaction,
765 const char *refname)
766{
767 struct ref_update *update;
768 FLEX_ALLOC_STR(update, refname, refname);
769 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
770 transaction->updates[transaction->nr++] = update;
771 return update;
772}
773
774int ref_transaction_update(struct ref_transaction *transaction,
775 const char *refname,
776 const unsigned char *new_sha1,
777 const unsigned char *old_sha1,
778 unsigned int flags, const char *msg,
779 struct strbuf *err)
780{
781 struct ref_update *update;
782
783 assert(err);
784
785 if (transaction->state != REF_TRANSACTION_OPEN)
786 die("BUG: update called for transaction that is not open");
787
788 if (new_sha1 && !is_null_sha1(new_sha1) &&
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
795 update = add_update(transaction, refname);
796 if (new_sha1) {
797 hashcpy(update->new_sha1, new_sha1);
798 flags |= REF_HAVE_NEW;
799 }
800 if (old_sha1) {
801 hashcpy(update->old_sha1, old_sha1);
802 flags |= REF_HAVE_OLD;
803 }
804 update->flags = flags;
805 if (msg)
806 update->msg = xstrdup(msg);
807 return 0;
808}
809
810int ref_transaction_create(struct ref_transaction *transaction,
811 const char *refname,
812 const unsigned char *new_sha1,
813 unsigned int flags, const char *msg,
814 struct strbuf *err)
815{
816 if (!new_sha1 || is_null_sha1(new_sha1))
817 die("BUG: create called without valid new_sha1");
818 return ref_transaction_update(transaction, refname, new_sha1,
819 null_sha1, flags, msg, err);
820}
821
822int ref_transaction_delete(struct ref_transaction *transaction,
823 const char *refname,
824 const unsigned char *old_sha1,
825 unsigned int flags, const char *msg,
826 struct strbuf *err)
827{
828 if (old_sha1 && is_null_sha1(old_sha1))
829 die("BUG: delete called with old_sha1 set to zeros");
830 return ref_transaction_update(transaction, refname,
831 null_sha1, old_sha1,
832 flags, msg, err);
833}
834
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
848int update_ref(const char *msg, const char *refname,
849 const unsigned char *new_sha1, const unsigned char *old_sha1,
850 unsigned int flags, enum action_on_err onerr)
851{
852 struct ref_transaction *t = NULL;
853 struct strbuf err = STRBUF_INIT;
854 int ret = 0;
855
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) {
869 const char *str = "update_ref failed for ref '%s': %s";
870
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);
882 return 1;
883 }
884 strbuf_release(&err);
885 if (t)
886 ref_transaction_free(t);
887 return 0;
888}
889
890char *shorten_unambiguous_ref(const char *refname, int strict)
891{
892 int i;
893 static char **scanf_fmts;
894 static int nr_rules;
895 char *short_name;
896
897 if (!nr_rules) {
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 */
904 size_t total_len = 0;
905 size_t offset = 0;
906
907 /* the rule list is NULL terminated, count them first */
908 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
909 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
910 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
911
912 scanf_fmts = xmalloc(st_add(st_mult(nr_rules, sizeof(char *)), total_len));
913
914 offset = 0;
915 for (i = 0; i < nr_rules; i++) {
916 assert(offset < total_len);
917 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
918 offset += snprintf(scanf_fmts[i], total_len - offset,
919 ref_rev_parse_rules[i], 2, "%s") + 1;
920 }
921 }
922
923 /* bail out if there are no rules */
924 if (!nr_rules)
925 return xstrdup(refname);
926
927 /* buffer for scanf result, at most refname must fit */
928 short_name = xstrdup(refname);
929
930 /* skip first rule, it will always match */
931 for (i = nr_rules - 1; i > 0 ; --i) {
932 int j;
933 int rules_to_fail = i;
934 int short_name_len;
935
936 if (1 != sscanf(refname, scanf_fmts[i], short_name))
937 continue;
938
939 short_name_len = strlen(short_name);
940
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
948 /*
949 * check if the short name resolves to a valid ref,
950 * but use only rules prior to the matched one
951 */
952 for (j = 0; j < rules_to_fail; j++) {
953 const char *rule = ref_rev_parse_rules[j];
954 char refname[PATH_MAX];
955
956 /* skip matched rule */
957 if (i == j)
958 continue;
959
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);
967 if (ref_exists(refname))
968 break;
969 }
970
971 /*
972 * short name is non-ambiguous if all previous rules
973 * haven't resolved to a valid ref
974 */
975 if (j == rules_to_fail)
976 return short_name;
977 }
978
979 free(short_name);
980 return xstrdup(refname);
981}
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 */
989 (starts_with(var, section) && var[strlen(section)] == '.' &&
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
1009int ref_is_hidden(const char *refname, const char *refname_full)
1010{
1011 int i;
1012
1013 if (!hide_refs)
1014 return 0;
1015 for (i = hide_refs->nr - 1; i >= 0; i--) {
1016 const char *match = hide_refs->items[i].string;
1017 const char *subject;
1018 int neg = 0;
1019 int len;
1020
1021 if (*match == '!') {
1022 neg = 1;
1023 match++;
1024 }
1025
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))
1035 continue;
1036 len = strlen(match);
1037 if (!subject[len] || subject[len] == '/')
1038 return !neg;
1039 }
1040 return 0;
1041}
1042
1043const char *find_descendant_ref(const char *dirname,
1044 const struct string_list *extras,
1045 const struct string_list *skip)
1046{
1047 int pos;
1048
1049 if (!extras)
1050 return NULL;
1051
1052 /*
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.
1057 */
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;
1061
1062 if (!starts_with(extra_refname, dirname))
1063 break;
1064
1065 if (!skip || !string_list_has_string(skip, extra_refname))
1066 return extra_refname;
1067 }
1068 return NULL;
1069}
1070
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;
1076
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;
1085}
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}
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}
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}