Coverage Report

Created: 2025-12-31 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/object-name.c
Line
Count
Source
1
#define USE_THE_REPOSITORY_VARIABLE
2
#define DISABLE_SIGN_COMPARE_WARNINGS
3
4
#include "git-compat-util.h"
5
#include "object-name.h"
6
#include "advice.h"
7
#include "config.h"
8
#include "environment.h"
9
#include "gettext.h"
10
#include "hex.h"
11
#include "tag.h"
12
#include "commit.h"
13
#include "tree.h"
14
#include "tree-walk.h"
15
#include "refs.h"
16
#include "remote.h"
17
#include "dir.h"
18
#include "oid-array.h"
19
#include "oidtree.h"
20
#include "packfile.h"
21
#include "pretty.h"
22
#include "object-file.h"
23
#include "read-cache-ll.h"
24
#include "repo-settings.h"
25
#include "repository.h"
26
#include "setup.h"
27
#include "midx.h"
28
#include "commit-reach.h"
29
#include "date.h"
30
#include "object-file-convert.h"
31
#include "prio-queue.h"
32
33
static int get_oid_oneline(struct repository *r, const char *, struct object_id *,
34
         const struct commit_list *);
35
36
typedef int (*disambiguate_hint_fn)(struct repository *, const struct object_id *, void *);
37
38
struct disambiguate_state {
39
  int len; /* length of prefix in hex chars */
40
  char hex_pfx[GIT_MAX_HEXSZ + 1];
41
  struct object_id bin_pfx;
42
43
  struct repository *repo;
44
  disambiguate_hint_fn fn;
45
  void *cb_data;
46
  struct object_id candidate;
47
  unsigned candidate_exists:1;
48
  unsigned candidate_checked:1;
49
  unsigned candidate_ok:1;
50
  unsigned disambiguate_fn_used:1;
51
  unsigned ambiguous:1;
52
  unsigned always_call_fn:1;
53
};
54
55
static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
56
0
{
57
  /* The hash algorithm of current has already been filtered */
58
0
  if (ds->always_call_fn) {
59
0
    ds->ambiguous = ds->fn(ds->repo, current, ds->cb_data) ? 1 : 0;
60
0
    return;
61
0
  }
62
0
  if (!ds->candidate_exists) {
63
    /* this is the first candidate */
64
0
    oidcpy(&ds->candidate, current);
65
0
    ds->candidate_exists = 1;
66
0
    return;
67
0
  } else if (oideq(&ds->candidate, current)) {
68
    /* the same as what we already have seen */
69
0
    return;
70
0
  }
71
72
0
  if (!ds->fn) {
73
    /* cannot disambiguate between ds->candidate and current */
74
0
    ds->ambiguous = 1;
75
0
    return;
76
0
  }
77
78
0
  if (!ds->candidate_checked) {
79
0
    ds->candidate_ok = ds->fn(ds->repo, &ds->candidate, ds->cb_data);
80
0
    ds->disambiguate_fn_used = 1;
81
0
    ds->candidate_checked = 1;
82
0
  }
83
84
0
  if (!ds->candidate_ok) {
85
    /* discard the candidate; we know it does not satisfy fn */
86
0
    oidcpy(&ds->candidate, current);
87
0
    ds->candidate_checked = 0;
88
0
    return;
89
0
  }
90
91
  /* if we reach this point, we know ds->candidate satisfies fn */
92
0
  if (ds->fn(ds->repo, current, ds->cb_data)) {
93
    /*
94
     * if both current and candidate satisfy fn, we cannot
95
     * disambiguate.
96
     */
97
0
    ds->candidate_ok = 0;
98
0
    ds->ambiguous = 1;
99
0
  }
100
101
  /* otherwise, current can be discarded and candidate is still good */
102
0
}
103
104
static int match_hash(unsigned, const unsigned char *, const unsigned char *);
105
106
static enum cb_next match_prefix(const struct object_id *oid, void *arg)
107
0
{
108
0
  struct disambiguate_state *ds = arg;
109
  /* no need to call match_hash, oidtree_each did prefix match */
110
0
  update_candidates(ds, oid);
111
0
  return ds->ambiguous ? CB_BREAK : CB_CONTINUE;
112
0
}
113
114
static void find_short_object_filename(struct disambiguate_state *ds)
115
0
{
116
0
  struct odb_source *source;
117
118
0
  for (source = ds->repo->objects->sources; source && !ds->ambiguous; source = source->next)
119
0
    oidtree_each(odb_source_loose_cache(source, &ds->bin_pfx),
120
0
        &ds->bin_pfx, ds->len, match_prefix, ds);
121
0
}
122
123
static int match_hash(unsigned len, const unsigned char *a, const unsigned char *b)
124
0
{
125
0
  do {
126
0
    if (*a != *b)
127
0
      return 0;
128
0
    a++;
129
0
    b++;
130
0
    len -= 2;
131
0
  } while (len > 1);
132
0
  if (len)
133
0
    if ((*a ^ *b) & 0xf0)
134
0
      return 0;
135
0
  return 1;
136
0
}
137
138
static void unique_in_midx(struct multi_pack_index *m,
139
         struct disambiguate_state *ds)
140
0
{
141
0
  for (; m; m = m->base_midx) {
142
0
    uint32_t num, i, first = 0;
143
0
    const struct object_id *current = NULL;
144
0
    int len = ds->len > ds->repo->hash_algo->hexsz ?
145
0
      ds->repo->hash_algo->hexsz : ds->len;
146
147
0
    if (!m->num_objects)
148
0
      continue;
149
150
0
    num = m->num_objects + m->num_objects_in_base;
151
152
0
    bsearch_one_midx(&ds->bin_pfx, m, &first);
153
154
    /*
155
     * At this point, "first" is the location of the lowest
156
     * object with an object name that could match
157
     * "bin_pfx".  See if we have 0, 1 or more objects that
158
     * actually match(es).
159
     */
160
0
    for (i = first; i < num && !ds->ambiguous; i++) {
161
0
      struct object_id oid;
162
0
      current = nth_midxed_object_oid(&oid, m, i);
163
0
      if (!match_hash(len, ds->bin_pfx.hash, current->hash))
164
0
        break;
165
0
      update_candidates(ds, current);
166
0
    }
167
0
  }
168
0
}
169
170
static void unique_in_pack(struct packed_git *p,
171
         struct disambiguate_state *ds)
172
0
{
173
0
  uint32_t num, i, first = 0;
174
0
  int len = ds->len > ds->repo->hash_algo->hexsz ?
175
0
    ds->repo->hash_algo->hexsz : ds->len;
176
177
0
  if (p->multi_pack_index)
178
0
    return;
179
180
0
  if (open_pack_index(p) || !p->num_objects)
181
0
    return;
182
183
0
  num = p->num_objects;
184
0
  bsearch_pack(&ds->bin_pfx, p, &first);
185
186
  /*
187
   * At this point, "first" is the location of the lowest object
188
   * with an object name that could match "bin_pfx".  See if we have
189
   * 0, 1 or more objects that actually match(es).
190
   */
191
0
  for (i = first; i < num && !ds->ambiguous; i++) {
192
0
    struct object_id oid;
193
0
    nth_packed_object_id(&oid, p, i);
194
0
    if (!match_hash(len, ds->bin_pfx.hash, oid.hash))
195
0
      break;
196
0
    update_candidates(ds, &oid);
197
0
  }
198
0
}
199
200
static void find_short_packed_object(struct disambiguate_state *ds)
201
0
{
202
0
  struct odb_source *source;
203
0
  struct packed_git *p;
204
205
  /* Skip, unless oids from the storage hash algorithm are wanted */
206
0
  if (ds->bin_pfx.algo && (&hash_algos[ds->bin_pfx.algo] != ds->repo->hash_algo))
207
0
    return;
208
209
0
  odb_prepare_alternates(ds->repo->objects);
210
0
  for (source = ds->repo->objects->sources; source && !ds->ambiguous; source = source->next) {
211
0
    struct multi_pack_index *m = get_multi_pack_index(source);
212
0
    if (m)
213
0
      unique_in_midx(m, ds);
214
0
  }
215
216
0
  repo_for_each_pack(ds->repo, p) {
217
0
    if (ds->ambiguous)
218
0
      break;
219
0
    unique_in_pack(p, ds);
220
0
  }
221
0
}
222
223
static int finish_object_disambiguation(struct disambiguate_state *ds,
224
          struct object_id *oid)
225
0
{
226
0
  if (ds->ambiguous)
227
0
    return SHORT_NAME_AMBIGUOUS;
228
229
0
  if (!ds->candidate_exists)
230
0
    return MISSING_OBJECT;
231
232
0
  if (!ds->candidate_checked)
233
    /*
234
     * If this is the only candidate, there is no point
235
     * calling the disambiguation hint callback.
236
     *
237
     * On the other hand, if the current candidate
238
     * replaced an earlier candidate that did _not_ pass
239
     * the disambiguation hint callback, then we do have
240
     * more than one objects that match the short name
241
     * given, so we should make sure this one matches;
242
     * otherwise, if we discovered this one and the one
243
     * that we previously discarded in the reverse order,
244
     * we would end up showing different results in the
245
     * same repository!
246
     */
247
0
    ds->candidate_ok = (!ds->disambiguate_fn_used ||
248
0
            ds->fn(ds->repo, &ds->candidate, ds->cb_data));
249
250
0
  if (!ds->candidate_ok)
251
0
    return SHORT_NAME_AMBIGUOUS;
252
253
0
  oidcpy(oid, &ds->candidate);
254
0
  return 0;
255
0
}
256
257
static int disambiguate_commit_only(struct repository *r,
258
            const struct object_id *oid,
259
            void *cb_data UNUSED)
260
0
{
261
0
  int kind = odb_read_object_info(r->objects, oid, NULL);
262
0
  return kind == OBJ_COMMIT;
263
0
}
264
265
static int disambiguate_committish_only(struct repository *r,
266
          const struct object_id *oid,
267
          void *cb_data UNUSED)
268
0
{
269
0
  struct object *obj;
270
0
  int kind;
271
272
0
  kind = odb_read_object_info(r->objects, oid, NULL);
273
0
  if (kind == OBJ_COMMIT)
274
0
    return 1;
275
0
  if (kind != OBJ_TAG)
276
0
    return 0;
277
278
  /* We need to do this the hard way... */
279
0
  obj = deref_tag(r, parse_object(r, oid), NULL, 0);
280
0
  if (obj && obj->type == OBJ_COMMIT)
281
0
    return 1;
282
0
  return 0;
283
0
}
284
285
static int disambiguate_tree_only(struct repository *r,
286
          const struct object_id *oid,
287
          void *cb_data UNUSED)
