Coverage Report

Created: 2026-12-01 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/refs.c
Line
Count
Source
1
/*
2
 * The backend-independent part of the reference module.
3
 */
4
5
#include "git-compat-util.h"
6
#include "abspath.h"
7
#include "advice.h"
8
#include "config.h"
9
#include "environment.h"
10
#include "strmap.h"
11
#include "gettext.h"
12
#include "hex.h"
13
#include "lockfile.h"
14
#include "iterator.h"
15
#include "refs.h"
16
#include "refs/refs-internal.h"
17
#include "hook.h"
18
#include "object-name.h"
19
#include "odb.h"
20
#include "object.h"
21
#include "path.h"
22
#include "submodule.h"
23
#include "worktree.h"
24
#include "strvec.h"
25
#include "repo-settings.h"
26
#include "setup.h"
27
#include "date.h"
28
#include "commit.h"
29
#include "wildmatch.h"
30
#include "ident.h"
31
#include "fsck.h"
32
33
/*
34
 * List of all available backends
35
 */
36
static const struct ref_storage_be *refs_backends[] = {
37
  [REF_STORAGE_FORMAT_FILES] = &refs_be_files,
38
  [REF_STORAGE_FORMAT_REFTABLE] = &refs_be_reftable,
39
};
40
41
static const struct ref_storage_be *find_ref_storage_backend(
42
  enum ref_storage_format ref_storage_format)
43
0
{
44
0
  if (ref_storage_format < ARRAY_SIZE(refs_backends))
45
0
    return refs_backends[ref_storage_format];
46
0
  return NULL;
47
0
}
48
49
enum ref_storage_format ref_storage_format_by_name(const char *name)
50
0
{
51
0
  for (unsigned int i = 0; i < ARRAY_SIZE(refs_backends); i++)
52
0
    if (refs_backends[i] && !strcmp(refs_backends[i]->name, name))
53
0
      return i;
54
0
  return REF_STORAGE_FORMAT_UNKNOWN;
55
0
}
56
57
enum ref_storage_format ref_storage_format_by_uri(const char *uri,
58
              char **payload)
59
0
{
60
0
  enum ref_storage_format format;
61
0
  const char *schema_end;
62
0
  char *name;
63
64
0
  schema_end = strstr(uri, "://");
65
0
  if (!schema_end) {
66
0
    name = xstrdup(uri);
67
0
    if (payload)
68
0
      *payload = NULL;
69
0
  } else {
70
0
    name = xstrndup(uri, schema_end - uri);
71
0
    if (payload)
72
0
      *payload = xstrdup(schema_end + 3);
73
0
  }
74
75
0
  format = ref_storage_format_by_name(name);
76
0
  free(name);
77
0
  return format;
78
0
}
79
80
const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format)
81
0
{
82
0
  const struct ref_storage_be *be = find_ref_storage_backend(ref_storage_format);
83
0
  if (!be)
84
0
    return "unknown";
85
0
  return be->name;
86
0
}
87
88
static const char *abort_by_ref_transaction_hook =
89
  N_("in '%s' phase, update aborted by the reference-transaction hook");
90
91
/*
92
 * How to handle various characters in refnames:
93
 * 0: An acceptable character for refs
94
 * 1: End-of-component
95
 * 2: ., look for a preceding . to reject .. in refs
96
 * 3: {, look for a preceding @ to reject @{ in refs
97
 * 4: A bad character: ASCII control characters, and
98
 *    ":", "?", "[", "\", "^", "~", SP, or TAB
99
 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
100
 */
101
static unsigned char refname_disposition[256] = {
102
  1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
103
  4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
104
  4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
105
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
106
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
108
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
109
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
110
};
111
112
struct ref_namespace_info ref_namespace[] = {
113
  [NAMESPACE_HEAD] = {
114
    .ref = "HEAD",
115
    .decoration = DECORATION_REF_HEAD,
116
    .exact = 1,
117
  },
118
  [NAMESPACE_BRANCHES] = {
119
    .ref = "refs/heads/",
120
    .decoration = DECORATION_REF_LOCAL,
121
  },
122
  [NAMESPACE_TAGS] = {
123
    .ref = "refs/tags/",
124
    .decoration = DECORATION_REF_TAG,
125
  },
126
  [NAMESPACE_REMOTE_REFS] = {
127
    /*
128
     * The default refspec for new remotes copies refs from
129
     * refs/heads/ on the remote into refs/remotes/<remote>/.
130
     * As such, "refs/remotes/" has special handling.
131
     */
132
    .ref = "refs/remotes/",
133
    .decoration = DECORATION_REF_REMOTE,
134
  },
135
  [NAMESPACE_STASH] = {
136
    /*
137
     * The single ref "refs/stash" stores the latest stash.
138
     * Older stashes can be found in the reflog.
139
     */
140
    .ref = "refs/stash",
141
    .exact = 1,
142
    .decoration = DECORATION_REF_STASH,
143
  },
144
  [NAMESPACE_REPLACE] = {
145
    /*
146
     * This namespace allows Git to act as if one object ID
147
     * points to the content of another. Unlike the other
148
     * ref namespaces, this one can be changed by the
149
     * GIT_REPLACE_REF_BASE environment variable. This
150
     * .namespace value will be overwritten during repository
151
     * setup.
152
     */
153
    .ref = "refs/replace/",
154
    .decoration = DECORATION_GRAFTED,
155
  },
156
  [NAMESPACE_NOTES] = {
157
    /*
158
     * The refs/notes/commit ref points to the tip of a
159
     * parallel commit history that adds metadata to commits
160
     * in the normal history. This ref can be overwritten
161
     * by the core.notesRef config variable or the
162
     * GIT_NOTES_REFS environment variable.
163
     */
164
    .ref = "refs/notes/commit",
165
    .exact = 1,
166
  },
167
  [NAMESPACE_PREFETCH] = {
168
    /*
169
     * Prefetch refs are written by the background 'fetch'
170
     * maintenance task. It allows faster foreground fetches
171
     * by advertising these previously-downloaded tips without
172
     * updating refs/remotes/ without user intervention.
173
     */
174
    .ref = "refs/prefetch/",
175
  },
176
  [NAMESPACE_REWRITTEN] = {
177
    /*
178
     * Rewritten refs are used by the 'label' command in the
179
     * sequencer. These are particularly useful during an
180
     * interactive rebase that uses the 'merge' command.
181
     */
182
    .ref = "refs/rewritten/",
183
  },
184
};
185
186
void update_ref_namespace(enum ref_namespace namespace, char *ref)
187
0
{
188
0
  struct ref_namespace_info *info = &ref_namespace[namespace];
189
0
  if (info->ref_updated)
190
0
    free((char *)info->ref);
191
0
  info->ref = ref;
192
0
  info->ref_updated = 1;
193
0
}
194
195
/*
196
 * Try to read one refname component from the front of refname.
197
 * Return the length of the component found, or -1 if the component is
198
 * not legal.  It is legal if it is something reasonable to have under
199
 * ".git/refs/"; We do not like it if:
200
 *
201
 * - it begins with ".", or
202
 * - it has double dots "..", or
203
 * - it has ASCII control characters, or
204
 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
205
 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
206
 * - it ends with a "/", or
207
 * - it ends with ".lock", or
208
 * - it contains a "@{" portion
209
 *
210
 * When sanitized is not NULL, instead of rejecting the input refname
211
 * as an error, try to come up with a usable replacement for the input
212
 * refname in it.
213
 */
214
static int check_refname_component(const char *refname, int *flags,
215
           struct strbuf *sanitized)
216
0
{
217
0
  const char *cp;
218
0
  char last = '\0';
219
0
  size_t component_start = 0; /* garbage - not a reasonable initial value */
220
221
0
  if (sanitized)
222
0
    component_start = sanitized->len;
223
224
0
  for (cp = refname; ; cp++) {
225
0
    int ch = *cp & 255;
226
0
    unsigned char disp = refname_disposition[ch];
227
228
0
    if (sanitized && disp != 1)
229
0
      strbuf_addch(sanitized, ch);
230
231
0
    switch (disp) {
232
0
    case 1:
233
0
      goto out;
234
0
    case 2:
235
0
      if (last == '.') { /* Refname contains "..". */
236
0
        if (sanitized)
237
          /* collapse ".." to single "." */
238
0
          strbuf_setlen(sanitized, sanitized->len - 1);
239
0
        else
240
0
          return -1;
241
0
      }
242
0
      break;
243
0
    case 3:
244
0
      if (last == '@') { /* Refname contains "@{". */
245
0
        if (sanitized)
246
0
          sanitized->buf[sanitized->len-1] = '-';
247
0
        else
248
0
          return -1;
249
0
      }
250
0
      break;
251
0
    case 4:
252
      /* forbidden char */
253
0
      if (sanitized)
254
0
        sanitized->buf[sanitized->len-1] = '-';
255
0
      else
256
0
        return -1;
257
0
      break;
258
0
    case 5:
259
0
      if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
260
        /* refspec can't be a pattern */
261
0
        if (sanitized)
262
0
          sanitized->buf[sanitized->len-1] = '-';
263
0
        else
264
0
          return -1;
265
0
      }
266
267
      /*
268
       * Unset the pattern flag so that we only accept
269
       * a single asterisk for one side of refspec.
270
       */
271
0
      *flags &= ~ REFNAME_REFSPEC_PATTERN;
272
0
      break;
273
0
    }
274
0
    last = ch;
275
0
  }
276
0
out:
277
0
  if (cp == refname)
278
0
    return 0; /* Component has zero length. */
279
280
0
  if (refname[0] == '.') { /* Component starts with '.'. */
281
0
    if (sanitized)
282
0
      sanitized->buf[component_start] = '-';
283
0
    else
284
0
      return -1;
285
0
  }
286
0
  if (cp - refname >= LOCK_SUFFIX_LEN &&
287
0
      !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
288
0
    if (!sanitized)
289
0
      return -1;
290
    /* Refname ends with ".lock". */
291
0
    while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
292
      /* try again in case we have .lock.lock */
293
0
    }
294
0
  }
295
0
  return cp - refname;
296
0
}
297
298
static int check_or_sanitize_refname(const char *refname, int flags,
299
             struct strbuf *sanitized)
300
0
{
301
0
  int component_len, component_count = 0;
302
303
0
  if (!strcmp(refname, "@")) {
304
    /* Refname is a single character '@'. */
305
0
    if (sanitized)
306
0
      strbuf_addch(sanitized, '-');
307
0
    else
308
0
      return -1;
309
0
  }
310
311
0
  while (1) {
312
0
    if (sanitized && sanitized->len)
313
0
      strbuf_complete(sanitized, '/');
314
315
    /* We are at the start of a path component. */
316
0
    component_len = check_refname_component(refname, &flags,
317
0
              sanitized);
318
0
    if (sanitized && component_len == 0)
319
0
      ; /* OK, omit empty component */
320
0
    else if (component_len <= 0)
321
0
      return -1;
322
323
0
    component_count++;
324
0
    if (refname[component_len] == '\0')
325
0
      break;
326
    /* Skip to next component. */
327
0
    refname += component_len + 1;
328
0
  }
329
330
0
  if (refname[component_len - 1] == '.') {
331
    /* Refname ends with '.'. */
332
0
    if (sanitized)
333
0
      ; /* omit ending dot */
334
0
    else
335
0
      return -1;
336
0
  }
337
0
  if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
338
0
    return -1; /* Refname has only one component. */
339
0
  return 0;
340
0
}
341
342
int check_refname_format(const char *refname, int flags)
343
0
{
344
0
  return check_or_sanitize_refname(refname, flags, NULL);
345
0
}
346
347
int refs_fsck_ref(struct ref_store *refs UNUSED, struct fsck_options *o,
348
      struct fsck_ref_report *report,
349
      const char *refname UNUSED, const struct object_id *oid)
350
0
{
351
0
  if (is_null_oid(oid))
352
0
    return fsck_report_ref(o, report, FSCK_MSG_BAD_REF_OID,
353
0
               "points to invalid object ID '%s'",
354
0
               oid_to_hex(oid));
355
356
0
  return 0;
357
0
}
358
359
int refs_fsck_symref(struct ref_store *refs UNUSED, struct fsck_options *o,
360
         struct fsck_ref_report *report,
361
         const char *refname, const char *target)
362
0
{
363
0
  const char *stripped_refname;
364
365
0
  parse_worktree_ref(refname, NULL, NULL, &stripped_refname);
366
367
0
  if (!strcmp(stripped_refname, "HEAD") &&
368
0
      !starts_with(target, "refs/heads/") &&
369
0
      fsck_report_ref(o, report, FSCK_MSG_BAD_HEAD_TARGET,
370
0
          "HEAD points to non-branch '%s'", target))
371
0
    return -1;
372
373
0
  if (is_root_ref(target))
374
0
    return 0;
375
376
0
  if (check_refname_format(target, 0) &&
377
0
      fsck_report_ref(o, report, FSCK_MSG_BAD_REFERENT_NAME,
378
0
          "points to invalid refname '%s'", target))
379
0
    return -1;
380
381
0
  if (!starts_with(target, "refs/") &&
382
0
      !starts_with(target, "worktrees/") &&
383
0
      fsck_report_ref(o, report, FSCK_MSG_SYMREF_TARGET_IS_NOT_A_REF,
384
0
          "points to non-ref target '%s'", target))
385
0
    return -1;
386
387
0
  return 0;
388
0
}
389
390
int refs_fsck(struct ref_store *refs, struct fsck_options *o,
391
        struct worktree *wt)
392
0
{
393
0
  if (o->verbose)
394
0
    fprintf_ln(stderr, _("Checking references consistency"));
395
396
0
  return refs->be->fsck(refs, o, wt);
397
0
}
398
399
void sanitize_refname_component(const char *refname, struct strbuf *out)
400
0
{
401
0
  if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
402
0
    BUG("sanitizing refname '%s' check returned error", refname);
403
0
}
404
405
int refname_is_safe(const char *refname)
406
0
{
407
0
  const char *rest;
408
409
0
  if (skip_prefix(refname, "refs/", &rest)) {
410
0
    char *buf;
411
0
    int result;
412
0
    size_t restlen = strlen(rest);
413
414
    /* rest must not be empty, or start or end with "/" */
415
0
    if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
416
0
      return 0;
417
418
    /*
419
     * Does the refname try to escape refs/?
420
     * For example: refs/foo/../bar is safe but refs/foo/../../bar
421
     * is not.
422
     */
423
0
    buf = xmallocz(restlen);
424
0
    result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
425
0
    free(buf);
426
0
    return result;
427
0
  }
428
429
0
  do {
430
0
    if (!isupper(*refname) && *refname != '_')
431
0
      return 0;
432
0
    refname++;
433
0
  } while (*refname);
434
0
  return 1;
435
0
}
436
437
/*
438
 * Return true if refname, which has the specified oid and flags, can
439
 * be resolved to an object in the database. If the referred-to object
440
 * does not exist, emit a warning and return false.
441
 */
442
int ref_resolves_to_object(const char *refname,
443
         struct repository *repo,
444
         const struct object_id *oid,
445
         unsigned int flags)
446
0
{
447
0
  if (flags & REF_ISBROKEN)
448
0
    return 0;
449
0
  if (!odb_has_object(repo->objects, oid,
450
0
          ODB_HAS_OBJECT_RECHECK_PACKED | ODB_HAS_OBJECT_FETCH_PROMISOR)) {
451
0
    error(_("%s does not point to a valid object!"), refname);
452
0
    return 0;
453
0
  }
454
0
  return 1;
455
0
}
456
457
char *refs_resolve_refdup(struct ref_store *refs,
458
        const char *refname, int resolve_flags,
459
        struct object_id *oid, int *flags)
460
0
{
461
0
  const char *result;
462
463
0
  result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
464
0
           oid, flags);
465
0
  return xstrdup_or_null(result);
466
0
}
467
468
/* The argument to for_each_filter_refs */
469
struct for_each_ref_filter {
470
  const char *pattern;
471
  size_t trim_prefix;
472
  refs_for_each_cb *fn;
473
  void *cb_data;
474
};
475
476
int refs_read_ref_full(struct ref_store *refs, const char *refname,
477
           int resolve_flags, struct object_id *oid, int *flags)
478
0
{
479
0
  if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
480
0
            oid, flags))
481
0
    return 0;
482
0
  return -1;
483
0
}
484
485
int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)
486
0
{
487
0
  return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);
488
0
}
489
490
int refs_ref_exists(struct ref_store *refs, const char *refname)
491
0
{
492
0
  return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
493
0
           NULL, NULL);
