Coverage Report

Created: 2026-02-26 06:44

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