288
0
{
289
0
  int kind = odb_read_object_info(r->objects, oid, NULL);
290
0
  return kind == OBJ_TREE;
291
0
}
292
293
static int disambiguate_treeish_only(struct repository *r,
294
             const struct object_id *oid,
295
             void *cb_data UNUSED)
296
0
{
297
0
  struct object *obj;
298
0
  int kind;
299
300
0
  kind = odb_read_object_info(r->objects, oid, NULL);
301
0
  if (kind == OBJ_TREE || kind == OBJ_COMMIT)
302
0
    return 1;
303
0
  if (kind != OBJ_TAG)
304
0
    return 0;
305
306
  /* We need to do this the hard way... */
307
0
  obj = deref_tag(r, parse_object(r, oid), NULL, 0);
308
0
  if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
309
0
    return 1;
310
0
  return 0;
311
0
}
312
313
static int disambiguate_blob_only(struct repository *r,
314
          const struct object_id *oid,
315
          void *cb_data UNUSED)
316
0
{
317
0
  int kind = odb_read_object_info(r->objects, oid, NULL);
318
0
  return kind == OBJ_BLOB;
319
0
}
320
321
static disambiguate_hint_fn default_disambiguate_hint;
322
323
int set_disambiguate_hint_config(const char *var, const char *value)
324
0
{
325
0
  static const struct {
326
0
    const char *name;
327
0
    disambiguate_hint_fn fn;
328
0
  } hints[] = {
329
0
    { "none", NULL },
330
0
    { "commit", disambiguate_commit_only },
331
0
    { "committish", disambiguate_committish_only },
332
0
    { "tree", disambiguate_tree_only },
333
0
    { "treeish", disambiguate_treeish_only },
334
0
    { "blob", disambiguate_blob_only }
335
0
  };
336
0
  int i;
337
338
0
  if (!value)
339
0
    return config_error_nonbool(var);
340
341
0
  for (i = 0; i < ARRAY_SIZE(hints); i++) {
342
0
    if (!strcasecmp(value, hints[i].name)) {
343
0
      default_disambiguate_hint = hints[i].fn;
344
0
      return 0;
345
0
    }
346
0
  }
347
348
0
  return error("unknown hint type for '%s': %s", var, value);
349
0
}
350
351
static int init_object_disambiguation(struct repository *r,
352
              const char *name, int len,
353
              const struct git_hash_algo *algo,
354
              struct disambiguate_state *ds)
355
0
{
356
0
  int i;
357
358
0
  if (len < MINIMUM_ABBREV || len > GIT_MAX_HEXSZ)
359
0
    return -1;
360
361
0
  memset(ds, 0, sizeof(*ds));
362
363
0
  for (i = 0; i < len ;i++) {
364
0
    unsigned char c = name[i];
365
0
    unsigned char val;
366
0
    if (c >= '0' && c <= '9')
367
0
      val = c - '0';
368
0
    else if (c >= 'a' && c <= 'f')
369
0
      val = c - 'a' + 10;
370
0
    else if (c >= 'A' && c <='F') {
371
0
      val = c - 'A' + 10;
372
0
      c -= 'A' - 'a';
373
0
    }
374
0
    else
375
0
      return -1;
376
0
    ds->hex_pfx[i] = c;
377
0
    if (!(i & 1))
378
0
      val <<= 4;
379
0
    ds->bin_pfx.hash[i >> 1] |= val;
380
0
  }
381
382
0
  ds->len = len;
383
0
  ds->hex_pfx[len] = '\0';
384
0
  ds->repo = r;
385
0
  ds->bin_pfx.algo = algo ? hash_algo_by_ptr(algo) : GIT_HASH_UNKNOWN;
386
0
  odb_prepare_alternates(r->objects);
387
0
  return 0;
388
0
}
389
390
struct ambiguous_output {
391
  const struct disambiguate_state *ds;
392
  struct strbuf advice;
393
  struct strbuf sb;
394
};
395
396
static int show_ambiguous_object(const struct object_id *oid, void *data)
397
0
{
398
0
  struct ambiguous_output *state = data;
399
0
  const struct disambiguate_state *ds = state->ds;
400
0
  struct strbuf *advice = &state->advice;
401
0
  struct strbuf *sb = &state->sb;
402
0
  int type;
403
0
  const char *hash;
404
405
0
  if (ds->fn && !ds->fn(ds->repo, oid, ds->cb_data))
406
0
    return 0;
407
408
0
  hash = repo_find_unique_abbrev(ds->repo, oid, DEFAULT_ABBREV);
409
0
  type = odb_read_object_info(ds->repo->objects, oid, NULL);
410
411
0
  if (type < 0) {
412
    /*
413
     * TRANSLATORS: This is a line of ambiguous object
414
     * output shown when we cannot look up or parse the
415
     * object in question. E.g. "deadbeef [bad object]".
416
     */
417
0
    strbuf_addf(sb, _("%s [bad object]"), hash);
418
0
    goto out;
419
0
  }
420
421
0
  assert(type == OBJ_TREE || type == OBJ_COMMIT ||
422
0
         type == OBJ_BLOB || type == OBJ_TAG);
423
424
0
  if (type == OBJ_COMMIT) {
425
0
    struct strbuf date = STRBUF_INIT;
426
0
    struct strbuf msg = STRBUF_INIT;
427
0
    struct commit *commit = lookup_commit(ds->repo, oid);
428
429
0
    if (commit) {
430
0
      struct pretty_print_context pp = {0};
431
0
      pp.date_mode.type = DATE_SHORT;
432
0
      repo_format_commit_message(the_repository, commit,
433
0
               "%ad", &date, &pp);
434
0
      repo_format_commit_message(the_repository, commit,
435
0
               "%s", &msg, &pp);
436
0
    }
437
438
    /*
439
     * TRANSLATORS: This is a line of ambiguous commit
440
     * object output. E.g.:
441
     *
442
     *    "deadbeef commit 2021-01-01 - Some Commit Message"
443
     */
444
0
    strbuf_addf(sb, _("%s commit %s - %s"), hash, date.buf,
445
0
          msg.buf);
446
447
0
    strbuf_release(&date);
448
0
    strbuf_release(&msg);
449
0
  } else if (type == OBJ_TAG) {
450
0
    struct tag *tag = lookup_tag(ds->repo, oid);
451
452
0
    if (!parse_tag(tag) && tag->tag) {
453
      /*
454
       * TRANSLATORS: This is a line of ambiguous
455
       * tag object output. E.g.:
456
       *
457
       *    "deadbeef tag 2022-01-01 - Some Tag Message"
458
       *
459
       * The second argument is the YYYY-MM-DD found
460
       * in the tag.
461
       *
462
       * The third argument is the "tag" string
463
       * from object.c.
464
       */
465
0
      strbuf_addf(sb, _("%s tag %s - %s"), hash,
466
0
            show_date(tag->date, 0, DATE_MODE(SHORT)),
467
0
            tag->tag);
468
0
    } else {
469
      /*
470
       * TRANSLATORS: This is a line of ambiguous
471
       * tag object output where we couldn't parse
472
       * the tag itself. E.g.:
473
       *
474
       *    "deadbeef [bad tag, could not parse it]"
475
       */
476
0
      strbuf_addf(sb, _("%s [bad tag, could not parse it]"),
477
0
            hash);
478
0
    }
479
0
  } else if (type == OBJ_TREE) {
480
    /*
481
     * TRANSLATORS: This is a line of ambiguous <type>
482
     * object output. E.g. "deadbeef tree".
483
     */
484
0
    strbuf_addf(sb, _("%s tree"), hash);
485
0
  } else if (type == OBJ_BLOB) {
486
    /*
487
     * TRANSLATORS: This is a line of ambiguous <type>
488
     * object output. E.g. "deadbeef blob".
489
     */
490
0
    strbuf_addf(sb, _("%s blob"), hash);
491
0
  }
492
493
494
0
out:
495
  /*
496
   * TRANSLATORS: This is line item of ambiguous object output
497
   * from describe_ambiguous_object() above. For RTL languages
498
   * you'll probably want to swap the "%s" and leading " " space
499
   * around.
500
   */
501
0
  strbuf_addf(advice, _("  %s\n"), sb->buf);
502
503
0
  strbuf_reset(sb);
504
0
  return 0;
505
0
}
506
507
static int collect_ambiguous(const struct object_id *oid, void *data)
508
0
{
509
0
  oid_array_append(data, oid);
510
0
  return 0;
511
0
}
512
513
static int repo_collect_ambiguous(struct repository *r UNUSED,
514
          const struct object_id *oid,
515
          void *data)
516
0
{
517
0
  return collect_ambiguous(oid, data);
518
0
}
519
520
static int sort_ambiguous(const void *va, const void *vb, void *ctx)
521
0
{
522
0
  struct repository *sort_ambiguous_repo = ctx;
523
0
  const struct object_id *a = va, *b = vb;
524
0
  int a_type = odb_read_object_info(sort_ambiguous_repo->objects, a, NULL);
525
0
  int b_type = odb_read_object_info(sort_ambiguous_repo->objects, b, NULL);
526
0
  int a_type_sort;
527
0
  int b_type_sort;
528
529
  /*
530
   * Sorts by hash within the same object type, just as
531
   * oid_array_for_each_unique() would do.
532
   */
533
0
  if (a_type == b_type) {
534
0
    if (a->algo == b->algo)
535
0
      return oidcmp(a, b);
536
0
    else
537
0
      return a->algo > b->algo ? 1 : -1;
538
0
  }
539
540
  /*
541
   * Between object types show tags, then commits, and finally
542
   * trees and blobs.
543
   *
544
   * The object_type enum is commit, tree, blob, tag, but we
545
   * want tag, commit, tree blob. Cleverly (perhaps too
546
   * cleverly) do that with modulus, since the enum assigns 1 to
547
   * commit, so tag becomes 0.
548
   */
549
0
  a_type_sort = a_type % 4;
550
0
  b_type_sort = b_type % 4;
551
0
  return a_type_sort > b_type_sort ? 1 : -1;
552
0
}
553
554
static void sort_ambiguous_oid_array(struct repository *r, struct oid_array *a)
555
0
{
556
0
  QSORT_S(a->oid, a->nr, sort_ambiguous, r);
557
0
}
558
559
static enum get_oid_result get_short_oid(struct repository *r,
560
           const char *name, int len,
561
           struct object_id *oid,
562
           unsigned flags)