494
0
}
495
496
static int for_each_filter_refs(const struct reference *ref, void *data)
497
0
{
498
0
  struct for_each_ref_filter *filter = data;
499
500
0
  if (wildmatch(filter->pattern, ref->name, 0))
501
0
    return 0;
502
0
  if (filter->trim_prefix) {
503
0
    struct reference skipped = *ref;
504
0
    if (strlen(skipped.name) <= filter->trim_prefix)
505
0
      BUG("attempt to trim too many characters");
506
0
    skipped.name += filter->trim_prefix;
507
0
    return filter->fn(&skipped, filter->cb_data);
508
0
  } else {
509
0
    return filter->fn(ref, filter->cb_data);
510
0
  }
511
0
}
512
513
struct warn_if_dangling_data {
514
  struct ref_store *refs;
515
  FILE *fp;
516
  const struct string_list *refnames;
517
  const char *indent;
518
  int dry_run;
519
};
520
521
static int warn_if_dangling_symref(const struct reference *ref, void *cb_data)
522
0
{
523
0
  struct warn_if_dangling_data *d = cb_data;
524
0
  const char *resolves_to, *msg;
525
526
0
  if (!(ref->flags & REF_ISSYMREF))
527
0
    return 0;
528
529
0
  resolves_to = refs_resolve_ref_unsafe(d->refs, ref->name, 0, NULL, NULL);
530
0
  if (!resolves_to
531
0
      || !string_list_has_string(d->refnames, resolves_to)) {
532
0
    return 0;
533
0
  }
534
535
0
  msg = d->dry_run
536
0
    ? _("%s%s will become dangling after %s is deleted\n")
537
0
    : _("%s%s has become dangling after %s was deleted\n");
538
0
  fprintf(d->fp, msg, d->indent, ref->name, resolves_to);
539
0
  return 0;
540
0
}
541
542
void refs_warn_dangling_symrefs(struct ref_store *refs, FILE *fp,
543
        const char *indent, int dry_run,
544
        const struct string_list *refnames)
545
0
{
546
0
  struct warn_if_dangling_data data = {
547
0
    .refs = refs,
548
0
    .fp = fp,
549
0
    .refnames = refnames,
550
0
    .indent = indent,
551
0
    .dry_run = dry_run,
552
0
  };
553
0
  struct refs_for_each_ref_options opts = {
554
0
    .flags = REFS_FOR_EACH_INCLUDE_BROKEN,
555
0
  };
556
0
  refs_for_each_ref_ext(refs, warn_if_dangling_symref, &data, &opts);
557
0
}
558
559
int refs_for_each_tag_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
560
0
{
561
0
  struct refs_for_each_ref_options opts = {
562
0
    .prefix = "refs/tags/",
563
0
    .trim_prefix = strlen("refs/tags/"),
564
0
  };
565
0
  return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
566
0
}
567
568
int refs_for_each_branch_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
569
0
{
570
0
  struct refs_for_each_ref_options opts = {
571
0
    .prefix = "refs/heads/",
572
0
    .trim_prefix = strlen("refs/heads/"),
573
0
  };
574
0
  return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
575
0
}
576
577
int refs_for_each_remote_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
578
0
{
579
0
  struct refs_for_each_ref_options opts = {
580
0
    .prefix = "refs/remotes/",
581
0
    .trim_prefix = strlen("refs/remotes/"),
582
0
  };
583
0
  return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
584
0
}
585
586
int refs_head_ref_namespaced(struct ref_store *refs, refs_for_each_cb fn, void *cb_data)
587
0
{
588
0
  struct strbuf buf = STRBUF_INIT;
589
0
  int ret = 0;
590
0
  struct object_id oid;
591
0
  int flag;
592
593
0
  strbuf_addf(&buf, "%sHEAD", get_git_namespace());
594
0
  if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag)) {
595
0
    struct reference ref = {
596
0
      .name = buf.buf,
597
0
      .oid = &oid,
598
0
      .flags = flag,
599
0
    };
600
601
0
    ret = fn(&ref, cb_data);
602
0
  }
603
0
  strbuf_release(&buf);
604
605
0
  return ret;
606
0
}
607
608
void normalize_glob_ref(struct string_list_item *item, const char *prefix,
609
      const char *pattern)
610
0
{
611
0
  struct strbuf normalized_pattern = STRBUF_INIT;
612
613
0
  if (*pattern == '/')
614
0
    BUG("pattern must not start with '/'");
615
616
0
  if (prefix)
617
0
    strbuf_addstr(&normalized_pattern, prefix);
618
0
  else if (!starts_with(pattern, "refs/") &&
619
0
       strcmp(pattern, "HEAD"))
620
0
    strbuf_addstr(&normalized_pattern, "refs/");
621
  /*
622
   * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
623
   * MERGE_HEAD, etc.
624
   */
625
626
0
  strbuf_addstr(&normalized_pattern, pattern);
627
0
  strbuf_strip_suffix(&normalized_pattern, "/");
628
629
0
  item->string = strbuf_detach(&normalized_pattern, NULL);
630
0
  item->util = has_glob_specials(pattern) ? NULL : item->string;
631
0
  strbuf_release(&normalized_pattern);
632
0
}
633
634
const char *prettify_refname(const char *name)
635
0
{
636
0
  if (skip_prefix(name, "refs/heads/", &name) ||
637
0
      skip_prefix(name, "refs/tags/", &name) ||
638
0
      skip_prefix(name, "refs/remotes/", &name))
639
0
    ; /* nothing */
640
0
  return name;
641
0
}
642
643
static const char *ref_rev_parse_rules[] = {
644
  "%.*s",
645
  "refs/%.*s",
646
  "refs/tags/%.*s",
647
  "refs/heads/%.*s",
648
  "refs/remotes/%.*s",
649
  "refs/remotes/%.*s/HEAD",
650
  NULL
651
};
652
653
0
#define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
654
655
/*
656
 * Check that the string refname matches a rule of the form
657
 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
658
 * "foo/%.*s/baz", and return the string "bar".
659
 */
660
static const char *match_parse_rule(const char *refname, const char *rule,
661
            size_t *len)
662
0
{
663
  /*
664
   * Check that rule matches refname up to the first percent in the rule.
665
   * We can bail immediately if not, but otherwise we leave "rule" at the
666
   * %-placeholder, and "refname" at the start of the potential matched
667
   * name.
668
   */
669
0
  while (*rule != '%') {
670
0
    if (!*rule)
671
0
      BUG("rev-parse rule did not have percent");
672
0
    if (*refname++ != *rule++)
673
0
      return NULL;
674
0
  }
675
676
  /*
677
   * Check that our "%" is the expected placeholder. This assumes there
678
   * are no other percents (placeholder or quoted) in the string, but
679
   * that is sufficient for our rev-parse rules.
680
   */
681
0
  if (!skip_prefix(rule, "%.*s", &rule))
682
0
    return NULL;
683
684
  /*
685
   * And now check that our suffix (if any) matches.
686
   */
687
0
  if (!strip_suffix(refname, rule, len))
688
0
    return NULL;
689
690
0
  return refname; /* len set by strip_suffix() */
691
0
}
692
693
/*
694
 * Is it possible that the caller meant full_name with abbrev_name?
695
 * If so return a non-zero value to signal "yes"; the magnitude of
696
 * the returned value gives the precedence used for disambiguation.
697
 *
698
 * If abbrev_name cannot mean full_name, return 0.
699
 */
700
int refname_match(const char *abbrev_name, const char *full_name)
701
0
{
702
0
  const char **p;
703
0
  const size_t abbrev_name_len = strlen(abbrev_name);
704
0
  const int num_rules = NUM_REV_PARSE_RULES;
705
706
0
  for (p = ref_rev_parse_rules; *p; p++) {
707
0
    size_t short_name_len;
708
0
    const char *short_name = match_parse_rule(full_name, *p,
709
0
                &short_name_len);
710
711
0
    if (short_name && short_name_len == abbrev_name_len &&
712
0
        !memcmp(short_name, abbrev_name, abbrev_name_len))
713
0
      return &ref_rev_parse_rules[num_rules] - p;
714
0
  }
715
716
0
  return 0;
717
0
}
718
719
/*
720
 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
721
 * the results to 'prefixes'
722
 */
723
void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
724
0
{
725
0
  const char **p;
726
0
  int len = strlen(prefix);
727
728
0
  for (p = ref_rev_parse_rules; *p; p++)
729
0
    strvec_pushf(prefixes, *p, len, prefix);
730
0
}
731
732
#ifndef WITH_BREAKING_CHANGES
733
static const char default_branch_name_advice[] = N_(
734
"Using '%s' as the name for the initial branch. This default branch name\n"
735
"will change to \"main\" in Git 3.0. To configure the initial branch name\n"
736
"to use in all of your new repositories, which will suppress this warning,\n"
737
"call:\n"
738
"\n"
739
"\tgit config --global init.defaultBranch <name>\n"
740
"\n"
741
"Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
742
"'development'. The just-created branch can be renamed via this command:\n"
743
"\n"
744
"\tgit branch -m <name>\n"
745
);
746
#else
747
static const char default_branch_name_advice[] = N_(
748
"Using '%s' as the name for the initial branch since Git 3.0.\n"
749
"If you expected Git to create 'master', the just-created\n"
750
"branch can be renamed via this command:\n"
751
"\n"
752
"\tgit branch -m master\n"
753
);
754
#endif /* WITH_BREAKING_CHANGES */
755
756
char *repo_default_branch_name(struct repository *r, int quiet)
757
0
{
758
0
  const char *config_key = "init.defaultbranch";
759
0
  const char *config_display_key = "init.defaultBranch";
760
0
  char *ret = NULL, *full_ref;
761
0
  const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
762
763
0
  if (env && *env)
764
0
    ret = xstrdup(env);
765
0
  if (!ret && repo_config_get_string(r, config_key, &ret) < 0)
766
0
    die(_("could not retrieve `%s`"), config_display_key);
767
768
0
  if (!ret) {
769
#ifdef WITH_BREAKING_CHANGES
770
    ret = xstrdup("main");
771
#else
772
0
    ret = xstrdup("master");
773
0
#endif /* WITH_BREAKING_CHANGES */
774
0
    if (!quiet)
775
0
      advise_if_enabled(ADVICE_DEFAULT_BRANCH_NAME,
776
0
            _(default_branch_name_advice), ret);
777
0
  }
778
779
0
  full_ref = xstrfmt("refs/heads/%s", ret);
780
0
  if (check_refname_format(full_ref, 0))
781
0
    die(_("invalid branch name: %s = %s"), config_display_key, ret);
782
0
  free(full_ref);
783
784
0
  return ret;
785
0
}
786
787
/*
788
 * *string and *len will only be substituted, and *string returned (for
789
 * later free()ing) if the string passed in is a magic short-hand form
790
 * to name a branch.
791
 */
792
static char *substitute_branch_name(struct repository *r,
793
            const char **string, int *len,
794
            int nonfatal_dangling_mark)
795
0
{
796
0
  struct strbuf buf = STRBUF_INIT;
797
0
  struct interpret_branch_name_options options = {
798
0
    .nonfatal_dangling_mark = nonfatal_dangling_mark
799
0
  };
800
0
  int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
801
802
0
  if (ret == *len) {
803
0
    size_t size;
804
0
    *string = strbuf_detach(&buf, &size);
805
0
    *len = size;
806
0
    return (char *)*string;
807
0
  }
808
809
0
  return NULL;
810
0
}
811
812
void copy_branchname(struct repository *repo,
813
         struct strbuf *sb, const char *name,
814
         enum interpret_branch_kind allowed)
815
0
{
816
0
  int len = strlen(name);
817
0
  struct interpret_branch_name_options options = {
818
0
    .allowed = allowed
819
0
  };
820
0
  int used = repo_interpret_branch_name(repo, name, len, sb,
821
0
                &options);
822
823
0
  if (used < 0)
824
0
    used = 0;
825
0
  strbuf_add(sb, name + used, len - used);
826
0
}
827
828
int check_branch_ref(struct repository *repo, struct strbuf *sb, const char *name)
829
0
{
830
0
  if (startup_info->have_repository)
831
0
    copy_branchname(repo, sb, name, INTERPRET_BRANCH_LOCAL);
832
0
  else
833
0
    strbuf_addstr(sb, name);
834
835
  /*
836
   * This splice must be done even if we end up rejecting the
837
   * name; builtin/branch.c::copy_or_rename_branch() still wants
838
   * to see what the name expanded to so that "branch -m" can be
839
   * used as a tool to correct earlier mistakes.
840
   */
841
0
  strbuf_splice(sb, 0, 0, "refs/heads/", 11);
842
843
0
  if (*name == '-' ||
844
0
      !strcmp(sb->buf, "refs/heads/HEAD"))
845
0
    return -1;
846
847
0
  return check_refname_format(sb->buf, 0);
848
0
}
849
850
int check_tag_ref(struct strbuf *sb, const char *name)
851
0
{
852
0
  if (name[0] == '-' || !strcmp(name, "HEAD"))
853
0
    return -1;
854
855
0
  strbuf_reset(sb);
856
0
  strbuf_addf(sb, "refs/tags/%s", name);
857
858
0
  return check_refname_format(sb->buf, 0);
859
0
}
860
861
int repo_dwim_ref(struct repository *r, const char *str, int len,
862
      struct object_id *oid, char **ref, int nonfatal_dangling_mark)
863
0
{
864
0
  char *last_branch = substitute_branch_name(r, &str, &len,
865
0
               nonfatal_dangling_mark);
866
0
  int   refs_found  = expand_ref(r, str, len, oid, ref);
867
0
  free(last_branch);
868
0
  return refs_found;
869
0
}
870
871
int expand_ref(struct repository *repo, const char *str, int len,
872
         struct object_id *oid, char **ref)
873
0
{
874
0
  const char **p, *r;
875
0
  int refs_found = 0;
876
0
  struct strbuf fullref = STRBUF_INIT;
877
878
0
  *ref = NULL;
879
0
  for (p = ref_rev_parse_rules; *p; p++) {
880
0
    struct object_id oid_from_ref;
881
0
    struct object_id *this_result;
882
0
    int flag;
883
0
    struct ref_store *refs = get_main_ref_store(repo);
884
885
0
    this_result = refs_found ? &oid_from_ref : oid;
886
0
    strbuf_reset(&fullref);
887
0
    strbuf_addf(&fullref, *p, len, str);
888
0
    r = refs_resolve_ref_unsafe(refs, fullref.buf,
889
0
              RESOLVE_REF_READING,
890
0
              this_result, &flag);
891
0
    if (r) {
892
0
      if (!refs_found++)
893
0
        *ref = xstrdup(r);
894
0
      if (!repo_settings_get_warn_ambiguous_refs(repo))
895
0
        break;
896
0
    } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
897
0
      warning(_("ignoring dangling symref %s"), fullref.buf);
898
0
    } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
899
0
      warning(_("ignoring broken ref %s"), fullref.buf);
900
0
    }
901
0
  }
902
0
  strbuf_release(&fullref);
903
0
  return refs_found;
904
0
}
905
906
int repo_dwim_log(struct repository *r, const char *str, int len,
907
      struct object_id *oid, char **log)
908
0
{
909
0
  struct ref_store *refs = get_main_ref_store(r);
910
0
  char *last_branch = substitute_branch_name(r, &str, &len, 0);
911
0
  const char **p;
912
0
  int logs_found = 0;
913
0
  struct strbuf path = STRBUF_INIT;
914
915
0
  *log = NULL;
916
0
  for (p = ref_rev_parse_rules; *p; p++) {
917
0
    struct object_id hash;
918
0
    const char *ref, *it;
919
920
0
    strbuf_reset(&path);
921
0
    strbuf_addf(&path, *p, len, str);
922
0
    ref = refs_resolve_ref_unsafe(refs, path.buf,
923
0
                RESOLVE_REF_READING,
924
0
                oid ? &hash : NULL, NULL);
925
0
    if (!ref)
926
0
      continue;
927
0
    if (refs_reflog_exists(refs, path.buf))
928
0
      it = path.buf;
929
0
    else if (strcmp(ref, path.buf) &&
930
0
       refs_reflog_exists(refs, ref))
931
0
      it = ref;
932
0
    else
933
0
      continue;
934
0
    if (!logs_found++) {
935
0
      *log = xstrdup(it);
936
0
      if (oid)
937
0
        oidcpy(oid, &hash);
938
0
    }
939
0
    if (!repo_settings_get_warn_ambiguous_refs(r))
940
0
      break;
941
0
  }
942
0
  strbuf_release(&path);
943
0
  free(last_branch);
944
0
  return logs_found;
945
0
}
946
947
int is_per_worktree_ref(const char *refname)
948
0
{
949
0
  return starts_with(refname, "refs/worktree/") ||
950
0
         starts_with(refname, "refs/bisect/") ||
951
0
         starts_with(refname, "refs/rewritten/");
952
0
}
953
954
int is_pseudo_ref(const char *refname)
955
0
{
956
0
  static const char * const pseudo_refs[] = {
957
0
    "FETCH_HEAD",
958
0
    "MERGE_HEAD",
959
0
  };
960
0
  size_t i;
961
962
0
  for (i = 0; i < ARRAY_SIZE(pseudo_refs); i++)
963
0
    if (!strcmp(refname, pseudo_refs[i]))
964
0
      return 1;
965
966
0
  return 0;
967
0
}
968
969
static int is_root_ref_syntax(const char *refname)
970
0
{
971
0
  const char *c;
972
973
0
  for (c = refname; *c; c++) {
974
0
    if (!isupper(*c) && *c != '-' && *c != '_')
975
0
      return 0;
976
0
  }
977
978
0
  return 1;
979
0
}
980
981
int is_root_ref(const char *refname)
982
0
{
983
0
  static const char *const irregular_root_refs[] = {
984
0
    "HEAD",
985
0
    "AUTO_MERGE",
986
0
    "BISECT_EXPECTED_REV",
987
0
    "NOTES_MERGE_PARTIAL",
988
0
    "NOTES_MERGE_REF",
989
0
    "MERGE_AUTOSTASH",
990
0
  };
991
0
  size_t i;
992
993
0
  if (!is_root_ref_syntax(refname) ||
994
0
      is_pseudo_ref(refname))
995
0
    return 0;
996
997
0
  if (ends_with(refname, "_HEAD"))
998
0
    return 1;
999
1000
0
  for (i = 0; i < ARRAY_SIZE(irregular_root_refs); i++)
1001
0
    if (!strcmp(refname, irregular_root_refs[i]))
1002
0
      return 1;
1003
1004
0
  return 0;
1005
0
}
1006
1007
0
static int is_current_worktree_ref(const char *ref) {
1008
0
  return is_root_ref_syntax(ref) || is_per_worktree_ref(ref);
1009
0
}
1010
1011
enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
1012
            const char **worktree_name, int *worktree_name_length,
