Coverage Report

Created: 2026-05-10 06:11

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