563
0
{
564
0
  int status;
565
0
  struct disambiguate_state ds;
566
0
  int quietly = !!(flags & GET_OID_QUIETLY);
567
0
  const struct git_hash_algo *algo = r->hash_algo;
568
569
0
  if (flags & GET_OID_HASH_ANY)
570
0
    algo = NULL;
571
572
0
  if (init_object_disambiguation(r, name, len, algo, &ds) < 0)
573
0
    return -1;
574
575
0
  if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
576
0
    BUG("multiple get_short_oid disambiguator flags");
577
578
0
  if (flags & GET_OID_COMMIT)
579
0
    ds.fn = disambiguate_commit_only;
580
0
  else if (flags & GET_OID_COMMITTISH)
581
0
    ds.fn = disambiguate_committish_only;
582
0
  else if (flags & GET_OID_TREE)
583
0
    ds.fn = disambiguate_tree_only;
584
0
  else if (flags & GET_OID_TREEISH)
585
0
    ds.fn = disambiguate_treeish_only;
586
0
  else if (flags & GET_OID_BLOB)
587
0
    ds.fn = disambiguate_blob_only;
588
0
  else
589
0
    ds.fn = default_disambiguate_hint;
590
591
0
  find_short_object_filename(&ds);
592
0
  find_short_packed_object(&ds);
593
0
  status = finish_object_disambiguation(&ds, oid);
594
595
  /*
596
   * If we didn't find it, do the usual reprepare() slow-path,
597
   * since the object may have recently been added to the repository
598
   * or migrated from loose to packed.
599
   */
600
0
  if (status == MISSING_OBJECT) {
601
0
    odb_reprepare(r->objects);
602
0
    find_short_object_filename(&ds);
603
0
    find_short_packed_object(&ds);
604
0
    status = finish_object_disambiguation(&ds, oid);
605
0
  }
606
607
0
  if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
608
0
    struct oid_array collect = OID_ARRAY_INIT;
609
0
    struct ambiguous_output out = {
610
0
      .ds = &ds,
611
0
      .sb = STRBUF_INIT,
612
0
      .advice = STRBUF_INIT,
613
0
    };
614
615
0
    error(_("short object ID %s is ambiguous"), ds.hex_pfx);
616
617
    /*
618
     * We may still have ambiguity if we simply saw a series of
619
     * candidates that did not satisfy our hint function. In
620
     * that case, we still want to show them, so disable the hint
621
     * function entirely.
622
     */
623
0
    if (!ds.ambiguous)
624
0
      ds.fn = NULL;
625
626
0
    repo_for_each_abbrev(r, ds.hex_pfx, algo, collect_ambiguous, &collect);
627
0
    sort_ambiguous_oid_array(r, &collect);
628
629
0
    if (oid_array_for_each(&collect, show_ambiguous_object, &out))
630
0
      BUG("show_ambiguous_object shouldn't return non-zero");
631
632
    /*
633
     * TRANSLATORS: The argument is the list of ambiguous
634
     * objects composed in show_ambiguous_object(). See
635
     * its "TRANSLATORS" comments for details.
636
     */
637
0
    advise(_("The candidates are:\n%s"), out.advice.buf);
638
639
0
    oid_array_clear(&collect);
640
0
    strbuf_release(&out.advice);
641
0
    strbuf_release(&out.sb);
642
0
  }
643
644
0
  return status;
645
0
}
646
647
int repo_for_each_abbrev(struct repository *r, const char *prefix,
648
       const struct git_hash_algo *algo,
649
       each_abbrev_fn fn, void *cb_data)
650
0
{
651
0
  struct oid_array collect = OID_ARRAY_INIT;
652
0
  struct disambiguate_state ds;
653
0
  int ret;
654
655
0
  if (init_object_disambiguation(r, prefix, strlen(prefix), algo, &ds) < 0)
656
0
    return -1;
657
658
0
  ds.always_call_fn = 1;
659
0
  ds.fn = repo_collect_ambiguous;
660
0
  ds.cb_data = &collect;
661
0
  find_short_object_filename(&ds);
662
0
  find_short_packed_object(&ds);
663
664
0
  ret = oid_array_for_each_unique(&collect, fn, cb_data);
665
0
  oid_array_clear(&collect);
666
0
  return ret;
667
0
}
668
669
/*
670
 * Return the slot of the most-significant bit set in "val". There are various
671
 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
672
 * probably not a big deal here.
673
 */
674
static unsigned msb(unsigned long val)
675
0
{
676
0
  unsigned r = 0;
677
0
  while (val >>= 1)
678
0
    r++;
679
0
  return r;
680
0
}
681
682
struct min_abbrev_data {
683
  unsigned int init_len;
684
  unsigned int cur_len;
685
  char *hex;
686
  struct repository *repo;
687
  const struct object_id *oid;
688
};
689
690
static inline char get_hex_char_from_oid(const struct object_id *oid,
691
           unsigned int pos)
692
0
{
693
0
  static const char hex[] = "0123456789abcdef";
694
695
0
  if ((pos & 1) == 0)
696
0
    return hex[oid->hash[pos >> 1] >> 4];
697
0
  else
698
0
    return hex[oid->hash[pos >> 1] & 0xf];
699
0
}
700
701
static int extend_abbrev_len(const struct object_id *oid,
702
           struct min_abbrev_data *mad)
703
0
{
704
0
  unsigned int i = mad->init_len;
705
0
  while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
706
0
    i++;
707
708
0
  if (mad->hex[i] && i >= mad->cur_len)
709
0
    mad->cur_len = i + 1;
710
711
0
  return 0;
712
0
}
713
714
static int repo_extend_abbrev_len(struct repository *r UNUSED,
715
          const struct object_id *oid,
716
          void *cb_data)
717
0
{
718
0
  return extend_abbrev_len(oid, cb_data);
719
0
}
720
721
static void find_abbrev_len_for_midx(struct multi_pack_index *m,
722
             struct min_abbrev_data *mad)
723
0
{
724
0
  for (; m; m = m->base_midx) {
725
0
    int match = 0;
726
0
    uint32_t num, first = 0;
727
0
    struct object_id oid;
728
0
    const struct object_id *mad_oid;
729
730
0
    if (!m->num_objects)
731
0
      continue;
732
733
0
    num = m->num_objects + m->num_objects_in_base;
734
0
    mad_oid = mad->oid;
735
0
    match = bsearch_one_midx(mad_oid, m, &first);
736
737
    /*
738
     * first is now the position in the packfile where we
739
     * would insert mad->hash if it does not exist (or the
740
     * position of mad->hash if it does exist). Hence, we
741
     * consider a maximum of two objects nearby for the
742
     * abbreviation length.
743
     */
744
0
    mad->init_len = 0;
745
0
    if (!match) {
746
0
      if (nth_midxed_object_oid(&oid, m, first))
747
0
        extend_abbrev_len(&oid, mad);
748
0
    } else if (first < num - 1) {
749
0
      if (nth_midxed_object_oid(&oid, m, first + 1))
750
0
        extend_abbrev_len(&oid, mad);
751
0
    }
752
0
    if (first > 0) {
753
0
      if (nth_midxed_object_oid(&oid, m, first - 1))
754
0
        extend_abbrev_len(&oid, mad);
755
0
    }
756
0
    mad->init_len = mad->cur_len;
757
0
  }
758
0
}
759
760
static void find_abbrev_len_for_pack(struct packed_git *p,
761
             struct min_abbrev_data *mad)
762
0
{
763
0
  int match = 0;
764
0
  uint32_t num, first = 0;
765
0
  struct object_id oid;
766
0
  const struct object_id *mad_oid;
767
768
0
  if (p->multi_pack_index)
769
0
    return;
770
771
0
  if (open_pack_index(p) || !p->num_objects)
772
0
    return;
773
774
0
  num = p->num_objects;
775
0
  mad_oid = mad->oid;
776
0
  match = bsearch_pack(mad_oid, p, &first);
777
778
  /*
779
   * first is now the position in the packfile where we would insert
780
   * mad->hash if it does not exist (or the position of mad->hash if
781
   * it does exist). Hence, we consider a maximum of two objects
782
   * nearby for the abbreviation length.
783
   */
784
0
  mad->init_len = 0;
785
0
  if (!match) {
786
0
    if (!nth_packed_object_id(&oid, p, first))
787
0
      extend_abbrev_len(&oid, mad);
788
0
  } else if (first < num - 1) {
789
0
    if (!nth_packed_object_id(&oid, p, first + 1))
790
0
      extend_abbrev_len(&oid, mad);
791
0
  }
792
0
  if (first > 0) {
793
0
    if (!nth_packed_object_id(&oid, p, first - 1))
794
0
      extend_abbrev_len(&oid, mad);
795
0
  }
796
0
  mad->init_len = mad->cur_len;
797
0
}
798
799
static void find_abbrev_len_packed(struct min_abbrev_data *mad)
800
0
{
801
0
  struct packed_git *p;
802
803
0
  odb_prepare_alternates(mad->repo->objects);
804
0
  for (struct odb_source *source = mad->repo->objects->sources; source; source = source->next) {
805
0
    struct multi_pack_index *m = get_multi_pack_index(source);
806
0
    if (m)
807
0
      find_abbrev_len_for_midx(m, mad);
808
0
  }
809
810
0
  repo_for_each_pack(mad->repo, p)
811
0
    find_abbrev_len_for_pack(p, mad);
812
0
}
813
814
void strbuf_repo_add_unique_abbrev(struct strbuf *sb, struct repository *repo,
815
           const struct object_id *oid, int abbrev_len)
816
0
{
817
0
  int r;
818
0
  strbuf_grow(sb, GIT_MAX_HEXSZ + 1);
819
0
  r = repo_find_unique_abbrev_r(repo, sb->buf + sb->len, oid, abbrev_len);
820
0
  strbuf_setlen(sb, sb->len + r);
821
0
}
822
823
void strbuf_add_unique_abbrev(struct strbuf *sb, const struct object_id *oid,
824
            int abbrev_len)
825
0
{
826
0
  strbuf_repo_add_unique_abbrev(sb, the_repository, oid, abbrev_len);
827
0
}
828
829
int repo_find_unique_abbrev_r(struct repository *r, char *hex,
830
            const struct object_id *oid, int len)