1013
            const char **bare_refname)
1014
0
{
1015
0
  const char *name_dummy;
1016
0
  int name_length_dummy;
1017
0
  const char *ref_dummy;
1018
1019
0
  if (!worktree_name)
1020
0
    worktree_name = &name_dummy;
1021
0
  if (!worktree_name_length)
1022
0
    worktree_name_length = &name_length_dummy;
1023
0
  if (!bare_refname)
1024
0
    bare_refname = &ref_dummy;
1025
1026
0
  if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
1027
0
    const char *slash = strchr(*bare_refname, '/');
1028
1029
0
    *worktree_name = *bare_refname;
1030
0
    if (!slash) {
1031
0
      *worktree_name_length = strlen(*worktree_name);
1032
1033
      /* This is an error condition, and the caller tell because the bare_refname is "" */
1034
0
      *bare_refname = *worktree_name + *worktree_name_length;
1035
0
      return REF_WORKTREE_OTHER;
1036
0
    }
1037
1038
0
    *worktree_name_length = slash - *bare_refname;
1039
0
    *bare_refname = slash + 1;
1040
1041
0
    if (is_current_worktree_ref(*bare_refname))
1042
0
      return REF_WORKTREE_OTHER;
1043
0
  }
1044
1045
0
  *worktree_name = NULL;
1046
0
  *worktree_name_length = 0;
1047
1048
0
  if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
1049
0
      && is_current_worktree_ref(*bare_refname))
1050
0
    return REF_WORKTREE_MAIN;
1051
1052
0
  *bare_refname = maybe_worktree_ref;
1053
0
  if (is_current_worktree_ref(maybe_worktree_ref))
1054
0
    return REF_WORKTREE_CURRENT;
1055
1056
0
  return REF_WORKTREE_SHARED;
1057
0
}
1058
1059
long get_files_ref_lock_timeout_ms(struct repository *repo)
1060
0
{
1061
0
  static int configured = 0;
1062
1063
  /* The default timeout is 100 ms: */
1064
0
  static int timeout_ms = 100;
1065
1066
0
  if (!configured) {
1067
0
    repo_config_get_int(repo, "core.filesreflocktimeout", &timeout_ms);
1068
0
    configured = 1;
1069
0
  }
1070
1071
0
  return timeout_ms;
1072
0
}
1073
1074
int refs_delete_ref(struct ref_store *refs, const char *msg,
1075
        const char *refname,
1076
        const struct object_id *old_oid,
1077
        unsigned int flags)
1078
0
{
1079
0
  struct ref_transaction *transaction;
1080
0
  struct strbuf err = STRBUF_INIT;
1081
1082
0
  transaction = ref_store_transaction_begin(refs, 0, &err);
1083
0
  if (!transaction ||
1084
0
      ref_transaction_delete(transaction, refname, old_oid,
1085
0
           NULL, flags, msg, &err) ||
1086
0
      ref_transaction_commit(transaction, &err)) {
1087
0
    error("%s", err.buf);
1088
0
    ref_transaction_free(transaction);
1089
0
    strbuf_release(&err);
1090
0
    return 1;
1091
0
  }
1092
0
  ref_transaction_free(transaction);
1093
0
  strbuf_release(&err);
1094
0
  return 0;
1095
0
}
1096
1097
static void copy_reflog_msg(struct strbuf *sb, const char *msg)
1098
0
{
1099
0
  char c;
1100
0
  int wasspace = 1;
1101
1102
0
  while ((c = *msg++)) {
1103
0
    if (wasspace && isspace(c))
1104
0
      continue;
1105
0
    wasspace = isspace(c);
1106
0
    if (wasspace)
1107
0
      c = ' ';
1108
0
    strbuf_addch(sb, c);
1109
0
  }
1110
0
  strbuf_rtrim(sb);
1111
0
}
1112
1113
static char *normalize_reflog_message(const char *msg)
1114
0
{
1115
0
  struct strbuf sb = STRBUF_INIT;
1116
1117
0
  if (msg && *msg)
1118
0
    copy_reflog_msg(&sb, msg);
1119
0
  return strbuf_detach(&sb, NULL);
1120
0
}
1121
1122
enum log_refs_config refs_parse_log_all_ref_updates_config(const char *value)
1123
0
{
1124
0
  if (value && !strcasecmp(value, "always"))
1125
0
    return LOG_REFS_ALWAYS;
1126
0
  else if (git_config_bool("core.logallrefupdates", value))
1127
0
    return LOG_REFS_NORMAL;
1128
0
  return LOG_REFS_NONE;
1129
0
}
1130
1131
int should_autocreate_reflog(enum log_refs_config log_all_ref_updates,
1132
           const char *refname)
1133
0
{
1134
0
  switch (log_all_ref_updates) {
1135
0
  case LOG_REFS_ALWAYS:
1136
0
    return 1;
1137
0
  case LOG_REFS_NORMAL:
1138
0
    return starts_with(refname, "refs/heads/") ||
1139
0
      starts_with(refname, "refs/remotes/") ||
1140
0
      starts_with(refname, "refs/notes/") ||
1141
0
      !strcmp(refname, "HEAD");
1142
0
  default:
1143
0
    return 0;
1144
0
  }
1145
0
}
1146
1147
int is_branch(const char *refname)
1148
0
{
1149
0
  return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
1150
0
}
1151
1152
struct read_ref_at_cb {
1153
  timestamp_t at_time;
1154
  int cnt;
1155
  int reccnt;
1156
  struct object_id *oid;
1157
  int found_it;
1158
1159
  struct object_id ooid;
1160
  struct object_id noid;
1161
  int tz;
1162
  timestamp_t date;
1163
  char **msg;
1164
  timestamp_t *cutoff_time;
1165
  int *cutoff_tz;
1166
  int *cutoff_cnt;
1167
};
1168
1169
static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
1170
    timestamp_t timestamp, int tz, const char *message)
1171
0
{
1172
0
  if (cb->msg)
1173
0
    *cb->msg = xstrdup(message);
1174
0
  if (cb->cutoff_time)
1175
0
    *cb->cutoff_time = timestamp;
1176
0
  if (cb->cutoff_tz)
1177
0
    *cb->cutoff_tz = tz;
1178
0
  if (cb->cutoff_cnt)
1179
0
    *cb->cutoff_cnt = cb->reccnt;
1180
0
}
1181
1182
static int read_ref_at_ent(const char *refname,
1183
         struct object_id *ooid, struct object_id *noid,
1184
         const char *email UNUSED,
1185
         timestamp_t timestamp, int tz,
1186
         const char *message, void *cb_data)
