Coverage Report

Created: 2026-03-21 06:46

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