831
0
{
832
0
  const struct git_hash_algo *algo =
833
0
    oid->algo ? &hash_algos[oid->algo] : r->hash_algo;
834
0
  struct disambiguate_state ds;
835
0
  struct min_abbrev_data mad;
836
0
  struct object_id oid_ret;
837
0
  const unsigned hexsz = algo->hexsz;
838
839
0
  if (len < 0) {
840
0
    unsigned long count = repo_approximate_object_count(r);
841
    /*
842
     * Add one because the MSB only tells us the highest bit set,
843
     * not including the value of all the _other_ bits (so "15"
844
     * is only one off of 2^4, but the MSB is the 3rd bit.
845
     */
846
0
    len = msb(count) + 1;
847
    /*
848
     * We now know we have on the order of 2^len objects, which
849
     * expects a collision at 2^(len/2). But we also care about hex
850
     * chars, not bits, and there are 4 bits per hex. So all
851
     * together we need to divide by 2 and round up.
852
     */
853
0
    len = DIV_ROUND_UP(len, 2);
854
    /*
855
     * For very small repos, we stick with our regular fallback.
856
     */
857
0
    if (len < FALLBACK_DEFAULT_ABBREV)
858
0
      len = FALLBACK_DEFAULT_ABBREV;
859
0
  }
860
861
0
  oid_to_hex_r(hex, oid);
862
0
  if (len >= hexsz || !len)
863
0
    return hexsz;
864
865
0
  mad.repo = r;
866
0
  mad.init_len = len;
867
0
  mad.cur_len = len;
868
0
  mad.hex = hex;
869
0
  mad.oid = oid;
870
871
0
  find_abbrev_len_packed(&mad);
872
873
0
  if (init_object_disambiguation(r, hex, mad.cur_len, algo, &ds) < 0)
874
0
    return -1;
875
876
0
  ds.fn = repo_extend_abbrev_len;
877
0
  ds.always_call_fn = 1;
878
0
  ds.cb_data = (void *)&mad;
879
880
0
  find_short_object_filename(&ds);
881
0
  (void)finish_object_disambiguation(&ds, &oid_ret);
882
883
0
  hex[mad.cur_len] = 0;
884
0
  return mad.cur_len;
885
0
}
886
887
const char *repo_find_unique_abbrev(struct repository *r,
888
            const struct object_id *oid,
889
            int len)
890
0
{
891
0
  static int bufno;
892
0
  static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
893
0
  char *hex = hexbuffer[bufno];
894
0
  bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
895
0
  repo_find_unique_abbrev_r(r, hex, oid, len);
896
0
  return hex;
897
0
}
898
899
static int ambiguous_path(const char *path, int len)
900
0
{
901
0
  int slash = 1;
902
0
  int cnt;
903
904
0
  for (cnt = 0; cnt < len; cnt++) {
905
0
    switch (*path++) {
906
0
    case '\0':
907
0
      break;
908
0
    case '/':
909
0
      if (slash)
910
0
        break;
911
0
      slash = 1;
912
0
      continue;
913
0
    case '.':
914
0
      continue;
915
0
    default:
916
0
      slash = 0;
917
0
      continue;
918
0
    }
919
0
    break;
920
0
  }
921
0
  return slash;
922
0
}
923
924
static inline int at_mark(const char *string, int len,
925
        const char **suffix, int nr)
926
0
{
927
0
  int i;
928
929
0
  for (i = 0; i < nr; i++) {
930
0
    int suffix_len = strlen(suffix[i]);
931
0
    if (suffix_len <= len
932
0
        && !strncasecmp(string, suffix[i], suffix_len))
933
0
      return suffix_len;
934
0
  }
935
0
  return 0;
936
0
}
937
938
static inline int upstream_mark(const char *string, int len)
939
0
{
940
0
  const char *suffix[] = { "@{upstream}", "@{u}" };
941
0
  return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
942
0
}
943
944
static inline int push_mark(const char *string, int len)
945
0
{
946
0
  const char *suffix[] = { "@{push}" };
947
0
  return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
948
0
}
949
950
static enum get_oid_result get_oid_1(struct repository *r, const char *name, int len, struct object_id *oid, unsigned lookup_flags);
951
static int interpret_nth_prior_checkout(struct repository *r, const char *name, int namelen, struct strbuf *buf);
952
953
static int get_oid_basic(struct repository *r, const char *str, int len,
954
       struct object_id *oid, unsigned int flags)
955
0
{
956
0
  static const char *warn_msg = "refname '%.*s' is ambiguous.";
957
0
  static const char *object_name_msg = N_(
958
0
  "Git normally never creates a ref that ends with 40 hex characters\n"
959
0
  "because it will be ignored when you just specify 40-hex. These refs\n"
960
0
  "may be created by mistake. For example,\n"
961
0
  "\n"
962
0
  "  git switch -c $br $(git rev-parse ...)\n"
963
0
  "\n"
964
0
  "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
965
0
  "examine these refs and maybe delete them. Turn this message off by\n"
966
0
  "running \"git config set advice.objectNameWarning false\"");
967
0
  struct object_id tmp_oid;
968
0
  char *real_ref = NULL;
969
0
  int refs_found = 0;
970
0
  int at, reflog_len, nth_prior = 0;
971
0
  int fatal = !(flags & GET_OID_QUIETLY);
972
973
0
  if (len == r->hash_algo->hexsz && !get_oid_hex(str, oid)) {
974
0
    if (!(flags & GET_OID_SKIP_AMBIGUITY_CHECK) &&
975
0
        repo_settings_get_warn_ambiguous_refs(r) &&
976
0
        warn_on_object_refname_ambiguity) {
977
0
      refs_found = repo_dwim_ref(r, str, len, &tmp_oid, &real_ref, 0);
978
0
      if (refs_found > 0) {
979
0
        warning(warn_msg, len, str);
980
0
        if (advice_enabled(ADVICE_OBJECT_NAME_WARNING))
981
0
          fprintf(stderr, "%s\n", _(object_name_msg));
982
0
      }
983
0
      free(real_ref);
984
0
    }
985
0
    return 0;
986
0
  }
987
988
  /* basic@{time or number or -number} format to query ref-log */
989
0
  reflog_len = at = 0;
990
0
  if (len && str[len-1] == '}') {
991
0
    for (at = len-4; at >= 0; at--) {
992
0
      if (str[at] == '@' && str[at+1] == '{') {
993
0
        if (str[at+2] == '-') {
994
0
          if (at != 0)
995
            /* @{-N} not at start */
996
0
            return -1;
997
0
          nth_prior = 1;
998
0
          continue;
999
0
        }
1000
0
        if (!upstream_mark(str + at, len - at) &&
1001
0
            !push_mark(str + at, len - at)) {
1002
0
          reflog_len = (len-1) - (at+2);
1003
0
          len = at;
1004
0
        }
1005
0
        break;
1006
0
      }
1007
0
    }
1008
0
  }
1009
1010
  /* Accept only unambiguous ref paths. */
1011
0
  if (len && ambiguous_path(str, len))
1012
0
    return -1;
1013
1014
0
  if (nth_prior) {
1015
0
    struct strbuf buf = STRBUF_INIT;
1016
0
    int detached;
1017
1018
0
    if (interpret_nth_prior_checkout(r, str, len, &buf) > 0) {
1019
0
      detached = (buf.len == r->hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
1020
0
      strbuf_release(&buf);
1021
0
      if (detached)
1022
0
        return 0;
1023
0
    }
1024
0
  }
1025
1026
0
  if (!len && reflog_len)
1027
    /* allow "@{...}" to mean the current branch reflog */
1028
0
    refs_found = repo_dwim_ref(r, "HEAD", 4, oid, &real_ref, !fatal);
1029
0
  else if (reflog_len)
1030
0
    refs_found = repo_dwim_log(r, str, len, oid, &real_ref);
1031
0
  else
1032
0
    refs_found = repo_dwim_ref(r, str, len, oid, &real_ref, !fatal);
1033
1034
0
  if (!refs_found)
1035
0
    return -1;
1036
1037
0
  if (repo_settings_get_warn_ambiguous_refs(r) && !(flags & GET_OID_QUIETLY) &&
1038
0
      (refs_found > 1 ||
1039
0
       !get_short_oid(r, str, len, &tmp_oid, GET_OID_QUIETLY)))
1040
0
    warning(warn_msg, len, str);
1041
1042
0
  if (reflog_len) {
1043
0
    int nth, i;
1044
0
    timestamp_t at_time;
1045
0
    timestamp_t co_time;
1046
0
    int co_tz, co_cnt;
1047
1048
    /* Is it asking for N-th entry, or approxidate? */
1049
0
    for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
1050
0
      char ch = str[at+2+i];
1051
0
      if ('0' <= ch && ch <= '9')
1052
0
        nth = nth * 10 + ch - '0';
1053
0
      else
1054
0
        nth = -1;
1055
0
    }
1056
0
    if (100000000 <= nth) {
1057
0
      at_time = nth;
1058
0
      nth = -1;
1059
0
    } else if (0 <= nth)
1060
0
      at_time = 0;
1061
0
    else {
1062
0
      int errors = 0;
1063
0
      char *tmp = xstrndup(str + at + 2, reflog_len);
1064
0
      at_time = approxidate_careful(tmp, &errors);
1065
0
      free(tmp);
1066
0
      if (errors) {
1067
0
        free(real_ref);
1068
0
        return -1;
1069
0
      }
1070
0
    }
1071
0
    if (read_ref_at(get_main_ref_store(r),
1072
0
        real_ref, flags, at_time, nth, oid, NULL,
1073
0
        &co_time, &co_tz, &co_cnt)) {
1074
0
      if (!len) {
1075
0
        if (!skip_prefix(real_ref, "refs/heads/", &str))
1076
0
          str = "HEAD";
1077
0
        len = strlen(str);
1078
0
      }
1079
0
      if (at_time) {
1080
0
        if (!(flags & GET_OID_QUIETLY)) {
1081
0
          warning(_("log for '%.*s' only goes back to %s"),
1082
0
            len, str,
1083
0
            show_date(co_time, co_tz, DATE_MODE(RFC2822)));
1084
0
        }
1085
0
      } else if (nth == co_cnt && !is_null_oid(oid)) {
1086
        /*
1087
         * We were asked for the Nth reflog (counting
1088
         * from 0), but there were only N entries.
1089
         * read_ref_at() will have returned "1" to tell
1090
         * us it did not find an entry, but it did
1091
         * still fill in the oid with the "old" value,
1092
         * which we can use.
1093
         */
1094
0
      } else if (!(flags & GET_OID_GENTLY)) {
1095
0
        if (flags & GET_OID_QUIETLY) {
1096
0
          exit(128);
1097
0
        }
1098
0
        die(_("log for '%.*s' only has %d entries"),
1099
0
            len, str, co_cnt);
1100
0
      }
1101
0
      if (flags & GET_OID_GENTLY) {
1102
0
        free(real_ref);
1103
0
        return -1;
1104
0
      }
1105
0
    }
1106
0
  }
1107
1108
0
  free(real_ref);
1109
0
  return 0;
1110
0
}
1111
1112
static enum get_oid_result get_parent(struct repository *r,
1113
              const char *name, int len,
1114
              struct object_id *result, int idx)