1187
0
{
1188
0
  struct read_ref_at_cb *cb = cb_data;
1189
1190
0
  cb->tz = tz;
1191
0
  cb->date = timestamp;
1192
1193
0
  if (timestamp <= cb->at_time || cb->cnt == 0) {
1194
0
    set_read_ref_cutoffs(cb, timestamp, tz, message);
1195
    /*
1196
     * we have not yet updated cb->[n|o]oid so they still
1197
     * hold the values for the previous record.
1198
     */
1199
0
    if (!is_null_oid(&cb->ooid)) {
1200
0
      oidcpy(cb->oid, noid);
1201
0
      if (!oideq(&cb->ooid, noid))
1202
0
        warning(_("log for ref %s has gap after %s"),
1203
0
          refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1204
0
    }
1205
0
    else if (cb->date == cb->at_time)
1206
0
      oidcpy(cb->oid, noid);
1207
0
    else if (!oideq(noid, cb->oid))
1208
0
      warning(_("log for ref %s unexpectedly ended on %s"),
1209
0
        refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1210
0
    cb->reccnt++;
1211
0
    oidcpy(&cb->ooid, ooid);
1212
0
    oidcpy(&cb->noid, noid);
1213
0
    cb->found_it = 1;
1214
0
    return 1;
1215
0
  }
1216
0
  cb->reccnt++;
1217
0
  oidcpy(&cb->ooid, ooid);
1218
0
  oidcpy(&cb->noid, noid);
1219
0
  if (cb->cnt > 0)
1220
0
    cb->cnt--;
1221
0
  return 0;
1222
0
}
1223
1224
static int read_ref_at_ent_oldest(const char *refname UNUSED,
1225
          struct object_id *ooid, struct object_id *noid,
1226
          const char *email UNUSED,
1227
          timestamp_t timestamp, int tz,
1228
          const char *message, void *cb_data)
1229
0
{
1230
0
  struct read_ref_at_cb *cb = cb_data;
1231
1232
0
  set_read_ref_cutoffs(cb, timestamp, tz, message);
1233
0
  oidcpy(cb->oid, ooid);
1234
0
  if (cb->at_time && is_null_oid(cb->oid))
1235
0
    oidcpy(cb->oid, noid);
1236
  /* We just want the first entry */
1237
0
  return 1;
1238
0
}
1239
1240
int read_ref_at(struct ref_store *refs, const char *refname,
1241
    unsigned int flags, timestamp_t at_time, int cnt,
1242
    struct object_id *oid, char **msg,
1243
    timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1244
0
{
1245
0
  struct read_ref_at_cb cb;
1246
1247
0
  memset(&cb, 0, sizeof(cb));
1248
0
  cb.at_time = at_time;
1249
0
  cb.cnt = cnt;
1250
0
  cb.msg = msg;
1251
0
  cb.cutoff_time = cutoff_time;
1252
0
  cb.cutoff_tz = cutoff_tz;
1253
0
  cb.cutoff_cnt = cutoff_cnt;
1254
0
  cb.oid = oid;
1255
1256
0
  refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1257
1258
0
  if (!cb.reccnt) {
1259
0
    if (cnt == 0) {
1260
      /*
1261
       * The caller asked for ref@{0}, and we had no entries.
1262
       * It's a bit subtle, but in practice all callers have
1263
       * prepped the "oid" field with the current value of
1264
       * the ref, which is the most reasonable fallback.
1265
       *
1266
       * We'll put dummy values into the out-parameters (so
1267
       * they're not just uninitialized garbage), and the
1268
       * caller can take our return value as a hint that
1269
       * we did not find any such reflog.
1270
       */
1271
0
      set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");
1272
0
      return 1;
1273
0
    }
1274
0
    if (flags & GET_OID_QUIETLY)
1275
0
      exit(128);
1276
0
    else
1277
0
      die(_("log for %s is empty"), refname);
1278
0
  }
1279
0
  if (cb.found_it)
1280
0
    return 0;
1281
1282
0
  refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1283
1284
0
  return 1;
1285
0
}
1286
1287
struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1288
                unsigned int flags,
1289
                struct strbuf *err)
1290
0
{
1291
0
  struct ref_transaction *tr;
1292
0
  assert(err);
1293
1294
0
  CALLOC_ARRAY(tr, 1);
1295
0
  tr->ref_store = refs;
1296
0
  tr->flags = flags;
1297
0
  string_list_init_dup(&tr->refnames);
1298
1299
0
  if (flags & REF_TRANSACTION_ALLOW_FAILURE)
1300
0
    CALLOC_ARRAY(tr->rejections, 1);
1301
1302
0
  return tr;
1303
0
}
1304
1305
void ref_transaction_free(struct ref_transaction *transaction)
1306
0
{
1307
0
  size_t i;
1308
1309
0
  if (!transaction)
1310
0
    return;
1311
1312
0
  switch (transaction->state) {
1313
0
  case REF_TRANSACTION_OPEN:
1314
0
  case REF_TRANSACTION_CLOSED:
1315
    /* OK */
1316
0
    break;
1317
0
  case REF_TRANSACTION_PREPARED:
1318
0
    BUG("free called on a prepared reference transaction");
1319
0
    break;
1320
0
  default:
1321
0
    BUG("unexpected reference transaction state");
1322
0
    break;
1323
0
  }
1324
1325
0
  for (i = 0; i < transaction->nr; i++) {
1326
0
    free(transaction->updates[i]->msg);
1327
0
    free(transaction->updates[i]->committer_info);
1328
0
    free((char *)transaction->updates[i]->new_target);
1329
0
    free((char *)transaction->updates[i]->old_target);
1330
0
    free((char *)transaction->updates[i]->rejection_details);
1331
0
    free(transaction->updates[i]);
1332
0
  }
1333
1334
0
  if (transaction->rejections)
1335
0
    free(transaction->rejections->update_indices);
1336
0
  free(transaction->rejections);
1337
1338
0
  string_list_clear(&transaction->refnames, 0);
1339
0
  free(transaction->updates);
1340
0
  free(transaction);
1341
0
}
1342
1343
int ref_transaction_maybe_set_rejected(struct ref_transaction *transaction,
1344
               size_t update_idx,
1345
               enum ref_transaction_error err,
1346
               struct strbuf *details)
1347
0
{
1348
0
  if (update_idx >= transaction->nr)
1349
0
    BUG("trying to set rejection on invalid update index");
1350
1351
0
  if (!(transaction->flags & REF_TRANSACTION_ALLOW_FAILURE))
1352
0
    return 0;
1353
1354
0
  if (!transaction->rejections)
1355
0
    BUG("transaction not initialized with failure support");
1356
1357
  /*
1358
   * Don't accept generic errors, since these errors are not user
1359
   * input related.
1360
   */
1361
0
  if (err == REF_TRANSACTION_ERROR_GENERIC)
1362
0
    return 0;
1363
1364
  /*
1365
   * Rejected refnames shouldn't be considered in the availability
1366
   * checks, so remove them from the list.
1367
   */
1368
0
  string_list_remove(&transaction->refnames,
1369
0
         transaction->updates[update_idx]->refname, 0);
1370
1371
0
  transaction->updates[update_idx]->rejection_err = err;
1372
0
  transaction->updates[update_idx]->rejection_details = strbuf_detach(details, NULL);
1373
0
  ALLOC_GROW(transaction->rejections->update_indices,
1374
0
       transaction->rejections->nr + 1,
1375
0
       transaction->rejections->alloc);
1376
0
  transaction->rejections->update_indices[transaction->rejections->nr++] = update_idx;
1377
1378
0
  return 1;
1379
0
}
1380
1381
struct ref_update *ref_transaction_add_update(
1382
    struct ref_transaction *transaction,
1383
    const char *refname, unsigned int flags,
1384
    const struct object_id *new_oid,
1385
    const struct object_id *old_oid,
1386
    const struct object_id *peeled,
1387
    const char *new_target, const char *old_target,
1388
    const char *committer_info,
1389
    const char *msg)
1390
0
{
1391
0
  struct string_list_item *item;
1392
0
  struct ref_update *update;
1393
1394
0
  if (transaction->state != REF_TRANSACTION_OPEN)
1395
0
    BUG("update called for transaction that is not open");
1396
1397
0
  if (old_oid && old_target)
1398
0
    BUG("only one of old_oid and old_target should be non NULL");
1399
0
  if (new_oid && new_target)
1400
0
    BUG("only one of new_oid and new_target should be non NULL");
1401
1402
0
  FLEX_ALLOC_STR(update, refname, refname);
1403
0
  ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1404
0
  transaction->updates[transaction->nr++] = update;
1405
1406
0
  update->flags = flags;
1407
0
  update->rejection_err = 0;
1408
1409
0
  update->new_target = xstrdup_or_null(new_target);
1410
0
  update->old_target = xstrdup_or_null(old_target);
1411
0
  if ((flags & REF_HAVE_NEW) && new_oid)
1412
0
    oidcpy(&update->new_oid, new_oid);
1413
0
  if ((flags & REF_HAVE_OLD) && old_oid)
1414
0
    oidcpy(&update->old_oid, old_oid);
1415
0
  if (!(flags & REF_SKIP_CREATE_REFLOG)) {
1416
0
    update->committer_info = xstrdup_or_null(committer_info);
1417
0
    update->msg = normalize_reflog_message(msg);
1418
0
  }
1419
0
  if (flags & REF_HAVE_PEELED)
1420
0
    oidcpy(&update->peeled, peeled);
1421
1422
  /*
1423
   * This list is generally used by the backends to avoid duplicates.
1424
   * But we do support multiple log updates for a given refname within
1425
   * a single transaction.
1426
   */
1427
0
  if (!(update->flags & REF_LOG_ONLY)) {
1428
0
    item = string_list_append(&transaction->refnames, refname);
1429
0
    item->util = update;
1430
0
  }
1431
1432
0
  return update;
1433
0
}
1434
1435
static int transaction_refname_valid(const char *refname,
1436
             const struct object_id *new_oid,
1437
             unsigned int flags, struct strbuf *err)
1438
0
{
1439
0
  if (flags & REF_SKIP_REFNAME_VERIFICATION)
1440
0
    return 1;
1441
1442
0
  if (is_pseudo_ref(refname)) {
1443
0
    const char *refusal_msg;
1444
0
    if (flags & REF_LOG_ONLY)
1445
0
      refusal_msg = _("refusing to update reflog for pseudoref '%s'");
1446
0
    else
1447
0
      refusal_msg = _("refusing to update pseudoref '%s'");
1448
0
    strbuf_addf(err, refusal_msg, refname);
1449
0
    return 0;
1450
0
  } else if ((new_oid && !is_null_oid(new_oid)) ?
1451
0
     check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1452
0
     !refname_is_safe(refname)) {
1453
0
    const char *refusal_msg;
1454
0
    if (flags & REF_LOG_ONLY)
1455
0
      refusal_msg = _("refusing to update reflog with bad name '%s'");
1456
0
    else
1457
0
      refusal_msg = _("refusing to update ref with bad name '%s'");
1458
0
    strbuf_addf(err, refusal_msg, refname);
1459
0
    return 0;
1460
0
  }
1461
1462
0
  return 1;
1463
0
}
1464
1465
enum ref_transaction_error ref_transaction_update(struct ref_transaction *transaction,
1466
              const char *refname,
1467
              const struct object_id *new_oid,
1468
              const struct object_id *old_oid,
1469
              const char *new_target,
1470
              const char *old_target,
1471
              unsigned int flags, const char *msg,
1472
              struct strbuf *err)
1473
0
{
1474
0
  struct object_id peeled;
1475
1476
0
  assert(err);
1477
1478
0
  if ((flags & REF_FORCE_CREATE_REFLOG) &&
1479
0
      (flags & REF_SKIP_CREATE_REFLOG)) {
1480
0
    strbuf_addstr(err, _("refusing to force and skip creation of reflog"));
1481
0
    return REF_TRANSACTION_ERROR_GENERIC;
1482
0
  }
1483
1484
0
  if (!transaction_refname_valid(refname, new_oid, flags, err))
1485
0
    return REF_TRANSACTION_ERROR_GENERIC;
1486
1487
0
  if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1488
0
    BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1489
1490
  /*
1491
   * Clear flags outside the allowed set; this should be a noop because
1492
   * of the BUG() check above, but it works around a -Wnonnull warning
1493
   * with some versions of "gcc -O3".
1494
   */
1495
0
  flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1496
1497
0
  flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1498
0
  flags |= (new_target ? REF_HAVE_NEW : 0) | (old_target ? REF_HAVE_OLD : 0);
1499
1500
0
  if ((flags & REF_HAVE_NEW) && !new_target && !is_null_oid(new_oid) &&
1501
0
      !(flags & REF_SKIP_OID_VERIFICATION) && !(flags & REF_LOG_ONLY)) {
1502
0
    struct object *o = parse_object(transaction->ref_store->repo, new_oid);
1503
1504
0
    if (!o) {
1505
0
      strbuf_addf(err,
1506
0
            _("trying to write ref '%s' with nonexistent object %s"),
1507
0
            refname, oid_to_hex(new_oid));
1508
0
      return REF_TRANSACTION_ERROR_INVALID_NEW_VALUE;
1509
0
    }
1510
1511
0
    if (o->type != OBJ_COMMIT && is_branch(refname)) {
1512
0
      strbuf_addf(err, _("trying to write non-commit object %s to branch '%s'"),
1513
0
            oid_to_hex(new_oid), refname);
1514
0
      return REF_TRANSACTION_ERROR_INVALID_NEW_VALUE;
1515
0
    }
1516
1517
0
    if (o->type == OBJ_TAG) {
1518
0
      if (!peel_object(transaction->ref_store->repo, new_oid, &peeled,
1519
0
           PEEL_OBJECT_VERIFY_TAGGED_OBJECT_TYPE))
1520
0
        flags |= REF_HAVE_PEELED;
1521
0
    }
1522
0
  }
1523
1524
0
  ref_transaction_add_update(transaction, refname, flags,
1525
0
           new_oid, old_oid, &peeled, new_target,
1526
0
           old_target, NULL, msg);
1527
1528
0
  return 0;
1529
0
}
1530
1531
int ref_transaction_update_reflog(struct ref_transaction *transaction,
1532
          const char *refname,
1533
          const struct object_id *new_oid,
1534
          const struct object_id *old_oid,
1535
          const char *committer_info,
1536
          const char *msg,
1537
          uint64_t index,
1538
          struct strbuf *err)
1539
0
{
1540
0
  struct ref_update *update;
1541
0
  unsigned int flags;
1542
1543
0
  assert(err);
1544
1545
0
  flags = REF_HAVE_OLD | REF_HAVE_NEW | REF_LOG_ONLY | REF_FORCE_CREATE_REFLOG | REF_NO_DEREF |
1546
0
    REF_LOG_USE_PROVIDED_OIDS;
1547
1548
0
  if (!transaction_refname_valid(refname, new_oid, flags, err))
1549
0
    return -1;
1550
1551
0
  update = ref_transaction_add_update(transaction, refname, flags,
1552
0
              new_oid, old_oid, NULL, NULL, NULL,
1553
0
              committer_info, msg);
1554
0
  update->index = index;
1555
1556
  /*
1557
   * Reference backends may need to know the max index to optimize
1558
   * their writes. So we store the max_index on the transaction level.
1559
   */
1560
0
  if (index > transaction->max_index)
1561
0
    transaction->max_index = index;
1562
1563
0
  return 0;
1564
0
}
1565
1566
int ref_transaction_create(struct ref_transaction *transaction,
1567
         const char *refname,
1568
         const struct object_id *new_oid,
1569
         const char *new_target,
1570
         unsigned int flags, const char *msg,
1571
         struct strbuf *err)
1572
0
{
1573
0
  if (new_oid && new_target)
1574
0
    BUG("create called with both new_oid and new_target set");
1575
0
  if ((!new_oid || is_null_oid(new_oid)) && !new_target) {
1576
0
    strbuf_addf(err, "'%s' has neither a valid OID nor a target", refname);
1577
0
    return 1;
1578
0
  }
1579
0
  return ref_transaction_update(transaction, refname, new_oid,
1580
0
              null_oid(transaction->ref_store->repo->hash_algo), new_target, NULL, flags,
1581
0
              msg, err);
1582
0
}
1583
1584
int ref_transaction_delete(struct ref_transaction *transaction,
1585
         const char *refname,
1586
         const struct object_id *old_oid,
1587
         const char *old_target,
1588
         unsigned int flags,
1589
         const char *msg,
1590
         struct strbuf *err)
1591
0
{
1592
0
  if (old_oid && is_null_oid(old_oid))
1593
0
    BUG("delete called with old_oid set to zeros");
1594
0
  if (old_oid && old_target)
1595
0
    BUG("delete called with both old_oid and old_target set");
1596
0
  if (old_target && !(flags & REF_NO_DEREF))
1597
0
    BUG("delete cannot operate on symrefs with deref mode");
1598
0
  return ref_transaction_update(transaction, refname,
1599
0
              null_oid(transaction->ref_store->repo->hash_algo), old_oid,
1600
0
              NULL, old_target, flags,
1601
0
              msg, err);
1602
0
}
1603
1604
int ref_transaction_verify(struct ref_transaction *transaction,
1605
         const char *refname,
1606
         const struct object_id *old_oid,
1607
         const char *old_target,
1608
         unsigned int flags,
1609
         struct strbuf *err)
1610
0
{
1611
0
  if (!old_target && !old_oid)
1612
0
    BUG("verify called with old_oid and old_target set to NULL");
1613
0
  if (old_oid && old_target)
1614
0
    BUG("verify called with both old_oid and old_target set");
1615
0
  if (old_target && !(flags & REF_NO_DEREF))
1616
0
    BUG("verify cannot operate on symrefs with deref mode");
1617
0
  return ref_transaction_update(transaction, refname,
1618
0
              NULL, old_oid,
1619
0
              NULL, old_target,
1620
0
              flags, NULL, err);
1621
0
}
1622
1623
int refs_update_ref(struct ref_store *refs, const char *msg,
1624
        const char *refname, const struct object_id *new_oid,
1625
        const struct object_id *old_oid, unsigned int flags,
1626
        enum action_on_err onerr)
1627
0
{
1628
0
  struct ref_transaction *t = NULL;
1629
0
  struct strbuf err = STRBUF_INIT;
1630
0
  int ret = 0;
1631
1632
0
  t = ref_store_transaction_begin(refs, 0, &err);
1633
0
  if (!t ||
1634
0
      ref_transaction_update(t, refname, new_oid, old_oid, NULL, NULL,
1635
0
           flags, msg, &err) ||
1636
0
      ref_transaction_commit(t, &err)) {
1637
0
    ret = 1;
1638
0
    ref_transaction_free(t);
1639
0
  }
1640
0
  if (ret) {
1641
0
    const char *str = _("update_ref failed for ref '%s': %s");
1642
1643
0
    switch (onerr) {
1644
0
    case UPDATE_REFS_MSG_ON_ERR:
1645
0
      error(str, refname, err.buf);
1646
0
      break;
1647
0
    case UPDATE_REFS_DIE_ON_ERR:
1648
0
      die(str, refname, err.buf);
1649
0
      break;
1650
0
    case UPDATE_REFS_QUIET_ON_ERR:
1651
0
      break;
1652
0
    }
1653
0
    strbuf_release(&err);
1654
0
    return 1;
1655
0
  }
1656
0
  strbuf_release(&err);
1657
0
  if (t)
1658
0
    ref_transaction_free(t);
1659
0
  return 0;
1660
0
}
1661
1662
char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1663
           const char *refname, int strict)
1664
0
{
1665
0
  int i;
1666
0
  struct strbuf resolved_buf = STRBUF_INIT;
1667
1668
  /* skip first rule, it will always match */
1669
0
  for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1670
0
    int j;
1671
0
    int rules_to_fail = i;
1672
0
    const char *short_name;
1673
0
    size_t short_name_len;
1674
1675
0
    short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1676
0
                &short_name_len);
1677
0
    if (!short_name)
1678
0
      continue;
1679
1680
    /*
1681
     * in strict mode, all (except the matched one) rules
1682
     * must fail to resolve to a valid non-ambiguous ref
1683
     */
1684
0
    if (strict)
1685
0
      rules_to_fail = NUM_REV_PARSE_RULES;
1686
1687
    /*
1688
     * check if the short name resolves to a valid ref,
1689
     * but use only rules prior to the matched one
1690
     */
1691
0
    for (j = 0; j < rules_to_fail; j++) {
1692
0
      const char *rule = ref_rev_parse_rules[j];
1693
1694
      /* skip matched rule */
1695
0
      if (i == j)
1696
0
        continue;
1697
1698
      /*
1699
       * the short name is ambiguous, if it resolves
1700
       * (with this previous rule) to a valid ref
1701
       * read_ref() returns 0 on success
1702
       */
1703
0
      strbuf_reset(&resolved_buf);
1704
0
      strbuf_addf(&resolved_buf, rule,
1705
0
            cast_size_t_to_int(short_name_len),
1706
0
            short_name);
1707
0
      if (refs_ref_exists(refs, resolved_buf.buf))
1708
0
        break;
1709
0
    }
1710
1711
    /*
1712
     * short name is non-ambiguous if all previous rules
1713
     * haven't resolved to a valid ref
1714
     */
1715
0
    if (j == rules_to_fail) {
1716
0
      strbuf_release(&resolved_buf);
1717
0
      return xmemdupz(short_name, short_name_len);
1718
0
    }
1719
0
  }
1720
1721
0
  strbuf_release(&resolved_buf);
1722
0
  return xstrdup(refname);
1723
0
}
1724
1725
int parse_hide_refs_config(const char *var, const char *value, const char *section,
1726
         struct strvec *hide_refs)
1727
0
{
1728
0
  const char *key;
1729
0
  if (!strcmp("transfer.hiderefs", var) ||
1730
0
      (!parse_config_key(var, section, NULL, NULL, &key) &&
1731
0
       !strcmp(key, "hiderefs"))) {
1732
0
    char *ref;
1733
0
    int len;
1734
1735
0
    if (!value)
1736
0
      return config_error_nonbool(var);
1737
1738
    /* drop const to remove trailing '/' characters */
1739
0
    ref = (char *)strvec_push(hide_refs, value);
1740
0
    len = strlen(ref);
1741
0
    while (len && ref[len - 1] == '/')
1742
0
      ref[--len] = '\0';
1743
0
  }
1744
0
  return 0;
1745
0
}
1746
1747
int ref_is_hidden(const char *refname, const char *refname_full,
1748
      const struct strvec *hide_refs)
1749
0
{
1750
0
  int i;
1751
1752
0
  for (i = hide_refs->nr - 1; i >= 0; i--) {
1753
0
    const char *match = hide_refs->v[i];
1754
0
    const char *subject;
1755
0
    int neg = 0;
1756
0
    const char *p;
1757
1758
0
    if (*match == '!') {
1759
0
      neg = 1;
1760
0
      match++;
1761
0
    }
1762
1763
0
    if (*match == '^') {
1764
0
      subject = refname_full;
1765
0
      match++;
1766
0
    } else {
1767
0
      subject = refname;
1768
0
    }
1769
1770
    /* refname can be NULL when namespaces are used. */
1771
0
    if (subject &&
1772
0
        skip_prefix(subject, match, &p) &&
1773
0
        (!*p || *p == '/'))
1774
0
      return !neg;
1775
0
  }
1776
0
  return 0;
1777
0
}
1778
1779
const char **hidden_refs_to_excludes(const struct strvec *hide_refs)
1780
0
{
1781
0
  const char **pattern;
1782
0
  for (pattern = hide_refs->v; *pattern; pattern++) {
1783
    /*
1784
     * We can't feed any excludes from hidden refs config
1785
     * sections, since later rules may override previous
1786
     * ones. For example, with rules "refs/foo" and
1787
     * "!refs/foo/bar", we should show "refs/foo/bar" (and
1788
     * everything underneath it), but the earlier exclusion
1789
     * would cause us to skip all of "refs/foo".  We
1790
     * likewise don't implement the namespace stripping
1791
     * required for '^' rules.
1792
     *
1793
     * Both are possible to do, but complicated, so avoid
1794
     * populating the jump list at all if we see either of
1795
     * these patterns.
1796
     */
1797
0
    if (**pattern == '!' || **pattern == '^')
1798
0
      return NULL;
1799
0
  }
1800
0
  return hide_refs->v;
1801
0
}
1802
1803
const char **get_namespaced_exclude_patterns(const char **exclude_patterns,
1804
               const char *namespace,
1805
               struct strvec *out)
1806
0
{
1807
0
  if (!namespace || !*namespace || !exclude_patterns || !*exclude_patterns)
1808
0
    return exclude_patterns;
1809
1810
0
  for (size_t i = 0; exclude_patterns[i]; i++)
1811
0
    strvec_pushf(out, "%s%s", namespace, exclude_patterns[i]);
1812
1813
0
  return out->v;
1814
0
}
1815
1816
const char *find_descendant_ref(const char *dirname,
1817
        const struct string_list *extras,
1818
        const struct string_list *skip)
1819
0
{
1820
0
  if (!extras)
1821
0
    return NULL;
1822
1823
  /*
1824
   * Look at the place where dirname would be inserted into
1825
   * extras. If there is an entry at that position that starts
1826
   * with dirname (remember, dirname includes the trailing
1827
   * slash) and is not in skip, then we have a conflict.
1828
   */
1829
0
  for (size_t pos = string_list_find_insert_index(extras, dirname, NULL);
1830
0
       pos < extras->nr; pos++) {
1831
0
    const char *extra_refname = extras->items[pos].string;
1832
1833
0
    if (!starts_with(extra_refname, dirname))
1834
0
      break;
1835
1836
0
    if (!skip || !string_list_has_string(skip, extra_refname))
1837
0
      return extra_refname;
1838
0
  }
1839
0
  return NULL;
1840
0
}
1841
1842
int refs_head_ref(struct ref_store *refs, refs_for_each_cb fn, void *cb_data)
1843
0
{
1844
0
  struct object_id oid;
1845
0
  int flag;
1846
1847
0
  if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1848
0
            &oid, &flag)) {
1849
0
    struct reference ref = {
1850
0
      .name = "HEAD",
1851
0
      .oid = &oid,
1852
0
      .flags = flag,
1853
0
    };
1854
1855
0
    return fn(&ref, cb_data);
1856
0
  }
1857
1858
0
  return 0;
1859
0
}
1860
1861
struct ref_iterator *refs_ref_iterator_begin(
1862
    struct ref_store *refs,
1863
    const char *prefix,
1864
    const char **exclude_patterns,
1865
    int trim,
1866
    enum refs_for_each_flag flags)
1867
0
{
1868
0
  struct ref_iterator *iter;
1869
0
  struct strvec normalized_exclude_patterns = STRVEC_INIT;
1870
1871
0
  if (exclude_patterns) {
1872
0
    for (size_t i = 0; exclude_patterns[i]; i++) {
1873
0
      const char *pattern = exclude_patterns[i];
1874
0
      size_t len = strlen(pattern);
1875
0
      if (!len)
1876
0
        continue;
1877
1878
0
      if (pattern[len - 1] == '/')
1879
0
        strvec_push(&normalized_exclude_patterns, pattern);
1880
0
      else
1881
0
        strvec_pushf(&normalized_exclude_patterns, "%s/",
1882
0
               pattern);
1883
0
    }
1884
1885
0
    exclude_patterns = normalized_exclude_patterns.v;
1886
0
  }
1887
1888
0
  if (!(flags & REFS_FOR_EACH_INCLUDE_BROKEN)) {
1889
0
    static int ref_paranoia = -1;
1890
1891
0
    if (ref_paranoia < 0)
1892
0
      ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1893
0
    if (ref_paranoia) {
1894
0
      flags |= REFS_FOR_EACH_INCLUDE_BROKEN;
1895
0
      flags |= REFS_FOR_EACH_OMIT_DANGLING_SYMREFS;
1896
0
    }
1897
0
  }
1898
1899
0
  iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);
1900
  /*
1901
   * `iterator_begin()` already takes care of prefix, but we
1902
   * might need to do some trimming:
1903
   */
1904
0
  if (trim)
1905
0
    iter = prefix_ref_iterator_begin(iter, "", trim);
1906
1907
0
  strvec_clear(&normalized_exclude_patterns);
1908
1909
0
  return iter;
1910
0
}
1911
1912
int refs_for_each_ref_ext(struct ref_store *refs,
1913
        refs_for_each_cb cb, void *cb_data,
1914
        const struct refs_for_each_ref_options *opts)
1915
0
{
1916
0
  struct strvec namespaced_exclude_patterns = STRVEC_INIT;
1917
0
  struct strbuf namespaced_prefix = STRBUF_INIT;
1918
0
  struct strbuf real_pattern = STRBUF_INIT;
1919
0
  struct for_each_ref_filter filter;
1920
0
  struct ref_iterator *iter;
1921
0
  size_t trim_prefix = opts->trim_prefix;
1922
0
  const char **exclude_patterns;
1923
0
  const char *prefix;
1924
0
  int ret;
1925
1926
0
  if (!refs)
1927
0
    BUG("no ref store passed");
1928
1929
0
  if (opts->trim_prefix) {
1930
0
    size_t prefix_len;
1931
1932
0
    if (!opts->prefix)
1933
0
      BUG("trimming only allowed with a prefix");
1934
1935
0
    prefix_len = strlen(opts->prefix);
1936
0
    if (prefix_len == opts->trim_prefix && opts->prefix[prefix_len - 1] != '/')
1937
0
      BUG("ref pattern must end in a trailing slash when trimming");
1938
0
  }
1939
1940
0
  if (opts->pattern) {
1941
0
    if (!opts->prefix && !starts_with(opts->pattern, "refs/"))
1942
0
      strbuf_addstr(&real_pattern, "refs/");
1943
0
    else if (opts->prefix)
1944
0
      strbuf_addstr(&real_pattern, opts->prefix);
1945
0
    strbuf_addstr(&real_pattern, opts->pattern);
1946
1947
0
    if (!has_glob_specials(opts->pattern)) {
1948
      /* Append implied '/' '*' if not present. */
1949
0
      strbuf_complete(&real_pattern, '/');
1950
      /* No need to check for '*', there is none. */
1951
0
      strbuf_addch(&real_pattern, '*');
1952
0
    }
1953
1954
0
    filter.pattern = real_pattern.buf;
1955
0
    filter.trim_prefix = opts->trim_prefix;
1956
0
    filter.fn = cb;
1957
0
    filter.cb_data = cb_data;
1958
1959
    /*
1960
     * We need to trim the prefix in the callback function as the
1961
     * pattern is expected to match on the full refname.
1962
     */
1963
0
    trim_prefix = 0;
1964
1965
0
    cb = for_each_filter_refs;
1966
0
    cb_data = &filter;
1967
0
  }
1968
1969
0
  if (opts->namespace) {
1970
0
    strbuf_addstr(&namespaced_prefix, opts->namespace);
1971
0
    if (opts->prefix)
1972
0
      strbuf_addstr(&namespaced_prefix, opts->prefix);
1973
0
    else
1974
0
      strbuf_addstr(&namespaced_prefix, "refs/");
1975
1976
0
    prefix = namespaced_prefix.buf;
1977
0
    exclude_patterns = get_namespaced_exclude_patterns(opts->exclude_patterns,
1978
0
                   opts->namespace,
1979
0
                   &namespaced_exclude_patterns);
1980
0
  } else {
1981
0
    prefix = opts->prefix ? opts->prefix : "";
1982
0
    exclude_patterns = opts->exclude_patterns;
1983
0
  }
1984
1985
0
  iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns,
1986
0
               trim_prefix, opts->flags);
1987
1988
0
  ret = do_for_each_ref_iterator(iter, cb, cb_data);
1989
1990
0
  strvec_clear(&namespaced_exclude_patterns);
1991
0
  strbuf_release(&namespaced_prefix);
1992
0
  strbuf_release(&real_pattern);
1993
0
  return ret;
1994
0
}
1995
1996
int refs_for_each_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
1997
0
{
1998
0
  struct refs_for_each_ref_options opts = { 0 };
1999
0
  return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
2000
0
}
2001
2002
int refs_for_each_replace_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
2003
0
{
2004
0
  const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
2005
0
  struct refs_for_each_ref_options opts = {
2006
0
    .prefix = git_replace_ref_base,
2007
0
    .trim_prefix = strlen(git_replace_ref_base),
2008
0
    .flags = REFS_FOR_EACH_INCLUDE_BROKEN,
2009
0
  };
2010
0
  return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
2011
0
}
2012
2013
static int qsort_strcmp(const void *va, const void *vb)
2014
0
{
2015
0
  const char *a = *(const char **)va;
2016
0
  const char *b = *(const char **)vb;
2017
2018
0
  return strcmp(a, b);
2019
0
}
2020
2021
static void find_longest_prefixes_1(struct string_list *out,
2022
          struct strbuf *prefix,
2023
          const char **patterns, size_t nr)
2024
0
{
2025
0
  size_t i;
2026
2027
0
  for (i = 0; i < nr; i++) {
2028
0
    char c = patterns[i][prefix->len];
2029
0
    if (!c || is_glob_special(c)) {
2030
0
      string_list_append(out, prefix->buf);
2031
0
      return;
2032
0
    }
2033
0
  }
2034
2035
0
  i = 0;
2036
0
  while (i < nr) {
2037
0
    size_t end;
2038
2039
    /*
2040
    * Set "end" to the index of the element _after_ the last one
2041
    * in our group.
2042
    */
2043
0
    for (end = i + 1; end < nr; end++) {
2044
0
      if (patterns[i][prefix->len] != patterns[end][prefix->len])
2045
0
        break;
2046
0
    }
2047
2048
0
    strbuf_addch(prefix, patterns[i][prefix->len]);
2049
0
    find_longest_prefixes_1(out, prefix, patterns + i, end - i);
2050
0
    strbuf_setlen(prefix, prefix->len - 1);
2051
2052
0
    i = end;
2053
0
  }
2054
0
}
2055
2056
static void find_longest_prefixes(struct string_list *out,
2057
          const char **patterns)
2058
0
{
2059
0
  struct strvec sorted = STRVEC_INIT;
2060
0
  struct strbuf prefix = STRBUF_INIT;
2061
2062
0
  strvec_pushv(&sorted, patterns);
2063
0
  QSORT(sorted.v, sorted.nr, qsort_strcmp);
2064
2065
0
  find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
2066
2067
0
  strvec_clear(&sorted);
2068
0
  strbuf_release(&prefix);
2069
0
}
2070
2071
int refs_for_each_ref_in_prefixes(struct ref_store *ref_store,
2072
          const char **prefixes,
2073
          const struct refs_for_each_ref_options *opts,
2074
          refs_for_each_cb cb, void *cb_data)
2075
0
{
2076
0
  struct string_list longest_prefixes = STRING_LIST_INIT_DUP;
2077
0
  struct string_list_item *prefix;
2078
0
  int ret = 0;
2079
2080
0
  if (opts->prefix)
2081
0
    BUG("refs_for_each_ref_in_prefixes called with specific prefix");
2082
2083
0
  find_longest_prefixes(&longest_prefixes, prefixes);
2084
2085
0
  for_each_string_list_item(prefix, &longest_prefixes) {
2086
0
    struct refs_for_each_ref_options prefix_opts = *opts;
2087
0
    prefix_opts.prefix = prefix->string;
2088
2089
0
    ret = refs_for_each_ref_ext(ref_store, cb, cb_data,
2090
0
              &prefix_opts);
2091
0
    if (ret)
2092
0
      break;
2093
0
  }
2094
2095
0
  string_list_clear(&longest_prefixes, 0);
2096
0
  return ret;
2097
0
}
2098
2099
static int refs_read_special_head(struct ref_store *ref_store,
2100
          const char *refname, struct object_id *oid,
2101
          struct strbuf *referent, unsigned int *type,
2102
          int *failure_errno)
2103
0
{
2104
0
  struct strbuf full_path = STRBUF_INIT;
2105
0
  struct strbuf content = STRBUF_INIT;
2106
0
  int result = -1;
2107
0
  strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
2108
2109
0
  if (strbuf_read_file(&content, full_path.buf, 0) < 0) {
2110
0
    *failure_errno = errno;
2111
0
    goto done;
2112
0
  }
2113
2114
0
  result = parse_loose_ref_contents(ref_store->repo->hash_algo, content.buf,
2115
0
            oid, referent, type, NULL, failure_errno);
2116
2117
0
done:
2118
0
  strbuf_release(&full_path);
2119
0
  strbuf_release(&content);
2120
0
  return result;
2121
0
}
2122
2123
int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
2124
          struct object_id *oid, struct strbuf *referent,
2125
          unsigned int *type, int *failure_errno)
2126
0
{
2127
0
  assert(failure_errno);
2128
0
  if (is_pseudo_ref(refname))
2129
0
    return refs_read_special_head(ref_store, refname, oid, referent,
2130
0
                type, failure_errno);
2131
2132
0
  return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
2133
0
             type, failure_errno);
2134
0
}
2135
2136
int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
2137
         struct strbuf *referent)
2138
0
{
2139
0
  return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
2140
0
}
2141
2142
const char *refs_resolve_ref_unsafe(struct ref_store *refs,
2143
            const char *refname,
2144
            int resolve_flags,
2145
            struct object_id *oid,
2146
            int *flags)
2147
0
{
2148
0
  static struct strbuf sb_refname = STRBUF_INIT;
2149
0
  struct object_id unused_oid;
2150
0
  int unused_flags;
2151
0
  int symref_count;
2152
2153
0
  if (!oid)
2154
0
    oid = &unused_oid;
2155
0
  if (!flags)
2156
0
    flags = &unused_flags;
2157
2158
0
  *flags = 0;
2159
2160
0
  if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
2161
0
    if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
2162
0
        !refname_is_safe(refname))
2163
0
      return NULL;
2164
2165
    /*
2166
     * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
2167
     * missing refs and refs that were present but invalid,
2168
     * to complain about the latter to stderr.
2169
     *
2170
     * We don't know whether the ref exists, so don't set
2171
     * REF_ISBROKEN yet.
2172
     */
2173
0
    *flags |= REF_BAD_NAME;
2174
0
  }
2175
2176
0
  for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
2177
0
    unsigned int read_flags = 0;
2178
0
    int failure_errno;
2179
2180
0
    if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
2181
0
              &read_flags, &failure_errno)) {
2182
0
      *flags |= read_flags;
2183
2184
      /* In reading mode, refs must eventually resolve */
2185
0
      if (resolve_flags & RESOLVE_REF_READING)
2186
0
        return NULL;
2187
2188
      /*
2189
       * Otherwise a missing ref is OK. But the files backend
2190
       * may show errors besides ENOENT if there are
2191
       * similarly-named refs.
2192
       */
2193
0
      if (failure_errno != ENOENT &&
2194
0
          failure_errno != EISDIR &&
2195
0
          failure_errno != ENOTDIR)
2196
0
        return NULL;
2197
2198
0
      oidclr(oid, refs->repo->hash_algo);
2199
0
      if (*flags & REF_BAD_NAME)
2200
0
        *flags |= REF_ISBROKEN;
2201
0
      return refname;
2202
0
    }
2203
2204
0
    *flags |= read_flags;
2205
2206
0
    if (!(read_flags & REF_ISSYMREF)) {
2207
0
      if (*flags & REF_BAD_NAME) {
2208
0
        oidclr(oid, refs->repo->hash_algo);
2209
0
        *flags |= REF_ISBROKEN;
2210
0
      }
2211
0
      return refname;
2212
0
    }
2213
2214
0
    refname = sb_refname.buf;
2215
0
    if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
2216
0
      oidclr(oid, refs->repo->hash_algo);
2217
0
      return refname;
2218
0
    }
2219
0
    if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
2220
0
      if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
2221
0
          !refname_is_safe(refname))
2222
0
        return NULL;
2223
2224
0
      *flags |= REF_ISBROKEN | REF_BAD_NAME;
2225
0
    }
2226
0
  }
2227
2228
0
  return NULL;
2229
0
}
2230
2231
void refs_create_refdir_stubs(struct repository *repo, const char *refdir,
2232
            const char *refs_heads_content)
2233
0
{
2234
0
  struct strbuf path = STRBUF_INIT;
2235
2236
0
  strbuf_addf(&path, "%s/HEAD", refdir);
2237
0
  write_file(path.buf, "ref: refs/heads/.invalid");
2238
0
  adjust_shared_perm(repo, path.buf);
2239
2240
0
  strbuf_reset(&path);
2241
0
  strbuf_addf(&path, "%s/refs", refdir);
2242
0
  safe_create_dir(repo, path.buf, 1);
2243
2244
0
  if (refs_heads_content) {
2245
0
    strbuf_reset(&path);
2246
0
    strbuf_addf(&path, "%s/refs/heads", refdir);
2247
0
    write_file(path.buf, "%s", refs_heads_content);
2248
0
    adjust_shared_perm(repo, path.buf);
2249
0
  }
2250
2251
0
  strbuf_release(&path);
2252
0
}
2253
2254
/* backend functions */
2255
int ref_store_create_on_disk(struct ref_store *refs, int flags, struct strbuf *err)
2256
0
{
2257
0
  int ret = refs->be->create_on_disk(refs, flags, err);
2258
2259
0
  if (!ret) {
2260
    /* Creation of stubs for linked worktrees are handled in the worktree code. */
2261
0
    if (!(flags & REF_STORE_CREATE_ON_DISK_IS_WORKTREE) && refs->repo->ref_storage_payload) {
2262
0
      refs_create_refdir_stubs(refs->repo, refs->repo->gitdir,
2263
0
             "repository uses alternate refs storage");
2264
0
    } else if (ref_storage_format_by_name(refs->be->name) != REF_STORAGE_FORMAT_FILES) {
2265
0
      struct strbuf msg = STRBUF_INIT;
2266
0
      strbuf_addf(&msg, "this repository uses the %s format", refs->be->name);
2267
0
      refs_create_refdir_stubs(refs->repo, refs->gitdir, msg.buf);
2268
0
      strbuf_release(&msg);
2269
0
    }
2270
0
  }
2271
2272
0
  return ret;
2273
0
}
2274
2275
int ref_store_remove_on_disk(struct ref_store *refs, struct strbuf *err)
2276
0
{
2277
0
  int ret = refs->be->remove_on_disk(refs, err);
2278
2279
0
  if (!ret) {
2280
0
    enum ref_storage_format format = ref_storage_format_by_name(refs->be->name);
2281
0
    struct strbuf sb = STRBUF_INIT;
2282
2283
    /* Backends apart from the files backend create stubs. */
2284
0
    if (format == REF_STORAGE_FORMAT_FILES)
2285
0
      return ret;
2286
2287
    /* Alternate refs backend require stubs in the gitdir. */
2288
0
    if (refs->repo->ref_storage_payload)
2289
0
      return ret;
2290
2291
0
    strbuf_addf(&sb, "%s/HEAD", refs->gitdir);
2292
0
    if (unlink(sb.buf) < 0) {
2293
0
      strbuf_addf(err, "could not delete stub HEAD: %s",
2294
0
            strerror(errno));
2295
0
      ret = -1;
2296
0
    }
2297
0
    strbuf_reset(&sb);
2298
2299
0
    strbuf_addf(&sb, "%s/refs/heads", refs->gitdir);
2300
0
    if (unlink(sb.buf) < 0) {
2301
0
      strbuf_addf(err, "could not delete stub heads: %s",
2302
0
            strerror(errno));
2303
0
      ret = -1;
2304
0
    }
2305
0
    strbuf_reset(&sb);
2306
2307
0
    strbuf_addf(&sb, "%s/refs", refs->gitdir);
2308
0
    if (rmdir(sb.buf) < 0) {
2309
0
      strbuf_addf(err, "could not delete refs directory: %s",
2310
0
            strerror(errno));
2311
0
      ret = -1;
2312
0
    }
2313
2314
0
    strbuf_release(&sb);
2315
0
  }
2316
2317
0
  return ret;
2318
0
}
2319
2320
int repo_resolve_gitlink_ref(struct repository *r,
2321
           const char *submodule, const char *refname,
2322
           struct object_id *oid)