1115
0
{
1116
0
  struct object_id oid;
1117
0
  enum get_oid_result ret = get_oid_1(r, name, len, &oid,
1118
0
              GET_OID_COMMITTISH);
1119
0
  struct commit *commit;
1120
0
  struct commit_list *p;
1121
1122
0
  if (ret)
1123
0
    return ret;
1124
0
  commit = lookup_commit_reference(r, &oid);
1125
0
  if (repo_parse_commit(r, commit))
1126
0
    return MISSING_OBJECT;
1127
0
  if (!idx) {
1128
0
    oidcpy(result, &commit->object.oid);
1129
0
    return FOUND;
1130
0
  }
1131
0
  p = commit->parents;
1132
0
  while (p) {
1133
0
    if (!--idx) {
1134
0
      oidcpy(result, &p->item->object.oid);
1135
0
      return FOUND;
1136
0
    }
1137
0
    p = p->next;
1138
0
  }
1139
0
  return MISSING_OBJECT;
1140
0
}
1141
1142
static enum get_oid_result get_nth_ancestor(struct repository *r,
1143
              const char *name, int len,
1144
              struct object_id *result,
1145
              int generation)
1146
0
{
1147
0
  struct object_id oid;
1148
0
  struct commit *commit;
1149
0
  int ret;
1150
1151
0
  ret = get_oid_1(r, name, len, &oid, GET_OID_COMMITTISH);
1152
0
  if (ret)
1153
0
    return ret;
1154
0
  commit = lookup_commit_reference(r, &oid);
1155
0
  if (!commit)
1156
0
    return MISSING_OBJECT;
1157
1158
0
  while (generation--) {
1159
0
    if (repo_parse_commit(r, commit) || !commit->parents)
1160
0
      return MISSING_OBJECT;
1161
0
    commit = commit->parents->item;
1162
0
  }
1163
0
  oidcpy(result, &commit->object.oid);
1164
0
  return FOUND;
1165
0
}
1166
1167
struct object *repo_peel_to_type(struct repository *r, const char *name, int namelen,
1168
         struct object *o, enum object_type expected_type)
1169
0
{
1170
0
  if (name && !namelen)
1171
0
    namelen = strlen(name);
1172
0
  while (1) {
1173
0
    if (!o || (!o->parsed && !parse_object(r, &o->oid)))
1174
0
      return NULL;
1175
0
    if (expected_type == OBJ_ANY || o->type == expected_type)
1176
0
      return o;
1177
0
    if (o->type == OBJ_TAG)
1178
0
      o = ((struct tag*) o)->tagged;
1179
0
    else if (o->type == OBJ_COMMIT)
1180
0
      o = &(repo_get_commit_tree(r, ((struct commit *)o))->object);
1181
0
    else {
1182
0
      if (name)
1183
0
        error("%.*s: expected %s type, but the object "
1184
0
              "dereferences to %s type",
1185
0
              namelen, name, type_name(expected_type),
1186
0
              type_name(o->type));
1187
0
      return NULL;
1188
0
    }
1189
0
  }
1190
0
}
1191
1192
static int peel_onion(struct repository *r, const char *name, int len,
1193
          struct object_id *oid, unsigned lookup_flags)
1194
0
{
1195
0
  struct object_id outer;
1196
0
  const char *sp;
1197
0
  unsigned int expected_type = 0;
1198
0
  struct object *o;
1199
1200
  /*
1201
   * "ref^{type}" dereferences ref repeatedly until you cannot
1202
   * dereference anymore, or you get an object of given type,
1203
   * whichever comes first.  "ref^{}" means just dereference
1204
   * tags until you get a non-tag.  "ref^0" is a shorthand for
1205
   * "ref^{commit}".  "commit^{tree}" could be used to find the
1206
   * top-level tree of the given commit.
1207
   */
1208
0
  if (len < 4 || name[len-1] != '}')
1209
0
    return -1;
1210
1211
0
  for (sp = name + len - 1; name <= sp; sp--) {
1212
0
    int ch = *sp;
1213
0
    if (ch == '{' && name < sp && sp[-1] == '^')
1214
0
      break;
1215
0
  }
1216
0
  if (sp <= name)
1217
0
    return -1;
1218
1219
0
  sp++; /* beginning of type name, or closing brace for empty */
1220
0
  if (starts_with(sp, "commit}"))
1221
0
    expected_type = OBJ_COMMIT;
1222
0
  else if (starts_with(sp, "tag}"))
1223
0
    expected_type = OBJ_TAG;
1224
0
  else if (starts_with(sp, "tree}"))
1225
0
    expected_type = OBJ_TREE;
1226
0
  else if (starts_with(sp, "blob}"))
1227
0
    expected_type = OBJ_BLOB;
1228
0
  else if (starts_with(sp, "object}"))
1229
0
    expected_type = OBJ_ANY;
1230
0
  else if (sp[0] == '}')
1231
0
    expected_type = OBJ_NONE;
1232
0
  else if (sp[0] == '/')
1233
0
    expected_type = OBJ_COMMIT;
1234
0
  else
1235
0
    return -1;
1236
1237
0
  lookup_flags &= ~GET_OID_DISAMBIGUATORS;
1238
0
  if (expected_type == OBJ_COMMIT)
1239
0
    lookup_flags |= GET_OID_COMMITTISH;
1240
0
  else if (expected_type == OBJ_TREE)
1241
0
    lookup_flags |= GET_OID_TREEISH;
1242
1243
0
  if (get_oid_1(r, name, sp - name - 2, &outer, lookup_flags))
1244
0
    return -1;
1245
1246
0
  o = parse_object(r, &outer);
1247
0
  if (!o)
1248
0
    return -1;
1249
0
  if (!expected_type) {
1250
0
    o = deref_tag(r, o, name, sp - name - 2);
1251
0
    if (!o || (!o->parsed && !parse_object(r, &o->oid)))
1252
0
      return -1;
1253
0
    oidcpy(oid, &o->oid);
1254
0
    return 0;
1255
0
  }
1256
1257
  /*
1258
   * At this point, the syntax look correct, so
1259
   * if we do not get the needed object, we should
1260
   * barf.
1261
   */
1262
0
  o = repo_peel_to_type(r, name, len, o, expected_type);
1263
0
  if (!o)
1264
0
    return -1;
1265
1266
0
  oidcpy(oid, &o->oid);
1267
0
  if (sp[0] == '/') {
1268
    /* "$commit^{/foo}" */
1269
0
    char *prefix;
1270
0
    int ret;
1271
0
    struct commit_list *list = NULL;
1272
1273
    /*
1274
     * $commit^{/}. Some regex implementation may reject.
1275
     * We don't need regex anyway. '' pattern always matches.
1276
     */
1277
0
    if (sp[1] == '}')
1278
0
      return 0;
1279
1280
0
    prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
1281
0
    commit_list_insert((struct commit *)o, &list);
1282
0
    ret = get_oid_oneline(r, prefix, oid, list);
1283
1284
0
    free_commit_list(list);
1285
0
    free(prefix);
1286
0
    return ret;
1287
0
  }
1288
0
  return 0;
1289
0
}
1290
1291
/*
1292
 * Documentation/revisions.adoc says:
1293
 *    '<describeOutput>', e.g. 'v1.7.4.2-679-g3bee7fb'::
1294
 *      Output from `git describe`; i.e. a closest tag, optionally
1295
 *      followed by a dash and a number of commits, followed by a dash, a
1296
 *      'g', and an abbreviated object name.
1297
 *
1298
 * which means that the stuff before '-g${HASH}' needs to be a valid
1299
 * refname, a dash, and a non-negative integer.  This function verifies
1300
 * that.
1301
 *
1302
 * In particular, we do not want to treat
1303
 *   branchname:path/to/file/named/i-gaffed
1304
 * as a request for commit affed.
1305
 *
1306
 * More generally, we should probably not treat
1307
 *   'refs/heads/./../.../ ~^:/?*[////\\\&}/busted.lock-g050e0ef6ead'
1308
 * as a request for object 050e0ef6ead either.
1309
 *
1310
 * We are called with name[len] == '-' and name[len+1] == 'g', i.e.
1311
 * we are verifying ${REFNAME}-{INTEGER} part of the name.
1312
 */
1313
static int ref_and_count_parts_valid(const char *name, int len)
1314
0
{
1315
0
  struct strbuf sb;
1316
0
  const char *cp;
1317
0
  int flags = REFNAME_ALLOW_ONELEVEL;
1318
0
  int ret = 1;
1319
1320
  /* Ensure we have at least one digit */
1321
0
  if (!isxdigit(name[len-1]))
1322
0
    return 0;
1323
1324
  /* Skip over digits backwards until we get to the dash */
1325
0
  for (cp = name + len - 2; name < cp; cp--) {
1326
0
    if (*cp == '-')
1327
0
      break;
1328
0
    if (!isxdigit(*cp))
1329
0
      return 0;
1330
0
  }
1331
  /* Ensure we found the leading dash */
1332
0
  if (*cp != '-')
1333
0
    return 0;
1334
1335
0
  len = cp - name;
1336
0
  strbuf_init(&sb, len);
1337
0
  strbuf_add(&sb, name, len);
1338
0
  ret = !check_refname_format(sb.buf, flags);
1339
0
  strbuf_release(&sb);
1340
0
  return ret;
1341
0
}
1342
1343
static int get_describe_name(struct repository *r,
1344
           const char *name, int len,
1345
           struct object_id *oid)
1346
0
{
1347
0
  const char *cp;
1348
0
  unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1349
1350
0
  for (cp = name + len - 1; name + 2 <= cp; cp--) {
1351
0
    char ch = *cp;
1352
0
    if (!isxdigit(ch)) {
1353
      /* We must be looking at g in "SOMETHING-g"
1354
       * for it to be describe output.
1355
       */
1356
0
      if (ch == 'g' && cp[-1] == '-' &&
1357
0
          ref_and_count_parts_valid(name, cp - 1 - name)) {
1358
0
        cp++;
1359
0
        len -= cp - name;
1360
0
        return get_short_oid(r,
1361
0
                 cp, len, oid, flags);
1362
0
      }
1363
0
    }
1364
0
  }
1365
0
  return -1;
1366
0
}
1367
1368
static enum get_oid_result get_oid_1(struct repository *r,
1369
             const char *name, int len,
1370
             struct object_id *oid,
1371
             unsigned lookup_flags)
1372
0
{
1373
0
  int ret, has_suffix;
1374
0
  const char *cp;
1375
1376
  /*
1377
   * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1378
   */
1379
0
  has_suffix = 0;
1380
0
  for (cp = name + len - 1; name <= cp; cp--) {
1381
0
    int ch = *cp;
1382
0
    if ('0' <= ch && ch <= '9')
1383
0
      continue;
1384
0
    if (ch == '~' || ch == '^')
1385
0
      has_suffix = ch;
1386
0
    break;
1387
0
  }
1388
1389
0
  if (has_suffix) {
1390
0
    unsigned int num = 0;
1391
0
    int len1 = cp - name;
1392
0
    cp++;
1393
0
    while (cp < name + len) {
1394
0
      unsigned int digit = *cp++ - '0';
1395
0
      if (unsigned_mult_overflows(num, 10))
1396
0
        return MISSING_OBJECT;
1397
0
      num *= 10;
1398
0
      if (unsigned_add_overflows(num, digit))
1399
0
        return MISSING_OBJECT;
1400
0
      num += digit;
1401
0
    }
1402
0
    if (!num && len1 == len - 1)
1403
0
      num = 1;
1404
0
    else if (num > INT_MAX)
1405
0
      return MISSING_OBJECT;
1406
0
    if (has_suffix == '^')
1407
0
      return get_parent(r, name, len1, oid, num);
1408
    /* else if (has_suffix == '~') -- goes without saying */
1409
0
    return get_nth_ancestor(r, name, len1, oid, num);
1410
0
  }
1411
1412
0
  ret = peel_onion(r, name, len, oid, lookup_flags);
1413
0
  if (!ret)
1414
0
    return FOUND;
1415
1416
0
  ret = get_oid_basic(r, name, len, oid, lookup_flags);
1417
0
  if (!ret)
1418
0
    return FOUND;
1419
1420
  /* It could be describe output that is "SOMETHING-gXXXX" */
1421
0
  ret = get_describe_name(r, name, len, oid);
1422
0
  if (!ret)
1423
0
    return FOUND;
1424
1425
0
  return get_short_oid(r, name, len, oid, lookup_flags);
1426
0
}
1427
1428
/*
1429
 * This interprets names like ':/Initial revision of "git"' by searching
1430
 * through history and returning the first commit whose message starts
1431
 * the given regular expression.
1432
 *
1433
 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1434
 *
1435
 * For a literal '!' character at the beginning of a pattern, you have to repeat
1436
 * that, like: ':/!!foo'
1437
 *
1438
 * For future extension, all other sequences beginning with ':/!' are reserved.
1439
 */
1440
1441
/* Remember to update object flag allocation in object.h */
1442
0
#define ONELINE_SEEN (1u<<20)
1443
1444
struct handle_one_ref_cb {
1445
  struct repository *repo;
1446
  struct commit_list **list;
1447
};
1448
1449
static int handle_one_ref(const struct reference *ref, void *cb_data)
1450
0
{
1451
0
  struct handle_one_ref_cb *cb = cb_data;
1452
0
  struct commit_list **list = cb->list;
1453
0
  struct object *object = parse_object(cb->repo, ref->oid);
1454
0
  if (!object)
1455
0
    return 0;
1456
0
  if (object->type == OBJ_TAG) {
1457
0
    object = deref_tag(cb->repo, object, ref->name,
1458
0
           strlen(ref->name));
1459
0
    if (!object)
1460
0
      return 0;
1461
0
  }
1462
0
  if (object->type != OBJ_COMMIT)
1463
0
    return 0;
1464
0
  commit_list_insert((struct commit *)object, list);
1465
0
  return 0;
1466
0
}
1467
1468
static int get_oid_oneline(struct repository *r,
1469
         const char *prefix, struct object_id *oid,
1470
         const struct commit_list *list)
1471
0
{
1472
0
  struct prio_queue copy = { compare_commits_by_commit_date };
1473
0
  const struct commit_list *l;
1474
0
  int found = 0;
1475
0
  int negative = 0;
1476
0
  regex_t regex;
1477
1478
0
  if (prefix[0] == '!') {
1479
0
    prefix++;
1480
1481
0
    if (prefix[0] == '-') {
1482
0
      prefix++;
1483
0
      negative = 1;
1484
0
    } else if (prefix[0] != '!') {
1485
0
      return -1;
1486
0
    }
1487
0
  }
1488
1489
0
  if (regcomp(&regex, prefix, REG_EXTENDED))
1490
0
    return -1;
1491
1492
0
  for (l = list; l; l = l->next) {
1493
0
    l->item->object.flags |= ONELINE_SEEN;
1494
0
    prio_queue_put(&copy, l->item);
1495
0
  }
1496
0
  while (copy.nr) {
1497
0
    const char *p, *buf;
1498
0
    struct commit *commit;
1499
0
    int matches;
1500
1501
0
    commit = pop_most_recent_commit(&copy, ONELINE_SEEN);
1502
0
    if (!parse_object(r, &commit->object.oid))
1503
0
      continue;
1504
0
    buf = repo_get_commit_buffer(r, commit, NULL);
1505
0
    p = strstr(buf, "\n\n");
1506
0
    matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
1507
0
    repo_unuse_commit_buffer(r, commit, buf);
1508
1509
0
    if (matches) {
1510
0
      oidcpy(oid, &commit->object.oid);
1511
0
      found = 1;
1512
0
      break;
1513
0
    }
1514
0
  }
1515
0
  regfree(&regex);
1516
0
  for (l = list; l; l = l->next)
1517
0
    clear_commit_marks(l->item, ONELINE_SEEN);
1518
0
  clear_prio_queue(&copy);
1519
0
  return found ? 0 : -1;
1520
0
}
1521
1522
struct grab_nth_branch_switch_cbdata {
1523
  int remaining;
1524
  struct strbuf *sb;
1525
};
1526
1527
static int grab_nth_branch_switch(const char *refname UNUSED,
1528
          struct object_id *ooid UNUSED,
1529
          struct object_id *noid UNUSED,
1530
          const char *email UNUSED,
1531
          timestamp_t timestamp UNUSED,
1532
          int tz UNUSED,
1533
          const char *message, void *cb_data)
1534
0
{
1535
0
  struct grab_nth_branch_switch_cbdata *cb = cb_data;
1536
0
  const char *match = NULL, *target = NULL;
1537
0
  size_t len;
1538
1539
0
  if (skip_prefix(message, "checkout: moving from ", &match))
1540
0
    target = strstr(match, " to ");
1541
1542
0
  if (!match || !target)
1543
0
    return 0;
1544
0
  if (--(cb->remaining) == 0) {
1545
0
    len = target - match;
1546
0
    strbuf_reset(cb->sb);
1547
0
    strbuf_add(cb->sb, match, len);
1548
0
    return 1; /* we are done */
1549
0
  }
1550
0
  return 0;
1551
0
}
1552
1553
/*
1554
 * Parse @{-N} syntax, return the number of characters parsed
1555
 * if successful; otherwise signal an error with negative value.
1556
 */
1557
static int interpret_nth_prior_checkout(struct repository *r,
1558
          const char *name, int namelen,
1559
          struct strbuf *buf)
1560
0
{
1561
0
  long nth;
1562
0
  int retval;
1563
0
  struct grab_nth_branch_switch_cbdata cb;
1564
0
  const char *brace;
1565
0
  char *num_end;
1566
1567
0
  if (namelen < 4)
1568
0
    return -1;
1569
0
  if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1570
0
    return -1;
1571
0
  brace = memchr(name, '}', namelen);
1572
0
  if (!brace)
1573
0
    return -1;
1574
0
  nth = strtol(name + 3, &num_end, 10);
1575
0
  if (num_end != brace)
1576
0
    return -1;
1577
0
  if (nth <= 0)
1578
0
    return -1;
1579
0
  cb.remaining = nth;
1580
0
  cb.sb = buf;
1581
1582
0
  retval = refs_for_each_reflog_ent_reverse(get_main_ref_store(r),
1583
0
      "HEAD", grab_nth_branch_switch, &cb);
1584
0
  if (0 < retval) {
1585
0
    retval = brace - name + 1;
1586
0
  } else
1587
0
    retval = 0;
1588
1589
0
  return retval;
1590
0
}
1591
1592
int repo_get_oid_mb(struct repository *r,
1593
        const char *name,
1594
        struct object_id *oid)