2323
0
{
2324
0
  struct ref_store *refs;
2325
0
  int flags;
2326
2327
0
  refs = repo_get_submodule_ref_store(r, submodule);
2328
0
  if (!refs)
2329
0
    return -1;
2330
2331
0
  if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
2332
0
      is_null_oid(oid))
2333
0
    return -1;
2334
0
  return 0;
2335
0
}
2336
2337
/*
2338
 * Look up a ref store by name. If that ref_store hasn't been
2339
 * registered yet, return NULL.
2340
 */
2341
static struct ref_store *lookup_ref_store_map(struct strmap *map,
2342
                const char *name)
2343
0
{
2344
0
  struct strmap_entry *entry;
2345
2346
0
  if (!map->map.tablesize)
2347
    /* It's initialized on demand in register_ref_store(). */
2348
0
    return NULL;
2349
2350
0
  entry = strmap_get_entry(map, name);
2351
0
  return entry ? entry->value : NULL;
2352
0
}
2353
2354
/*
2355
 * Create, record, and return a ref_store instance for the specified
2356
 * gitdir using the given ref storage format.
2357
 */
2358
static struct ref_store *ref_store_init(struct repository *repo,
2359
          enum ref_storage_format format,
2360
          const char *gitdir,
2361
          unsigned int flags)
2362
0
{
2363
0
  const struct ref_storage_be *be;
2364
0
  struct ref_store *refs;
2365
0
  struct ref_store_init_options opts = {
2366
0
    .access_flags = flags,
2367
0
  };
2368
2369
0
  be = find_ref_storage_backend(format);
2370
0
  if (!be)
2371
0
    BUG("reference backend is unknown");
2372
2373
  /*
2374
   * TODO Send in a 'struct worktree' instead of a 'gitdir', and
2375
   * allow the backend to handle how it wants to deal with worktrees.
2376
   */
2377
0
  refs = be->init(repo, repo->ref_storage_payload, gitdir, &opts);
2378
2379
0
  return refs;
2380
0
}
2381
2382
void ref_store_release(struct ref_store *ref_store)
2383
0
{
2384
0
  ref_store->be->release(ref_store);
2385
0
  free(ref_store->gitdir);
2386
0
}
2387
2388
struct ref_store *get_main_ref_store(struct repository *r)
2389
0
{
2390
0
  static bool initializing;
2391
2392
0
  if (r->refs_private)
2393
0
    return r->refs_private;
2394
2395
0
  if (!r->gitdir)
2396
0
    BUG("attempting to get main_ref_store outside of repository");
2397
0
  if (initializing)
2398
0
    BUG("initialization of main ref store is recursing");
2399
2400
0
  initializing = true;
2401
0
  r->refs_private = ref_store_init(r, r->ref_storage_format,
2402
0
           r->gitdir, REF_STORE_ALL_CAPS);
2403
0
  r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
2404
0
  initializing = false;
2405
2406
0
  return r->refs_private;
2407
0
}
2408
2409
/*
2410
 * Associate a ref store with a name. It is a fatal error to call this
2411
 * function twice for the same name.
2412
 */
2413
static void register_ref_store_map(struct strmap *map,
2414
           const char *type,
2415
           struct ref_store *refs,
2416
           const char *name)
2417
0
{
2418
0
  if (!map->map.tablesize)
2419
0
    strmap_init(map);
2420
0
  if (strmap_put(map, name, refs))
2421
0
    BUG("%s ref_store '%s' initialized twice", type, name);
2422
0
}
2423
2424
struct ref_store *repo_get_submodule_ref_store(struct repository *repo,
2425
                 const char *submodule)
2426
0
{
2427
0
  struct strbuf submodule_sb = STRBUF_INIT;
2428
0
  struct ref_store *refs;
2429
0
  char *to_free = NULL;
2430
0
  size_t len;
2431
0
  struct repository *subrepo;
2432
2433
0
  if (!submodule)
2434
0
    return NULL;
2435
2436
0
  len = strlen(submodule);
2437
0
  while (len && is_dir_sep(submodule[len - 1]))
2438
0
    len--;
2439
0
  if (!len)
2440
0
    return NULL;
2441
2442
0
  if (submodule[len])
2443
    /* We need to strip off one or more trailing slashes */
2444
0
    submodule = to_free = xmemdupz(submodule, len);
2445
2446
0
  refs = lookup_ref_store_map(&repo->submodule_ref_stores, submodule);
2447
0
  if (refs)
2448
0
    goto done;
2449
2450
0
  strbuf_addstr(&submodule_sb, submodule);
2451
0
  if (!is_nonbare_repository_dir(&submodule_sb))
2452
0
    goto done;
2453
2454
0
  if (submodule_to_gitdir(repo, &submodule_sb, submodule))
2455
0
    goto done;
2456
2457
0
  subrepo = xmalloc(sizeof(*subrepo));
2458
2459
0
  if (repo_submodule_init(subrepo, repo, submodule,
2460
0
        null_oid(repo->hash_algo))) {
2461
0
    free(subrepo);
2462
0
    goto done;
2463
0
  }
2464
0
  refs = ref_store_init(subrepo, subrepo->ref_storage_format,
2465
0
            submodule_sb.buf,
2466
0
            REF_STORE_READ | REF_STORE_ODB);
2467
0
  register_ref_store_map(&repo->submodule_ref_stores, "submodule",
2468
0
             refs, submodule);
2469
2470
0
done:
2471
0
  strbuf_release(&submodule_sb);
2472
0
  free(to_free);
2473
2474
0
  return refs;
2475
0
}
2476
2477
struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2478
0
{
2479
0
  struct ref_store *refs;
2480
0
  const char *id;
2481
2482
0
  if (wt->is_current)
2483
0
    return get_main_ref_store(wt->repo);
2484
2485
0
  id = wt->id ? wt->id : "/";
2486
0
  refs = lookup_ref_store_map(&wt->repo->worktree_ref_stores, id);
2487
0
  if (refs)
2488
0
    return refs;
2489
2490
0
  if (wt->id) {
2491
0
    struct strbuf common_path = STRBUF_INIT;
2492
0
    repo_common_path_append(wt->repo, &common_path,
2493
0
          "worktrees/%s", wt->id);
2494
0
    refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,
2495
0
              common_path.buf, REF_STORE_ALL_CAPS);
2496
0
    strbuf_release(&common_path);
2497
0
  } else {
2498
0
    refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,
2499
0
              wt->repo->commondir, REF_STORE_ALL_CAPS);
2500
0
  }
2501
2502
0
  if (refs)
2503
0
    register_ref_store_map(&wt->repo->worktree_ref_stores,
2504
0
               "worktree", refs, id);
2505
2506
0
  return refs;
2507
0
}
2508
2509
void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2510
       const char *path, const struct ref_storage_be *be)
2511
0
{
2512
0
  refs->be = be;
2513
0
  refs->repo = repo;
2514
0
  refs->gitdir = xstrdup(path);
2515
0
}
2516
2517
int refs_optimize(struct ref_store *refs, struct refs_optimize_opts *opts)
2518
0
{
2519
0
  return refs->be->optimize(refs, opts);
2520
0
}
2521
2522
int refs_optimize_required(struct ref_store *refs,
2523
         struct refs_optimize_opts *opts,
2524
         bool *required)
2525
0
{
2526
0
  return refs->be->optimize_required(refs, opts, required);
2527
0
}
2528
2529
int reference_get_peeled_oid(struct repository *repo,
2530
           const struct reference *ref,
2531
           struct object_id *peeled_oid)
2532
0
{
2533
0
  if (ref->peeled_oid) {
2534
0
    oidcpy(peeled_oid, ref->peeled_oid);
2535
0
    return 0;
2536
0
  }
2537
2538
0
  return peel_object(repo, ref->oid, peeled_oid, 0) ? -1 : 0;
2539
0
}
2540
2541
int refs_update_symref(struct ref_store *refs, const char *ref,
2542
           const char *target, const char *logmsg)
2543
0
{
2544
0
  return refs_update_symref_extended(refs, ref, target, logmsg, NULL, 0);
2545
0
}
2546
2547
int refs_update_symref_extended(struct ref_store *refs, const char *ref,
2548
           const char *target, const char *logmsg,
2549
           struct strbuf *referent, int create_only)
2550
0
{
2551
0
  struct ref_transaction *transaction;
2552
0
  struct strbuf err = STRBUF_INIT;
2553
0
  int ret = 0, prepret = 0;
2554
2555
0
  transaction = ref_store_transaction_begin(refs, 0, &err);
2556
0
  if (!transaction) {
2557
0
  error_return:
2558
0
    ret = error("%s", err.buf);
2559
0
    goto cleanup;
2560
0
  }
2561
0
  if (create_only) {
2562
0
    if (ref_transaction_create(transaction, ref, NULL, target,
2563
0
             REF_NO_DEREF, logmsg, &err))
2564
0
      goto error_return;
2565
0
    prepret = ref_transaction_prepare(transaction, &err);
2566
0
    if (prepret && prepret != REF_TRANSACTION_ERROR_CREATE_EXISTS)
2567
0
      goto error_return;
2568
0
  } else {
2569
0
    if (ref_transaction_update(transaction, ref, NULL, NULL,
2570
0
             target, NULL, REF_NO_DEREF,
2571
0
             logmsg, &err) ||
2572
0
      ref_transaction_prepare(transaction, &err))
2573
0
      goto error_return;
2574
0
  }
2575
2576
0
  if (referent && refs_read_symbolic_ref(refs, ref, referent) == NOT_A_SYMREF) {
2577
0
    struct object_id oid;
2578
0
    if (!refs_read_ref(refs, ref, &oid)) {
2579
0
      strbuf_add_oid_hex(referent, &oid);
2580
0
      ret = NOT_A_SYMREF;
2581
0
    }
2582
0
  }
2583
2584
0
  if (prepret == REF_TRANSACTION_ERROR_CREATE_EXISTS)
2585
0
    goto cleanup;
2586
2587
0
  if (ref_transaction_commit(transaction, &err))
2588
0
    goto error_return;
2589
2590
0
cleanup:
2591
0
  strbuf_release(&err);
2592
0
  if (transaction)
2593
0
    ref_transaction_free(transaction);
2594
2595
0
  return ret;
2596
0
}
2597
2598
/*
2599
 * Write an error to `err` and return a nonzero value iff the same
2600
 * refname appears multiple times in `refnames`. `refnames` must be
2601
 * sorted on entry to this function.
2602
 */
2603
static int ref_update_reject_duplicates(struct string_list *refnames,
2604
          struct strbuf *err)
2605
0
{
2606
0
  size_t i, n = refnames->nr;
2607
2608
0
  assert(err);
2609
2610
0
  for (i = 1; i < n; i++) {
2611
0
    int cmp = strcmp(refnames->items[i - 1].string,
2612
0
         refnames->items[i].string);
2613
2614
0
    if (!cmp) {
2615
0
      strbuf_addf(err,
2616
0
            _("multiple updates for ref '%s' not allowed"),
2617
0
            refnames->items[i].string);
2618
0
      return 1;
2619
0
    } else if (cmp > 0) {
2620
0
      BUG("ref_update_reject_duplicates() received unsorted list");
2621
0
    }
2622
0
  }
2623
0
  return 0;
2624
0
}
2625
2626
struct transaction_feed_cb_data {
2627
  size_t index;
2628
  struct strbuf buf;
2629
};
2630
2631
static int transaction_hook_feed_stdin(int hook_stdin_fd, void *pp_cb, void *pp_task_cb)
2632
0
{
2633
0
  struct hook_cb_data *hook_cb = pp_cb;
2634
0
  struct ref_transaction *transaction = hook_cb->options->feed_pipe_ctx;
2635
0
  struct transaction_feed_cb_data *feed_cb_data = pp_task_cb;
2636
0
  struct strbuf *buf = &feed_cb_data->buf;
2637
0
  struct ref_update *update;
2638
0
  size_t i = feed_cb_data->index++;
2639
0
  int ret;
2640
2641
0
  if (i >= transaction->nr)
2642
0
    return 1; /* No more refs to process */
2643
2644
0
  update = transaction->updates[i];
2645
2646
0
  if (update->flags & REF_LOG_ONLY)
2647
0
    return 0;
2648
2649
0
  strbuf_reset(buf);
2650
2651
0
  if (!(update->flags & REF_HAVE_OLD))
2652
0
    strbuf_addf(buf, "%s ", oid_to_hex(null_oid(transaction->ref_store->repo->hash_algo)));
2653
0
  else if (update->old_target)
2654
0
    strbuf_addf(buf, "ref:%s ", update->old_target);
2655
0
  else
2656
0
    strbuf_addf(buf, "%s ", oid_to_hex(&update->old_oid));
2657
2658
0
  if (!(update->flags & REF_HAVE_NEW))
2659
0
    strbuf_addf(buf, "%s ", oid_to_hex(null_oid(transaction->ref_store->repo->hash_algo)));
2660
0
  else if (update->new_target)
2661
0
    strbuf_addf(buf, "ref:%s ", update->new_target);
2662
0
  else
2663
0
    strbuf_addf(buf, "%s ", oid_to_hex(&update->new_oid));
2664
2665
0
  strbuf_addf(buf, "%s\n", update->refname);
2666
2667
0
  ret = write_in_full(hook_stdin_fd, buf->buf, buf->len);
2668
0
  if (ret < 0 && errno != EPIPE)
2669
0
    return ret;
2670
2671
0
  return 0; /* no more input to feed */
2672
0
}
2673
2674
static void *transaction_feed_cb_data_alloc(void *feed_pipe_ctx UNUSED)
2675
0
{
2676
0
  struct transaction_feed_cb_data *data;
2677
0
  CALLOC_ARRAY(data, 1);
2678
0
  strbuf_init(&data->buf, 0);
2679
0
  data->index = 0;
2680
0
  return data;
2681
0
}
2682
2683
static void transaction_feed_cb_data_free(void *data)
2684
0
{
2685
0
  struct transaction_feed_cb_data *d = data;
2686
0
  if (!d)
2687
0
    return;
2688
0
  strbuf_release(&d->buf);
2689
0
  free(d);
2690
0
}
2691
2692
static int run_transaction_hook(struct ref_transaction *transaction,
2693
        const char *state)
2694
0
{
2695
0
  struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
2696
0
  int ret = 0;
2697
2698
0
  strvec_push(&opt.args, state);
2699
2700
0
  opt.feed_pipe = transaction_hook_feed_stdin;
2701
0
  opt.feed_pipe_ctx = transaction;
2702
0
  opt.feed_pipe_cb_data_alloc = transaction_feed_cb_data_alloc;
2703
0
  opt.feed_pipe_cb_data_free = transaction_feed_cb_data_free;
2704
2705
0
  ret = run_hooks_opt(transaction->ref_store->repo, "reference-transaction", &opt);
2706
2707
0
  return ret;
2708
0
}
2709
2710
int ref_transaction_prepare(struct ref_transaction *transaction,
2711
          struct strbuf *err)
2712
0
{
2713
0
  struct ref_store *refs = transaction->ref_store;
2714
0
  int ret;
2715
2716
0
  switch (transaction->state) {
2717
0
  case REF_TRANSACTION_OPEN:
2718
    /* Good. */
2719
0
    break;
2720
0
  case REF_TRANSACTION_PREPARED:
2721
0
    BUG("prepare called twice on reference transaction");
2722
0
    break;
2723
0
  case REF_TRANSACTION_CLOSED:
2724
0
    BUG("prepare called on a closed reference transaction");
2725
0
    break;
2726
0
  default:
2727
0
    BUG("unexpected reference transaction state");
2728
0
    break;
2729
0
  }
2730
2731
0
  if (refs->repo->disable_ref_updates) {
2732
0
    strbuf_addstr(err,
2733
0
            _("ref updates forbidden inside quarantine environment"));
2734
0
    return -1;
2735
0
  }
2736
2737
0
  string_list_sort(&transaction->refnames);
2738
0
  if (ref_update_reject_duplicates(&transaction->refnames, err))
2739
0
    return REF_TRANSACTION_ERROR_GENERIC;
2740
2741
  /* Preparing checks before locking references */
2742
0
  ret = run_transaction_hook(transaction, "preparing");
2743
0
  if (ret) {
2744
0
    ref_transaction_abort(transaction, err);
2745
0
    die(_(abort_by_ref_transaction_hook), "preparing");
2746
0
  }
2747
2748
0
  ret = refs->be->transaction_prepare(refs, transaction, err);
2749
0
  if (ret)
2750
0
    return ret;
2751
2752
0
  ret = run_transaction_hook(transaction, "prepared");
2753
0
  if (ret) {
2754
0
    ref_transaction_abort(transaction, err);
2755
0
    die(_(abort_by_ref_transaction_hook), "prepared");
2756
0
  }
2757
2758
0
  return 0;
2759
0
}
2760
2761
int ref_transaction_abort(struct ref_transaction *transaction,
2762
        struct strbuf *err)