1595
0
{
1596
0
  struct commit *one, *two;
1597
0
  struct commit_list *mbs = NULL;
1598
0
  struct object_id oid_tmp;
1599
0
  const char *dots;
1600
0
  int st;
1601
1602
0
  dots = strstr(name, "...");
1603
0
  if (!dots)
1604
0
    return repo_get_oid(r, name, oid);
1605
0
  if (dots == name)
1606
0
    st = repo_get_oid(r, "HEAD", &oid_tmp);
1607
0
  else {
1608
0
    struct strbuf sb;
1609
0
    strbuf_init(&sb, dots - name);
1610
0
    strbuf_add(&sb, name, dots - name);
1611
0
    st = repo_get_oid_committish(r, sb.buf, &oid_tmp);
1612
0
    strbuf_release(&sb);
1613
0
  }
1614
0
  if (st)
1615
0
    return st;
1616
0
  one = lookup_commit_reference_gently(r, &oid_tmp, 0);
1617
0
  if (!one)
1618
0
    return -1;
1619
1620
0
  if (repo_get_oid_committish(r, dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1621
0
    return -1;
1622
0
  two = lookup_commit_reference_gently(r, &oid_tmp, 0);
1623
0
  if (!two)
1624
0
    return -1;
1625
0
  if (repo_get_merge_bases(r, one, two, &mbs) < 0) {
1626
0
    free_commit_list(mbs);
1627
0
    return -1;
1628
0
  }
1629
0
  if (!mbs || mbs->next)
1630
0
    st = -1;
1631
0
  else {
1632
0
    st = 0;
1633
0
    oidcpy(oid, &mbs->item->object.oid);
1634
0
  }
1635
0
  free_commit_list(mbs);
1636
0
  return st;
1637
0
}
1638
1639
/* parse @something syntax, when 'something' is not {.*} */
1640
static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1641
0
{
1642
0
  const char *next;
1643
1644
0
  if (len || name[1] == '{')
1645
0
    return -1;
1646
1647
  /* make sure it's a single @, or @@{.*}, not @foo */
1648
0
  next = memchr(name + len + 1, '@', namelen - len - 1);
1649
0
  if (next && next[1] != '{')
1650
0
    return -1;
1651
0
  if (!next)
1652
0
    next = name + namelen;
1653
0
  if (next != name + 1)
1654
0
    return -1;
1655
1656
0
  strbuf_reset(buf);
1657
0
  strbuf_add(buf, "HEAD", 4);
1658
0
  return 1;
1659
0
}
1660
1661
static int reinterpret(struct repository *r,
1662
           const char *name, int namelen, int len,
1663
           struct strbuf *buf, unsigned allowed)
1664
0
{
1665
  /* we have extra data, which might need further processing */
1666
0
  struct strbuf tmp = STRBUF_INIT;
1667
0
  int used = buf->len;
1668
0
  int ret;
1669
0
  struct interpret_branch_name_options options = {
1670
0
    .allowed = allowed
1671
0
  };
1672
1673
0
  strbuf_add(buf, name + len, namelen - len);
1674
0
  ret = repo_interpret_branch_name(r, buf->buf, buf->len, &tmp, &options);
1675
  /* that data was not interpreted, remove our cruft */
1676
0
  if (ret < 0) {
1677
0
    strbuf_setlen(buf, used);
1678
0
    return len;
1679
0
  }
1680
0
  strbuf_reset(buf);
1681
0
  strbuf_addbuf(buf, &tmp);
1682
0
  strbuf_release(&tmp);
1683
  /* tweak for size of {-N} versus expanded ref name */
1684
0
  return ret - used + len;
1685
0
}
1686
1687
static void set_shortened_ref(struct repository *r, struct strbuf *buf, const char *ref)
1688
0
{
1689
0
  char *s = refs_shorten_unambiguous_ref(get_main_ref_store(r), ref, 0);
1690
0
  strbuf_reset(buf);
1691
0
  strbuf_addstr(buf, s);
1692
0
  free(s);
1693
0
}
1694
1695
static int branch_interpret_allowed(const char *refname, unsigned allowed)
1696
0
{
1697
0
  if (!allowed)
1698
0
    return 1;
1699
1700
0
  if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1701
0
      starts_with(refname, "refs/heads/"))
1702
0
    return 1;
1703
0
  if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1704
0
      starts_with(refname, "refs/remotes/"))
1705
0
    return 1;
1706
1707
0
  return 0;
1708
0
}
1709
1710
static int interpret_branch_mark(struct repository *r,
1711
         const char *name, int namelen,
1712
         int at, struct strbuf *buf,
1713
         int (*get_mark)(const char *, int),
1714
         const char *(*get_data)(struct branch *,
1715
               struct strbuf *),
1716
         const struct interpret_branch_name_options *options)
1717
0
{
1718
0
  int len;
1719
0
  struct branch *branch;
1720
0
  struct strbuf err = STRBUF_INIT;
1721
0
  const char *value;
1722
1723
0
  len = get_mark(name + at, namelen - at);
1724
0
  if (!len)
1725
0
    return -1;
1726
1727
0
  if (memchr(name, ':', at))
1728
0
    return -1;
1729
1730
0
  if (at) {
1731
0
    char *name_str = xmemdupz(name, at);
1732
0
    branch = branch_get(name_str);
1733
0
    free(name_str);
1734
0
  } else
1735
0
    branch = branch_get(NULL);
1736
1737
0
  value = get_data(branch, &err);
1738
0
  if (!value) {
1739
0
    if (options->nonfatal_dangling_mark) {
1740
0
      strbuf_release(&err);
1741
0
      return -1;
1742
0
    } else {
1743
0
      die("%s", err.buf);
1744
0
    }
1745
0
  }
1746
1747
0
  if (!branch_interpret_allowed(value, options->allowed))
1748
0
    return -1;
1749
1750
0
  set_shortened_ref(r, buf, value);
1751
0
  return len + at;
1752
0
}
1753
1754
int repo_interpret_branch_name(struct repository *r,
1755
             const char *name, int namelen,
1756
             struct strbuf *buf,
1757
             const struct interpret_branch_name_options *options)
1758
0
{
1759
0
  char *at;
1760
0
  const char *start;
1761
0
  int len;
1762
1763
0
  if (!namelen)
1764
0
    namelen = strlen(name);
1765
1766
0
  if (!options->allowed || (options->allowed & INTERPRET_BRANCH_LOCAL)) {
1767
0
    len = interpret_nth_prior_checkout(r, name, namelen, buf);
1768
0
    if (!len) {
1769
0
      return len; /* syntax Ok, not enough switches */
1770
0
    } else if (len > 0) {
1771
0
      if (len == namelen)
1772
0
        return len; /* consumed all */
1773
0
      else
1774
0
        return reinterpret(r, name, namelen, len, buf,
1775
0
               options->allowed);
1776
0
    }
1777
0
  }
1778
1779
0
  for (start = name;
1780
0
       (at = memchr(start, '@', namelen - (start - name)));
1781
0
       start = at + 1) {
1782
1783
0
    if (!options->allowed || (options->allowed & INTERPRET_BRANCH_HEAD)) {
1784
0
      len = interpret_empty_at(name, namelen, at - name, buf);
1785
0
      if (len > 0)
1786
0
        return reinterpret(r, name, namelen, len, buf,
1787
0
               options->allowed);
1788
0
    }
1789
1790
0
    len = interpret_branch_mark(r, name, namelen, at - name, buf,
1791
0
              upstream_mark, branch_get_upstream,
1792
0
              options);
1793
0
    if (len > 0)
1794
0
      return len;
1795
1796
0
    len = interpret_branch_mark(r, name, namelen, at - name, buf,
1797
0
              push_mark, branch_get_push,
1798
0
              options);
1799
0
    if (len > 0)
1800
0
      return len;
1801
0
  }
1802
1803
0
  return -1;
1804
0
}
1805
1806
void object_context_release(struct object_context *ctx)
1807
0
{
1808
0
  free(ctx->path);
1809
0
  strbuf_release(&ctx->symlink_path);
1810
0
}
1811
1812
int repo_get_oid_with_flags(struct repository *r, const char *name,
1813
          struct object_id *oid, unsigned flags)
1814
0
{
1815
0
  struct object_context unused;
1816
0
  int ret = get_oid_with_context(r, name, flags, oid, &unused);
1817
0
  object_context_release(&unused);
1818
0
  return ret;
1819
0
}
1820
1821
int repo_get_oid(struct repository *r, const char *name, struct object_id *oid)
1822
0
{
1823
0
  return repo_get_oid_with_flags(r, name, oid, 0);
1824
0
}
1825
1826
/*
1827
 * This returns a non-zero value if the string (built using printf
1828
 * format and the given arguments) is not a valid object.
1829
 */
1830
int get_oidf(struct object_id *oid, const char *fmt, ...)
1831
0
{
1832
0
  va_list ap;
1833
0
  int ret;
1834
0
  struct strbuf sb = STRBUF_INIT;
1835
1836
0
  va_start(ap, fmt);
1837
0
  strbuf_vaddf(&sb, fmt, ap);
1838
0
  va_end(ap);
1839
1840
0
  ret = repo_get_oid(the_repository, sb.buf, oid);
1841
0
  strbuf_release(&sb);
1842
1843
0
  return ret;
1844
0
}
1845
1846
/*
1847
 * Many callers know that the user meant to name a commit-ish by
1848
 * syntactical positions where the object name appears.  Calling this
1849
 * function allows the machinery to disambiguate shorter-than-unique
1850
 * abbreviated object names between commit-ish and others.
1851
 *
1852
 * Note that this does NOT error out when the named object is not a
1853
 * commit-ish. It is merely to give a hint to the disambiguation
1854
 * machinery.
1855
 */
1856
int repo_get_oid_committish(struct repository *r,
1857
          const char *name,
1858
          struct object_id *oid)
1859
0
{
1860
0
  return repo_get_oid_with_flags(r, name, oid, GET_OID_COMMITTISH);
1861
0
}
1862
1863
int repo_get_oid_treeish(struct repository *r,
1864
       const char *name,
1865
       struct object_id *oid)
1866
0
{
1867
0
  return repo_get_oid_with_flags(r, name, oid, GET_OID_TREEISH);
1868
0
}
1869
1870
int repo_get_oid_commit(struct repository *r,
1871
      const char *name,
1872
      struct object_id *oid)
1873
0
{
1874
0
  return repo_get_oid_with_flags(r, name, oid, GET_OID_COMMIT);
1875
0
}
1876
1877
int repo_get_oid_tree(struct repository *r,
1878
          const char *name,
1879
          struct object_id *oid)
1880
0
{
1881
0
  return repo_get_oid_with_flags(r, name, oid, GET_OID_TREE);
1882
0
}
1883
1884
int repo_get_oid_blob(struct repository *r,
1885
          const char *name,
1886
          struct object_id *oid)
1887
0
{
1888
0
  return repo_get_oid_with_flags(r, name, oid, GET_OID_BLOB);
1889
0
}
1890
1891
/* Must be called only when object_name:filename doesn't exist. */
1892
static void diagnose_invalid_oid_path(struct repository *r,
1893
              const char *prefix,
1894
              const char *filename,
1895
              const struct object_id *tree_oid,
1896
              const char *object_name,
1897
              int object_name_len)
1898
0
{
1899
0
  struct object_id oid;
1900
0
  unsigned short mode;
1901
1902
0
  if (!prefix)
1903
0
    prefix = "";
1904
1905
0
  if (file_exists(filename))
1906
0
    die(_("path '%s' exists on disk, but not in '%.*s'"),
1907
0
        filename, object_name_len, object_name);
1908
0
  if (is_missing_file_error(errno)) {
1909
0
    char *fullname = xstrfmt("%s%s", prefix, filename);
1910
1911
0
    if (!get_tree_entry(r, tree_oid, fullname, &oid, &mode)) {
1912
0
      die(_("path '%s' exists, but not '%s'\n"
1913
0
          "hint: Did you mean '%.*s:%s' aka '%.*s:./%s'?"),
1914
0
          fullname,
1915
0
          filename,
1916
0
          object_name_len, object_name,
1917
0
          fullname,
1918
0
          object_name_len, object_name,
1919
0
          filename);
1920
0
    }
1921
0
    die(_("path '%s' does not exist in '%.*s'"),
1922
0
        filename, object_name_len, object_name);
1923
0
  }
1924
0
}
1925
1926
/* Must be called only when :stage:filename doesn't exist. */
1927
static void diagnose_invalid_index_path(struct repository *r,
1928
          int stage,
1929
          const char *prefix,
1930
          const char *filename)