2763
0
{
2764
0
  struct ref_store *refs = transaction->ref_store;
2765
0
  int ret = 0;
2766
2767
0
  switch (transaction->state) {
2768
0
  case REF_TRANSACTION_OPEN:
2769
    /* No need to abort explicitly. */
2770
0
    break;
2771
0
  case REF_TRANSACTION_PREPARED:
2772
0
    ret = refs->be->transaction_abort(refs, transaction, err);
2773
0
    break;
2774
0
  case REF_TRANSACTION_CLOSED:
2775
0
    BUG("abort called on a closed reference transaction");
2776
0
    break;
2777
0
  default:
2778
0
    BUG("unexpected reference transaction state");
2779
0
    break;
2780
0
  }
2781
2782
0
  run_transaction_hook(transaction, "aborted");
2783
2784
0
  ref_transaction_free(transaction);
2785
0
  return ret;
2786
0
}
2787
2788
int ref_transaction_commit(struct ref_transaction *transaction,
2789
         struct strbuf *err)
2790
0
{
2791
0
  struct ref_store *refs = transaction->ref_store;
2792
0
  int ret;
2793
2794
0
  switch (transaction->state) {
2795
0
  case REF_TRANSACTION_OPEN:
2796
    /* Need to prepare first. */
2797
0
    ret = ref_transaction_prepare(transaction, err);
2798
0
    if (ret)
2799
0
      return ret;
2800
0
    break;
2801
0
  case REF_TRANSACTION_PREPARED:
2802
    /* Fall through to finish. */
2803
0
    break;
2804
0
  case REF_TRANSACTION_CLOSED:
2805
0
    BUG("commit called on a closed reference transaction");
2806
0
    break;
2807
0
  default:
2808
0
    BUG("unexpected reference transaction state");
2809
0
    break;
2810
0
  }
2811
2812
0
  ret = refs->be->transaction_finish(refs, transaction, err);
2813
0
  if (!ret && !(transaction->flags & REF_TRANSACTION_FLAG_INITIAL))
2814
0
    run_transaction_hook(transaction, "committed");
2815
0
  return ret;
2816
0
}
2817
2818
enum ref_transaction_error refs_verify_refnames_available(struct ref_store *refs,
2819
            const struct string_list *refnames,
2820
            const struct string_list *extras,
2821
            const struct string_list *skip,
2822
            struct ref_transaction *transaction,
2823
            unsigned int initial_transaction,
2824
            struct strbuf *err)
2825
0
{
2826
0
  struct strbuf dirname = STRBUF_INIT;
2827
0
  struct strbuf referent = STRBUF_INIT;
2828
0
  struct string_list_item *item;
2829
0
  struct ref_iterator *iter = NULL;
2830
0
  struct strset conflicting_dirnames;
2831
0
  struct strset dirnames;
2832
0
  int ret = REF_TRANSACTION_ERROR_NAME_CONFLICT;
2833
2834
  /*
2835
   * For the sake of comments in this function, suppose that
2836
   * refname is "refs/foo/bar".
2837
   */
2838
2839
0
  assert(err);
2840
2841
0
  strset_init(&conflicting_dirnames);
2842
0
  strset_init(&dirnames);
2843
2844
0
  for_each_string_list_item(item, refnames) {
2845
0
    const size_t *update_idx = (size_t *)item->util;
2846
0
    const char *refname = item->string;
2847
0
    const char *extra_refname;
2848
0
    struct object_id oid;
2849
0
    unsigned int type;
2850
0
    const char *slash;
2851
2852
0
    strbuf_reset(&dirname);
2853
2854
0
    for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2855
      /*
2856
       * Just saying "Is a directory" when we e.g. can't
2857
       * lock some multi-level ref isn't very informative,
2858
       * the user won't be told *what* is a directory, so
2859
       * let's not use strerror() below.
2860
       */
2861
0
      int ignore_errno;
2862
2863
      /* Expand dirname to the new prefix, not including the trailing slash: */
2864
0
      strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2865
2866
      /*
2867
       * We are still at a leading dir of the refname (e.g.,
2868
       * "refs/foo"; if there is a reference with that name,
2869
       * it is a conflict, *unless* it is in skip.
2870
       */
2871
0
      if (skip && string_list_has_string(skip, dirname.buf))
2872
0
        continue;
2873
2874
      /*
2875
       * If we've already seen the directory we don't need to
2876
       * process it again. Skip it to avoid checking common
2877
       * prefixes like "refs/heads/" repeatedly.
2878
       */
2879
0
      if (!strset_add(&dirnames, dirname.buf))
2880
0
        continue;
2881
2882
0
      if (!initial_transaction &&
2883
0
          (strset_contains(&conflicting_dirnames, dirname.buf) ||
2884
0
           !refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2885
0
            &type, &ignore_errno))) {
2886
2887
0
        strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2888
0
              dirname.buf, refname);
2889
2890
0
        if (transaction && ref_transaction_maybe_set_rejected(
2891
0
              transaction, *update_idx,
2892
0
              REF_TRANSACTION_ERROR_NAME_CONFLICT, err)) {
2893
0
          strset_remove(&dirnames, dirname.buf);
2894
0
          strset_add(&conflicting_dirnames, dirname.buf);
2895
0
          goto next_ref;
2896
0
        }
2897
2898
0
        goto cleanup;
2899
0
      }
2900
2901
0
      if (extras && string_list_has_string(extras, dirname.buf)) {
2902
0
        strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2903
0
              refname, dirname.buf);
2904
2905
0
        if (transaction && ref_transaction_maybe_set_rejected(
2906
0
              transaction, *update_idx,
2907
0
              REF_TRANSACTION_ERROR_NAME_CONFLICT, err)) {
2908
0
          strset_remove(&dirnames, dirname.buf);
2909
0
          goto next_ref;
2910
0
        }
2911
2912
0
        goto cleanup;
2913
0
      }
2914
0
    }
2915
2916
    /*
2917
     * We are at the leaf of our refname (e.g., "refs/foo/bar").
2918
     * There is no point in searching for a reference with that
2919
     * name, because a refname isn't considered to conflict with
2920
     * itself. But we still need to check for references whose
2921
     * names are in the "refs/foo/bar/" namespace, because they
2922
     * *do* conflict.
2923
     */
2924
0
    strbuf_addstr(&dirname, refname + dirname.len);
2925
0
    strbuf_addch(&dirname, '/');
2926
2927
0
    if (!initial_transaction) {
2928
0
      int ok;
2929
2930
0
      if (!iter)
2931
0
        iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,
2932
0
                     REFS_FOR_EACH_INCLUDE_BROKEN);
2933
0
      else if (ref_iterator_seek(iter, dirname.buf,
2934
0
               REF_ITERATOR_SEEK_SET_PREFIX) < 0)
2935
0
        goto cleanup;
2936
2937
0
      while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2938
0
        if (skip &&
2939
0
            string_list_has_string(skip, iter->ref.name))
2940
0
          continue;
2941
0
        strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2942
0
              iter->ref.name, refname);
2943
2944
0
        if (transaction && ref_transaction_maybe_set_rejected(
2945
0
              transaction, *update_idx,
2946
0
              REF_TRANSACTION_ERROR_NAME_CONFLICT, err))
2947
0
          goto next_ref;
2948
2949
0
        goto cleanup;
2950
0
      }
2951
2952
0
      if (ok != ITER_DONE)
2953
0
        BUG("error while iterating over references");
2954
0
    }
2955
2956
0
    extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2957
0
    if (extra_refname) {
2958
0
      strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2959
0
            refname, extra_refname);
2960
2961
0
      if (transaction && ref_transaction_maybe_set_rejected(
2962
0
            transaction, *update_idx,
2963
0
            REF_TRANSACTION_ERROR_NAME_CONFLICT, err))
2964
0
        goto next_ref;
2965
2966
0
      goto cleanup;
2967
0
    }
2968
0
next_ref:;
2969
0
  }
2970
2971
0
  ret = 0;
2972
2973
0
cleanup:
2974
0
  strbuf_release(&referent);
2975
0
  strbuf_release(&dirname);
2976
0
  strset_clear(&conflicting_dirnames);
2977
0
  strset_clear(&dirnames);
2978
0
  ref_iterator_free(iter);
2979
0
  return ret;
2980
0
}
2981
2982
enum ref_transaction_error refs_verify_refname_available(
2983
  struct ref_store *refs,
2984
  const char *refname,
2985
  const struct string_list *extras,
2986
  const struct string_list *skip,
2987
  unsigned int initial_transaction,
2988
  struct strbuf *err)
2989
0
{
2990
0
  struct string_list_item item = { .string = (char *) refname };
2991
0
  struct string_list refnames = {
2992
0
    .items = &item,
2993
0
    .nr = 1,
2994
0
  };
2995
2996
0
  return refs_verify_refnames_available(refs, &refnames, extras, skip,
2997
0
                NULL, initial_transaction, err);
2998
0
}
2999
3000
struct do_for_each_reflog_help {
3001
  each_reflog_fn *fn;
3002
  void *cb_data;
3003
};
3004
3005
static int do_for_each_reflog_helper(const struct reference *ref, void *cb_data)
3006
0
{
3007
0
  struct do_for_each_reflog_help *hp = cb_data;
3008
0
  return hp->fn(ref->name, hp->cb_data);
3009
0
}
3010
3011
int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)
3012
0
{
3013
0
  struct ref_iterator *iter;
3014
0
  struct do_for_each_reflog_help hp = { fn, cb_data };
3015
3016
0
  iter = refs->be->reflog_iterator_begin(refs);
3017
3018
0
  return do_for_each_ref_iterator(iter, do_for_each_reflog_helper, &hp);
3019
0
}
3020
3021
int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
3022
             const char *refname,
3023
             each_reflog_ent_fn fn,
3024
             void *cb_data)
3025
0
{
3026
0
  return refs->be->for_each_reflog_ent_reverse(refs, refname,
3027
0
                 fn, cb_data);
3028
0
}
3029
3030
int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
3031
           each_reflog_ent_fn fn, void *cb_data)
3032
0
{
3033
0
  return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
3034
0
}
3035
3036
int refs_reflog_exists(struct ref_store *refs, const char *refname)
3037
0
{
3038
0
  return refs->be->reflog_exists(refs, refname);
3039
0
}
3040
3041
int refs_create_reflog(struct ref_store *refs, const char *refname,
3042
           struct strbuf *err)
3043
0
{
3044
0
  return refs->be->create_reflog(refs, refname, err);
3045
0
}
3046
3047
int refs_delete_reflog(struct ref_store *refs, const char *refname)
3048
0
{
3049
0
  return refs->be->delete_reflog(refs, refname);
3050
0
}
3051
3052
int refs_reflog_expire(struct ref_store *refs,
3053
           const char *refname,
3054
           unsigned int flags,
3055
           reflog_expiry_prepare_fn prepare_fn,
3056
           reflog_expiry_should_prune_fn should_prune_fn,
3057
           reflog_expiry_cleanup_fn cleanup_fn,
3058
           void *policy_cb_data)
3059
0
{
3060
0
  return refs->be->reflog_expire(refs, refname, flags,
3061
0
               prepare_fn, should_prune_fn,
3062
0
               cleanup_fn, policy_cb_data);
3063
0
}
3064
3065
void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
3066
              ref_transaction_for_each_queued_update_fn cb,
3067
              void *cb_data)
3068
0
{
3069
0
  for (size_t i = 0; i < transaction->nr; i++) {
3070
0
    struct ref_update *update = transaction->updates[i];
3071
3072
0
    cb(update->refname,
3073
0
       (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
3074
0
       (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
3075
0
       cb_data);
3076
0
  }
3077
0
}
3078
3079
void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
3080
                ref_transaction_for_each_rejected_update_fn cb,
3081
                void *cb_data)
3082
0
{
3083
0
  if (!transaction->rejections)
3084
0
    return;
3085
3086
0
  for (size_t i = 0; i < transaction->rejections->nr; i++) {
3087
0
    size_t update_index = transaction->rejections->update_indices[i];
3088
0
    struct ref_update *update = transaction->updates[update_index];
3089
3090
0
    if (!update->rejection_err)
3091
0
      continue;
3092
3093
0
    cb(update->refname,
3094
0
       (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
3095
0
       (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
3096
0
       update->old_target, update->new_target,
3097
0
       update->rejection_err, update->rejection_details, cb_data);
3098
0
  }
3099
0
}
3100
3101
int refs_delete_refs(struct ref_store *refs, const char *logmsg,
3102
         struct string_list *refnames, unsigned int flags)
3103
0
{
3104
0
  struct ref_transaction *transaction;
3105
0
  struct strbuf err = STRBUF_INIT;
3106
0
  struct string_list_item *item;
3107
0
  int ret = 0, failures = 0;
3108
0
  char *msg;
3109
3110
0
  if (!refnames->nr)
3111
0
    return 0;
3112
3113
0
  msg = normalize_reflog_message(logmsg);
3114
3115
  /*
3116
   * Since we don't check the references' old_oids, the
3117
   * individual updates can't fail, so we can pack all of the
3118
   * updates into a single transaction.
3119
   */
3120
0
  transaction = ref_store_transaction_begin(refs, 0, &err);
3121
0
  if (!transaction) {
3122
0
    ret = error("%s", err.buf);
3123
0
    goto out;
3124
0
  }
3125
3126
0
  for_each_string_list_item(item, refnames) {
3127
0
    ret = ref_transaction_delete(transaction, item->string,
3128
0
               NULL, NULL, flags, msg, &err);
3129
0
    if (ret) {
3130
0
      warning(_("could not delete reference %s: %s"),
3131
0
        item->string, err.buf);
3132
0
      strbuf_reset(&err);
3133
0
      failures = 1;
3134
0
    }
3135
0
  }
3136
3137
0
  ret = ref_transaction_commit(transaction, &err);
3138
0
  if (ret) {
3139
0
    if (refnames->nr == 1)
3140
0
      error(_("could not delete reference %s: %s"),
3141
0
            refnames->items[0].string, err.buf);
3142
0
    else
3143
0
      error(_("could not delete references: %s"), err.buf);
3144
0
  }
3145
3146
0
out:
3147
0
  if (!ret && failures)
3148
0
    ret = -1;
3149
0
  ref_transaction_free(transaction);
3150
0
  strbuf_release(&err);
3151
0
  free(msg);
3152
0
  return ret;
3153
0
}
3154
3155
int refs_rename_ref(struct ref_store *refs, const char *oldref,
3156
        const char *newref, const char *logmsg)
3157
0
{
3158
0
  char *msg;
3159
0
  int retval;
3160
3161
0
  msg = normalize_reflog_message(logmsg);
3162
0
  retval = refs->be->rename_ref(refs, oldref, newref, msg);
3163
0
  free(msg);
3164
0
  return retval;
3165
0
}
3166
3167
int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
3168
        const char *newref, const char *logmsg)
3169
0
{
3170
0
  char *msg;
3171
0
  int retval;
3172
3173
0
  msg = normalize_reflog_message(logmsg);
3174
0
  retval = refs->be->copy_ref(refs, oldref, newref, msg);
3175
0
  free(msg);
3176
0
  return retval;
3177
0
}
3178
3179
const char *ref_update_original_update_refname(struct ref_update *update)
3180
0
{
3181
0
  while (update->parent_update)
3182
0
    update = update->parent_update;
3183
3184
0
  return update->refname;
3185
0
}
3186
3187
int ref_update_has_null_new_value(struct ref_update *update)
3188
0
{
3189
0
  return !update->new_target && is_null_oid(&update->new_oid);
3190
0
}
3191
3192
enum ref_transaction_error ref_update_check_old_target(const char *referent,
3193
                   struct ref_update *update,
3194
                   struct strbuf *err)
3195
0
{
3196
0
  if (!update->old_target)
3197
0
    BUG("called without old_target set");
3198
3199
0
  if (!strcmp(referent, update->old_target))
3200
0
    return 0;
3201
3202
0
  if (!strcmp(referent, "")) {
3203
0
    strbuf_addf(err, "verifying symref target: '%s': "
3204
0
          "reference is missing but expected %s",
3205
0
          ref_update_original_update_refname(update),
3206
0
          update->old_target);
3207
0
    return REF_TRANSACTION_ERROR_NONEXISTENT_REF;
3208
0
  }
3209
3210
0
  strbuf_addf(err, "verifying symref target: '%s': is at %s but expected %s",
3211
0
          ref_update_original_update_refname(update),
3212
0
          referent, update->old_target);
3213
0
  return REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE;
3214
0
}
3215
3216
struct migration_data {
3217
  struct ref_store *old_refs;
3218
  struct ref_transaction *transaction;
3219
  struct strbuf *errbuf;
3220
  struct strbuf sb, name, mail;
3221
  uint64_t index;
3222
};
3223
3224
static int migrate_one_ref(const struct reference *ref, void *cb_data)
3225
0
{
3226
0
  struct migration_data *data = cb_data;
3227
0
  const struct git_hash_algo *hash_algo = data->transaction->ref_store->repo->hash_algo;
3228
0
  struct strbuf symref_target = STRBUF_INIT;
3229
0
  int ret;
3230
3231
0
  if (ref->flags & REF_ISSYMREF) {
3232
0
    ret = refs_read_symbolic_ref(data->old_refs, ref->name, &symref_target);
3233
0
    if (ret < 0)
3234
0
      goto done;
3235
3236
0
    ret = ref_transaction_update(data->transaction, ref->name, NULL, null_oid(hash_algo),
3237
0
               symref_target.buf, NULL,
3238
0
               REF_SKIP_CREATE_REFLOG | REF_NO_DEREF, NULL, data->errbuf);
3239
0
    if (ret < 0)
3240
0
      goto done;
3241
0
  } else {
3242
0
    ret = ref_transaction_create(data->transaction, ref->name, ref->oid, NULL,
3243
0
               REF_SKIP_CREATE_REFLOG | REF_SKIP_OID_VERIFICATION,
3244
0
               NULL, data->errbuf);
3245
0
    if (ret < 0)
3246
0
      goto done;
3247
0
  }
3248
3249
0
done:
3250
0
  strbuf_release(&symref_target);
3251
0
  return ret;
3252
0
}
3253
3254
static int migrate_one_reflog_entry(const char *refname,
3255
            struct object_id *old_oid,
3256
            struct object_id *new_oid,
3257
            const char *committer,
3258
            timestamp_t timestamp, int tz,
3259
            const char *msg, void *cb_data)
3260
0
{
3261
0
  struct migration_data *data = cb_data;
3262
0
  struct ident_split ident;
3263
0
  const char *date;
3264
0
  int ret;
3265
3266
0
  if (split_ident_line(&ident, committer, strlen(committer)) < 0)
3267
0
    return -1;
3268
3269
0
  strbuf_reset(&data->name);
3270
0
  strbuf_add(&data->name, ident.name_begin, ident.name_end - ident.name_begin);
3271
0
  strbuf_reset(&data->mail);
3272
0
  strbuf_add(&data->mail, ident.mail_begin, ident.mail_end - ident.mail_begin);
3273
3274
0
  date = show_date(timestamp, tz, DATE_MODE(NORMAL));
3275
0
  strbuf_reset(&data->sb);
3276
0
  strbuf_addstr(&data->sb, fmt_ident(data->name.buf, data->mail.buf, WANT_BLANK_IDENT, date, 0));
3277
3278
0
  ret = ref_transaction_update_reflog(data->transaction, refname,
3279
0
              new_oid, old_oid, data->sb.buf,
3280
0
              msg, data->index++, data->errbuf);
3281
0
  return ret;
3282
0
}
3283
3284
static int migrate_one_reflog(const char *refname, void *cb_data)
3285
0
{
3286
0
  struct migration_data *migration_data = cb_data;
3287
0
  return refs_for_each_reflog_ent(migration_data->old_refs, refname,
3288
0
          migrate_one_reflog_entry, migration_data);
3289
0
}
3290
3291
static int move_files(const char *from_path, const char *to_path, struct strbuf *errbuf)
3292
0
{
3293
0
  struct strbuf from_buf = STRBUF_INIT, to_buf = STRBUF_INIT;
3294
0
  size_t from_len, to_len;
3295
0
  DIR *from_dir;
3296
0
  int ret;
3297
3298
0
  from_dir = opendir(from_path);
3299
0
  if (!from_dir) {
3300
0
    strbuf_addf(errbuf, "could not open source directory '%s': %s",
3301
0
          from_path, strerror(errno));
3302
0
    ret = -1;
3303
0
    goto done;
3304
0
  }
3305
3306
0
  strbuf_addstr(&from_buf, from_path);
3307
0
  strbuf_complete(&from_buf, '/');
3308
0
  from_len = from_buf.len;
3309
3310
0
  strbuf_addstr(&to_buf, to_path);
3311
0
  strbuf_complete(&to_buf, '/');
3312
0
  to_len = to_buf.len;
3313
3314
0
  while (1) {
3315
0
    struct dirent *ent;
3316
3317
0
    errno = 0;
3318
0
    ent = readdir(from_dir);
3319
0
    if (!ent)
3320
0
      break;
3321
3322
0
    if (!strcmp(ent->d_name, ".") ||
3323
0
        !strcmp(ent->d_name, ".."))
3324
0
      continue;
3325
3326
0
    strbuf_setlen(&from_buf, from_len);
3327
0
    strbuf_addstr(&from_buf, ent->d_name);
3328
3329
0
    strbuf_setlen(&to_buf, to_len);
3330
0
    strbuf_addstr(&to_buf, ent->d_name);
3331
3332
0
    ret = rename(from_buf.buf, to_buf.buf);
3333
0
    if (ret < 0) {
3334
0
      strbuf_addf(errbuf, "could not link file '%s' to '%s': %s",
3335
0
            from_buf.buf, to_buf.buf, strerror(errno));
3336
0
      goto done;
3337
0
    }
3338
0
  }
3339
3340
0
  if (errno) {
3341
0
    strbuf_addf(errbuf, "could not read entry from directory '%s': %s",
3342
0
          from_path, strerror(errno));
3343
0
    ret = -1;
3344
0
    goto done;
3345
0
  }
3346
3347
0
  ret = 0;
3348
3349
0
done:
3350
0
  strbuf_release(&from_buf);
3351
0
  strbuf_release(&to_buf);
3352
0
  if (from_dir)
3353
0
    closedir(from_dir);
3354
0
  return ret;
3355
0
}
3356
3357
static int has_worktrees(struct repository *repo)
3358
0
{
3359
0
  struct worktree **worktrees = get_worktrees(repo);
3360
0
  int ret = 0;
3361
0
  size_t i;
3362
3363
0
  for (i = 0; worktrees[i]; i++) {
3364
0
    if (is_main_worktree(worktrees[i]))
3365
0
      continue;
3366
0
    ret = 1;
3367
0
  }
3368
3369
0
  free_worktrees(worktrees);
3370
0
  return ret;
3371
0
}
3372
3373
int repo_migrate_ref_storage_format(struct repository *repo,
3374
            enum ref_storage_format format,
3375
            unsigned int flags,
3376
            struct strbuf *errbuf)
3377
0
{
3378
0
  struct ref_store *old_refs = NULL, *new_refs = NULL;
3379
0
  struct refs_for_each_ref_options for_each_ref_opts = {
3380
0
    .flags = REFS_FOR_EACH_INCLUDE_ROOT_REFS | REFS_FOR_EACH_INCLUDE_BROKEN,
3381
0
  };
3382
0
  struct ref_transaction *transaction = NULL;
3383
0
  struct strbuf new_gitdir = STRBUF_INIT;
3384
0
  struct migration_data data = {
3385
0
    .sb = STRBUF_INIT,
3386
0
    .name = STRBUF_INIT,
3387
0
    .mail = STRBUF_INIT,
3388
0
  };
3389
0
  int did_migrate_refs = 0;
3390
0
  int ret;
3391
3392
0
  if (repo->ref_storage_format == format) {
3393
0
    strbuf_addstr(errbuf, "current and new ref storage format are equal");
3394
0
    ret = -1;
3395
0
    goto done;
3396
0
  }
3397
3398
0
  old_refs = get_main_ref_store(repo);
3399
3400
  /*
3401
   * Worktrees complicate the migration because every worktree has a
3402
   * separate ref storage. While it should be feasible to implement, this
3403
   * is pushed out to a future iteration.
3404
   */
3405
0
  if (has_worktrees(repo)) {
3406
0
    strbuf_addstr(errbuf, "migrating repositories with worktrees is not supported yet");
3407
0
    ret = -1;
3408
0
    goto done;
3409
0
  }
3410
3411
  /*
3412
   * The overall logic looks like this:
3413
   *
3414
   *   1. Set up a new temporary directory and initialize it with the new
3415
   *      format. This is where all refs will be migrated into.
3416
   *
3417
   *   2. Enumerate all refs and write them into the new ref storage.
3418
   *      This operation is safe as we do not yet modify the main
3419
   *      repository.
3420
   *
3421
   *   3. Enumerate all reflogs and write them into the new ref storage.
3422
   *      This operation is safe as we do not yet modify the main
3423
   *      repository.
3424
   *
3425
   *   4. If we're in dry-run mode then we are done and can hand over the
3426
   *      directory to the caller for inspection. If not, we now start
3427
   *      with the destructive part.
3428
   *
3429
   *   5. Delete the old ref storage from disk. As we have a copy of refs
3430
   *      in the new ref storage it's okay(ish) if we now get interrupted
3431
   *      as there is an equivalent copy of all refs available.
3432
   *
3433
   *   6. Move the new ref storage files into place.
3434
   *
3435
   *  7. Change the repository format to the new ref format.
3436
   */
3437
0
  strbuf_addf(&new_gitdir, "%s/%s", old_refs->gitdir, "ref_migration.XXXXXX");
3438
0
  if (!mkdtemp(new_gitdir.buf)) {
3439
0
    strbuf_addf(errbuf, "cannot create migration directory: %s",
3440
0
          strerror(errno));
3441
0
    ret = -1;
3442
0
    goto done;
3443
0
  }
3444
3445
0
  new_refs = ref_store_init(repo, format, new_gitdir.buf,
3446
0
          REF_STORE_ALL_CAPS);
3447
0
  ret = ref_store_create_on_disk(new_refs, 0, errbuf);
3448
0
  if (ret < 0)
3449
0
    goto done;
3450
3451
0
  transaction = ref_store_transaction_begin(new_refs, REF_TRANSACTION_FLAG_INITIAL,
3452
0
              errbuf);
3453
0
  if (!transaction)
3454
0
    goto done;
3455
3456
0
  data.old_refs = old_refs;
3457
0
  data.transaction = transaction;
3458
0
  data.errbuf = errbuf;
3459
3460
  /*
3461
   * We need to use `refs_for_each_ref_ext()` here so that we can
3462
   * also include broken refs and symrefs. These would otherwise be
3463
   * skipped silently.
3464
   *
3465
   * Ideally, we would do this call while locking the old ref storage
3466
   * such that there cannot be any concurrent modifications. We do not
3467
   * have the infra for that though, and the "files" backend does not
3468
   * allow for a central lock due to its design. It's thus on the user to
3469
   * ensure that there are no concurrent writes.
3470
   */
3471
0
  ret = refs_for_each_ref_ext(old_refs, migrate_one_ref, &data, &for_each_ref_opts);
3472
0
  if (ret < 0)
3473
0
    goto done;
3474
3475
0
  if (!(flags & REPO_MIGRATE_REF_STORAGE_FORMAT_SKIP_REFLOG)) {
3476
0
    ret = refs_for_each_reflog(old_refs, migrate_one_reflog, &data);
3477
0
    if (ret < 0)
3478
0
      goto done;
3479
0
  }
3480
3481
0
  ret = ref_transaction_commit(transaction, errbuf);
3482
0
  if (ret < 0)
3483
0
    goto done;
3484
0
  did_migrate_refs = 1;
3485
3486
0
  if (flags & REPO_MIGRATE_REF_STORAGE_FORMAT_DRYRUN) {
3487
0
    printf(_("Finished dry-run migration of refs, "
3488
0
       "the result can be found at '%s'\n"), new_gitdir.buf);
3489
0
    ret = 0;
3490
0
    goto done;
3491
0
  }
3492
3493
  /*
3494
   * Release the new ref store such that any potentially-open files will
3495
   * be closed. This is required for platforms like Cygwin, where
3496
   * renaming an open file results in EPERM.
3497
   */
3498
0
  ref_store_release(new_refs);
3499
0
  FREE_AND_NULL(new_refs);
3500
3501
  /*
3502
   * Until now we were in the non-destructive phase, where we only
3503
   * populated the new ref store. From hereon though we are about
3504
   * to get hands by deleting the old ref store and then moving
3505
   * the new one into place.
3506
   *
3507
   * Assuming that there were no concurrent writes, the new ref
3508
   * store should have all information. So if we fail from hereon
3509
   * we may be in an in-between state, but it would still be able
3510
   * to recover by manually moving remaining files from the
3511
   * temporary migration directory into place.
3512
   */
3513
0
  ret = ref_store_remove_on_disk(old_refs, errbuf);
3514
0
  if (ret < 0)
3515
0
    goto done;
3516
3517
0
  ret = move_files(new_gitdir.buf, old_refs->gitdir, errbuf);
3518
0
  if (ret < 0)
3519
0
    goto done;
3520
3521
0
  if (rmdir(new_gitdir.buf) < 0)
3522
0
    warning_errno(_("could not remove temporary migration directory '%s'"),
3523
0
            new_gitdir.buf);
3524
3525
  /*
3526
   * We have migrated the repository, so we now need to adjust the
3527
   * repository format so that clients will use the new ref store.
3528
   * We also need to swap out the repository's main ref store.
3529
   */
3530
0
  initialize_repository_version(repo, hash_algo_by_ptr(repo->hash_algo), format,
3531
0
              repo->object_storage_format, 1);
3532
3533
  /*
3534
   * Unset the old ref store and release it. `get_main_ref_store()` will
3535
   * make sure to lazily re-initialize the repository's ref store with
3536
   * the new format.
3537
   */
3538
0
  ref_store_release(old_refs);
3539
0
  FREE_AND_NULL(old_refs);
3540
0
  repo->refs_private = NULL;
3541
3542
0
  ret = 0;
3543
3544
0
done:
3545
0
  if (ret && did_migrate_refs) {
3546
0
    strbuf_complete(errbuf, '\n');
3547
0
    strbuf_addf(errbuf, _("migrated refs can be found at '%s'"),
3548
0
          new_gitdir.buf);
3549
0
  }
3550
3551
0
  if (new_refs) {
3552
0
    ref_store_release(new_refs);
3553
0
    free(new_refs);
3554
0
  }
3555
0
  ref_transaction_free(transaction);
3556
0
  strbuf_release(&new_gitdir);
3557
0
  strbuf_release(&data.sb);
3558
0
  strbuf_release(&data.name);
3559
0
  strbuf_release(&data.mail);
3560
0
  return ret;
3561
0
}
3562
3563
int ref_update_expects_existing_old_ref(struct ref_update *update)
3564
0
{
3565
0
  if (update->flags & REF_LOG_ONLY)
3566
0
    return 0;
3567
3568
0
  return (update->flags & REF_HAVE_OLD) &&
3569
0
    (!is_null_oid(&update->old_oid) || update->old_target);
3570
0
}
3571
3572
const char *ref_transaction_error_msg(enum ref_transaction_error err)
3573
0
{
3574
0
  switch (err) {
3575
0
  case REF_TRANSACTION_ERROR_NAME_CONFLICT:
3576
0
    return "refname conflict";
3577
0
  case REF_TRANSACTION_ERROR_CREATE_EXISTS:
3578
0
    return "reference already exists";
3579
0
  case REF_TRANSACTION_ERROR_NONEXISTENT_REF:
3580
0
    return "reference does not exist";
3581
0
  case REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE:
3582
0
    return "incorrect old value provided";
3583
0
  case REF_TRANSACTION_ERROR_INVALID_NEW_VALUE:
3584
0
    return "invalid new value provided";
3585
0
  case REF_TRANSACTION_ERROR_EXPECTED_SYMREF:
3586
0
    return "expected symref but found regular ref";
3587
0
  case REF_TRANSACTION_ERROR_CASE_CONFLICT:
3588
0
    return "reference conflict due to case-insensitive filesystem";
3589
0
  default:
3590
0
    return "unknown failure";
3591
0
  }
3592
0
}
3593
3594
void refs_compute_filesystem_location(const char *gitdir, const char *payload,
3595
              bool *is_worktree, struct strbuf *refdir,
3596
              struct strbuf *ref_common_dir)
3597
0
{
3598
0
  struct strbuf sb = STRBUF_INIT;
3599
3600
0
  *is_worktree = get_common_dir_noenv(ref_common_dir, gitdir);
3601
3602
0
  if (!payload) {
3603
    /*
3604
     * We can use the 'gitdir' as the 'refdir' without appending the
3605
     * worktree path, as the 'gitdir' here is already the worktree
3606
     * path and is different from 'commondir' denoted by 'ref_common_dir'.
3607
     */
3608
0
    strbuf_addstr(refdir, gitdir);
3609
0
    return;
3610
0
  }
3611
3612
0
  if (!is_absolute_path(payload)) {
3613
0
    strbuf_addf(&sb, "%s/%s", ref_common_dir->buf, payload);
3614
0
    strbuf_realpath(ref_common_dir, sb.buf, 1);
3615
0
  } else {
3616
0
    strbuf_realpath(ref_common_dir, payload, 1);
3617
0
  }
3618
3619
0
  strbuf_addbuf(refdir, ref_common_dir);
3620
3621
0
  if (*is_worktree) {
3622
0
    const char *wt_id = strrchr(gitdir, '/');
3623
0
    if (!wt_id)
3624
0
      BUG("worktree path does not contain slash");
3625
0
    strbuf_addf(refdir, "/worktrees/%s", wt_id + 1);
3626
0
  }
3627
3628
0
  strbuf_release(&sb);
3629
0
}