1931
0
{
1932
0
  struct index_state *istate = r->index;
1933
0
  const struct cache_entry *ce;
1934
0
  int pos;
1935
0
  unsigned namelen = strlen(filename);
1936
0
  struct strbuf fullname = STRBUF_INIT;
1937
1938
0
  if (!prefix)
1939
0
    prefix = "";
1940
1941
  /* Wrong stage number? */
1942
0
  pos = index_name_pos(istate, filename, namelen);
1943
0
  if (pos < 0)
1944
0
    pos = -pos - 1;
1945
0
  if (pos < istate->cache_nr) {
1946
0
    ce = istate->cache[pos];
1947
0
    if (!S_ISSPARSEDIR(ce->ce_mode) &&
1948
0
        ce_namelen(ce) == namelen &&
1949
0
        !memcmp(ce->name, filename, namelen))
1950
0
      die(_("path '%s' is in the index, but not at stage %d\n"
1951
0
          "hint: Did you mean ':%d:%s'?"),
1952
0
          filename, stage,
1953
0
          ce_stage(ce), filename);
1954
0
  }
1955
1956
  /* Confusion between relative and absolute filenames? */
1957
0
  strbuf_addstr(&fullname, prefix);
1958
0
  strbuf_addstr(&fullname, filename);
1959
0
  pos = index_name_pos(istate, fullname.buf, fullname.len);
1960
0
  if (pos < 0)
1961
0
    pos = -pos - 1;
1962
0
  if (pos < istate->cache_nr) {
1963
0
    ce = istate->cache[pos];
1964
0
    if (!S_ISSPARSEDIR(ce->ce_mode) &&
1965
0
        ce_namelen(ce) == fullname.len &&
1966
0
        !memcmp(ce->name, fullname.buf, fullname.len))
1967
0
      die(_("path '%s' is in the index, but not '%s'\n"
1968
0
          "hint: Did you mean ':%d:%s' aka ':%d:./%s'?"),
1969
0
          fullname.buf, filename,
1970
0
          ce_stage(ce), fullname.buf,
1971
0
          ce_stage(ce), filename);
1972
0
  }
1973
1974
0
  if (repo_file_exists(r, filename))
1975
0
    die(_("path '%s' exists on disk, but not in the index"), filename);
1976
0
  if (is_missing_file_error(errno))
1977
0
    die(_("path '%s' does not exist (neither on disk nor in the index)"),
1978
0
        filename);
1979
1980
0
  strbuf_release(&fullname);
1981
0
}
1982
1983
1984
static char *resolve_relative_path(struct repository *r, const char *rel)
1985
0
{
1986
0
  if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1987
0
    return NULL;
1988
1989
0
  if (r != the_repository || !is_inside_work_tree())
1990
0
    die(_("relative path syntax can't be used outside working tree"));
1991
1992
  /* die() inside prefix_path() if resolved path is outside worktree */
1993
0
  return prefix_path(startup_info->prefix,
1994
0
         startup_info->prefix ? strlen(startup_info->prefix) : 0,
1995
0
         rel);
1996
0
}
1997
1998
static int reject_tree_in_index(struct repository *repo,
1999
        int only_to_die,
2000
        const struct cache_entry *ce,
2001
        int stage,
2002
        const char *prefix,
2003
        const char *cp)
2004
0
{
2005
0
  if (!S_ISSPARSEDIR(ce->ce_mode))
2006
0
    return 0;
2007
0
  if (only_to_die)
2008
0
    diagnose_invalid_index_path(repo, stage, prefix, cp);
2009
0
  return -1;
2010
0
}
2011
2012
static enum get_oid_result get_oid_with_context_1(struct repository *repo,
2013
          const char *name,
2014
          unsigned flags,
2015
          const char *prefix,
2016
          struct object_id *oid,
2017
          struct object_context *oc)
2018
0
{
2019
0
  int ret, bracket_depth;
2020
0
  int namelen = strlen(name);
2021
0
  const char *cp;
2022
0
  int only_to_die = flags & GET_OID_ONLY_TO_DIE;
2023
2024
0
  memset(oc, 0, sizeof(*oc));
2025
0
  oc->mode = S_IFINVALID;
2026
0
  strbuf_init(&oc->symlink_path, 0);
2027
0
  ret = get_oid_1(repo, name, namelen, oid, flags);
2028
0
  if (!ret && flags & GET_OID_REQUIRE_PATH)
2029
0
    die(_("<object>:<path> required, only <object> '%s' given"),
2030
0
        name);
2031
0
  if (!ret)
2032
0
    return ret;
2033
  /*
2034
   * tree:path --> object name of path in tree
2035
   * :path -> object name of absolute path in index
2036
   * :./path -> object name of path relative to cwd in index
2037
   * :[0-3]:path -> object name of path in index at stage
2038
   * :/foo -> recent commit matching foo
2039
   */
2040
0
  if (name[0] == ':') {
2041
0
    int stage = 0;
2042
0
    const struct cache_entry *ce;
2043
0
    char *new_path = NULL;
2044
0
    int pos;
2045
0
    if (!only_to_die && namelen > 2 && name[1] == '/') {
2046
0
      struct handle_one_ref_cb cb;
2047
0
      struct commit_list *list = NULL;
2048
2049
0
      cb.repo = repo;
2050
0
      cb.list = &list;
2051
0
      refs_for_each_ref(get_main_ref_store(repo), handle_one_ref, &cb);
2052
0
      refs_head_ref(get_main_ref_store(repo), handle_one_ref, &cb);
2053
0
      ret = get_oid_oneline(repo, name + 2, oid, list);
2054
2055
0
      free_commit_list(list);
2056
0
      return ret;
2057
0
    }
2058
0
    if (namelen < 3 ||
2059
0
        name[2] != ':' ||
2060
0
        name[1] < '0' || '3' < name[1])
2061
0
      cp = name + 1;
2062
0
    else {
2063
0
      stage = name[1] - '0';
2064
0
      cp = name + 3;
2065
0
    }
2066
0
    new_path = resolve_relative_path(repo, cp);
2067
0
    if (!new_path) {
2068
0
      namelen = namelen - (cp - name);
2069
0
    } else {
2070
0
      cp = new_path;
2071
0
      namelen = strlen(cp);
2072
0
    }
2073
2074
0
    if (flags & GET_OID_RECORD_PATH)
2075
0
      oc->path = xstrdup(cp);
2076
2077
0
    if (!repo->index || !repo->index->cache)
2078
0
      repo_read_index(repo);
2079
0
    pos = index_name_pos(repo->index, cp, namelen);
2080
0
    if (pos < 0)
2081
0
      pos = -pos - 1;
2082
0
    while (pos < repo->index->cache_nr) {
2083
0
      ce = repo->index->cache[pos];
2084
0
      if (ce_namelen(ce) != namelen ||
2085
0
          memcmp(ce->name, cp, namelen))
2086
0
        break;
2087
0
      if (ce_stage(ce) == stage) {
2088
0
        free(new_path);
2089
0
        if (reject_tree_in_index(repo, only_to_die, ce,
2090
0
               stage, prefix, cp))
2091
0
          return -1;
2092
0
        oidcpy(oid, &ce->oid);
2093
0
        oc->mode = ce->ce_mode;
2094
0
        return 0;
2095
0
      }
2096
0
      pos++;
2097
0
    }
2098
0
    if (only_to_die && name[1] && name[1] != '/')
2099
0
      diagnose_invalid_index_path(repo, stage, prefix, cp);
2100
0
    free(new_path);
2101
0
    return -1;
2102
0
  }
2103
0
  for (cp = name, bracket_depth = 0; *cp; cp++) {
2104
0
    if (strchr("@^", *cp) && cp[1] == '{') {
2105
0
      cp++;
2106
0
      bracket_depth++;
2107
0
    } else if (bracket_depth && *cp == '}') {
2108
0
      bracket_depth--;
2109
0
    } else if (!bracket_depth && *cp == ':') {
2110
0
      break;
2111
0
    }
2112
0
  }
2113
0
  if (*cp == ':') {
2114
0
    struct object_id tree_oid;
2115
0
    int len = cp - name;
2116
0
    unsigned sub_flags = flags;
2117
2118
0
    sub_flags &= ~GET_OID_DISAMBIGUATORS;
2119
0
    sub_flags |= GET_OID_TREEISH;
2120
2121
0
    if (!get_oid_1(repo, name, len, &tree_oid, sub_flags)) {
2122
0
      const char *filename = cp+1;
2123
0
      char *new_filename = NULL;
2124
2125
0
      new_filename = resolve_relative_path(repo, filename);
2126
0
      if (new_filename)
2127
0
        filename = new_filename;
2128
0
      if (flags & GET_OID_FOLLOW_SYMLINKS) {
2129
0
        ret = get_tree_entry_follow_symlinks(repo, &tree_oid,
2130
0
          filename, oid, &oc->symlink_path,
2131
0
          &oc->mode);
2132
0
      } else {
2133
0
        ret = get_tree_entry(repo, &tree_oid, filename, oid,
2134
0
                 &oc->mode);
2135
0
        if (ret && only_to_die) {
2136
0
          diagnose_invalid_oid_path(repo, prefix,
2137
0
                   filename,
2138
0
                   &tree_oid,
2139
0
                   name, len);
2140
0
        }
2141
0
      }
2142
0
      if (flags & GET_OID_RECORD_PATH)
2143
0
        oc->path = xstrdup(filename);
2144
2145
0
      free(new_filename);
2146
0
      return ret;
2147
0
    } else {
2148
0
      if (only_to_die)
2149
0
        die(_("invalid object name '%.*s'."), len, name);
2150
0
    }
2151
0
  }
2152
0
  return ret;
2153
0
}
2154
2155
/*
2156
 * Call this function when you know "name" given by the end user must
2157
 * name an object but it doesn't; the function _may_ die with a better
2158
 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
2159
 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
2160
 * you have a chance to diagnose the error further.
2161
 */
2162
void maybe_die_on_misspelt_object_name(struct repository *r,
2163
               const char *name,
2164
               const char *prefix)
2165
0
{
2166
0
  struct object_context oc;
2167
0
  struct object_id oid;
2168
0
  get_oid_with_context_1(r, name, GET_OID_ONLY_TO_DIE | GET_OID_QUIETLY,
2169
0
             prefix, &oid, &oc);
2170
0
  object_context_release(&oc);
2171
0
}
2172
2173
enum get_oid_result get_oid_with_context(struct repository *repo,
2174
           const char *str,
2175
           unsigned flags,
2176
           struct object_id *oid,
2177
           struct object_context *oc)
2178
0
{
2179
0
  if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
2180
0
    BUG("incompatible flags for get_oid_with_context");
2181
0
  return get_oid_with_context_1(repo, str, flags, NULL, oid, oc);
2182
0
}