]> git.ipfire.org Git - thirdparty/git.git/blame - sha1-name.c
sha1_name.c: rename to use dash in file name
[thirdparty/git.git] / sha1-name.c
CommitLineData
9938af6a 1#include "cache.h"
b2141fc1 2#include "config.h"
5385f52d 3#include "tag.h"
9938af6a 4#include "commit.h"
5385f52d
JH
5#include "tree.h"
6#include "blob.h"
f3ab49db 7#include "tree-walk.h"
d556fae2 8#include "refs.h"
28fb8438 9#include "remote.h"
dbe44faa 10#include "dir.h"
fad6b9e5 11#include "sha1-array.h"
0317f455 12#include "packfile.h"
0d4a1321 13#include "object-store.h"
031dc927 14#include "repository.h"
9938af6a 15
e82caf38 16static int get_oid_oneline(const char *, struct object_id *, struct commit_list *);
32574b68 17
d2b7d9c7 18typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
a78fafe7
JH
19
20struct disambiguate_state {
0016043b 21 int len; /* length of prefix in hex chars */
dc01505f 22 char hex_pfx[GIT_MAX_HEXSZ + 1];
d2ee1185 23 struct object_id bin_pfx;
0016043b 24
a78fafe7
JH
25 disambiguate_hint_fn fn;
26 void *cb_data;
d2ee1185 27 struct object_id candidate;
a78fafe7
JH
28 unsigned candidate_exists:1;
29 unsigned candidate_checked:1;
30 unsigned candidate_ok:1;
31 unsigned disambiguate_fn_used:1;
32 unsigned ambiguous:1;
957d7406 33 unsigned always_call_fn:1;
a78fafe7
JH
34};
35
d2b7d9c7 36static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
a78fafe7 37{
957d7406
JH
38 if (ds->always_call_fn) {
39 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
40 return;
41 }
a78fafe7
JH
42 if (!ds->candidate_exists) {
43 /* this is the first candidate */
d2b7d9c7 44 oidcpy(&ds->candidate, current);
a78fafe7
JH
45 ds->candidate_exists = 1;
46 return;
d2b7d9c7 47 } else if (!oidcmp(&ds->candidate, current)) {
a78fafe7
JH
48 /* the same as what we already have seen */
49 return;
50 }
51
52 if (!ds->fn) {
53 /* cannot disambiguate between ds->candidate and current */
54 ds->ambiguous = 1;
55 return;
56 }
57
58 if (!ds->candidate_checked) {
d2b7d9c7 59 ds->candidate_ok = ds->fn(&ds->candidate, ds->cb_data);
a78fafe7
JH
60 ds->disambiguate_fn_used = 1;
61 ds->candidate_checked = 1;
62 }
63
64 if (!ds->candidate_ok) {
749f763d 65 /* discard the candidate; we know it does not satisfy fn */
d2b7d9c7 66 oidcpy(&ds->candidate, current);
a78fafe7
JH
67 ds->candidate_checked = 0;
68 return;
69 }
70
71 /* if we reach this point, we know ds->candidate satisfies fn */
72 if (ds->fn(current, ds->cb_data)) {
73 /*
74 * if both current and candidate satisfy fn, we cannot
75 * disambiguate.
76 */
77 ds->candidate_ok = 0;
78 ds->ambiguous = 1;
79 }
80
81 /* otherwise, current can be discarded and candidate is still good */
82}
83
cc817ca3
RS
84static int append_loose_object(const struct object_id *oid, const char *path,
85 void *data)
86{
87 oid_array_append(data, oid);
88 return 0;
89}
90
91static int match_sha(unsigned, const unsigned char *, const unsigned char *);
92
0016043b 93static void find_short_object_filename(struct disambiguate_state *ds)
9938af6a 94{
cc817ca3 95 int subdir_nr = ds->bin_pfx.hash[0];
99a19b43 96 struct alternate_object_database *alt;
99a19b43
JH
97 static struct alternate_object_database *fakeent;
98
99 if (!fakeent) {
274ac009
JH
100 /*
101 * Create a "fake" alternate object database that
102 * points to our own object database, to make it
103 * easier to get a temporary working space in
104 * alt->name/alt->base while iterating over the
105 * object databases including our own.
106 */
7f0fa2c0 107 fakeent = alloc_alt_odb(get_object_directory());
99a19b43 108 }
031dc927 109 fakeent->next = the_repository->objects->alt_odb_list;
9938af6a 110
a78fafe7 111 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
cc817ca3
RS
112 int pos;
113
114 if (!alt->loose_objects_subdir_seen[subdir_nr]) {
115 struct strbuf *buf = alt_scratch_buf(alt);
cc817ca3
RS
116 for_each_file_in_obj_subdir(subdir_nr, buf,
117 append_loose_object,
118 NULL, NULL,
119 &alt->loose_objects_cache);
120 alt->loose_objects_subdir_seen[subdir_nr] = 1;
121 }
a78fafe7 122
cc817ca3
RS
123 pos = oid_array_lookup(&alt->loose_objects_cache, &ds->bin_pfx);
124 if (pos < 0)
125 pos = -1 - pos;
126 while (!ds->ambiguous && pos < alt->loose_objects_cache.nr) {
127 const struct object_id *oid;
128 oid = alt->loose_objects_cache.oid + pos;
129 if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
130 break;
131 update_candidates(ds, oid);
132 pos++;
9938af6a 133 }
9938af6a 134 }
9938af6a
JH
135}
136
137static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
138{
139 do {
140 if (*a != *b)
141 return 0;
142 a++;
143 b++;
144 len -= 2;
145 } while (len > 1);
146 if (len)
147 if ((*a ^ *b) & 0xf0)
148 return 0;
149 return 1;
150}
151
0016043b 152static void unique_in_pack(struct packed_git *p,
a78fafe7 153 struct disambiguate_state *ds)
9938af6a 154{
902f5a21 155 uint32_t num, i, first = 0;
d2b7d9c7 156 const struct object_id *current = NULL;
f703e6ea 157
0e87b856
DS
158 if (open_pack_index(p) || !p->num_objects)
159 return;
160
f703e6ea 161 num = p->num_objects;
902f5a21 162 bsearch_pack(&ds->bin_pfx, p, &first);
f703e6ea
JH
163
164 /*
165 * At this point, "first" is the location of the lowest object
1703f9aa 166 * with an object name that could match "bin_pfx". See if we have
f703e6ea
JH
167 * 0, 1 or more objects that actually match(es).
168 */
a78fafe7 169 for (i = first; i < num && !ds->ambiguous; i++) {
d2b7d9c7 170 struct object_id oid;
171 current = nth_packed_object_oid(&oid, p, i);
172 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
f703e6ea 173 break;
a78fafe7 174 update_candidates(ds, current);
9938af6a 175 }
f703e6ea
JH
176}
177
0016043b 178static void find_short_packed_object(struct disambiguate_state *ds)
9938af6a
JH
179{
180 struct packed_git *p;
181
a80d72db
SB
182 for (p = get_packed_git(the_repository); p && !ds->ambiguous;
183 p = p->next)
0016043b 184 unique_in_pack(p, ds);
99a19b43
JH
185}
186
013f276e
JH
187#define SHORT_NAME_NOT_FOUND (-1)
188#define SHORT_NAME_AMBIGUOUS (-2)
189
a78fafe7 190static int finish_object_disambiguation(struct disambiguate_state *ds,
e82caf38 191 struct object_id *oid)
99a19b43 192{
a78fafe7
JH
193 if (ds->ambiguous)
194 return SHORT_NAME_AMBIGUOUS;
99a19b43 195
a78fafe7 196 if (!ds->candidate_exists)
013f276e 197 return SHORT_NAME_NOT_FOUND;
a78fafe7
JH
198
199 if (!ds->candidate_checked)
200 /*
201 * If this is the only candidate, there is no point
202 * calling the disambiguation hint callback.
203 *
204 * On the other hand, if the current candidate
205 * replaced an earlier candidate that did _not_ pass
206 * the disambiguation hint callback, then we do have
207 * more than one objects that match the short name
208 * given, so we should make sure this one matches;
209 * otherwise, if we discovered this one and the one
210 * that we previously discarded in the reverse order,
211 * we would end up showing different results in the
212 * same repository!
213 */
214 ds->candidate_ok = (!ds->disambiguate_fn_used ||
d2b7d9c7 215 ds->fn(&ds->candidate, ds->cb_data));
a78fafe7
JH
216
217 if (!ds->candidate_ok)
013f276e 218 return SHORT_NAME_AMBIGUOUS;
a78fafe7 219
e82caf38 220 oidcpy(oid, &ds->candidate);
9938af6a
JH
221 return 0;
222}
223
d2b7d9c7 224static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
aa1dec9e 225{
abef9020 226 int kind = oid_object_info(oid, NULL);
aa1dec9e
JH
227 return kind == OBJ_COMMIT;
228}
229
d2b7d9c7 230static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
e2643617
JH
231{
232 struct object *obj;
233 int kind;
234
abef9020 235 kind = oid_object_info(oid, NULL);
e2643617
JH
236 if (kind == OBJ_COMMIT)
237 return 1;
238 if (kind != OBJ_TAG)
99a19b43 239 return 0;
e2643617
JH
240
241 /* We need to do this the hard way... */
c251c83d 242 obj = deref_tag(parse_object(oid), NULL, 0);
e2643617
JH
243 if (obj && obj->type == OBJ_COMMIT)
244 return 1;
9938af6a
JH
245 return 0;
246}
247
d2b7d9c7 248static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
9938af6a 249{
abef9020 250 int kind = oid_object_info(oid, NULL);
daba53ae
JH
251 return kind == OBJ_TREE;
252}
9938af6a 253
d2b7d9c7 254static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
daba53ae
JH
255{
256 struct object *obj;
257 int kind;
258
abef9020 259 kind = oid_object_info(oid, NULL);
daba53ae
JH
260 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
261 return 1;
262 if (kind != OBJ_TAG)
263 return 0;
264
265 /* We need to do this the hard way... */
c251c83d 266 obj = deref_tag(parse_object(oid), NULL, 0);
daba53ae
JH
267 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
268 return 1;
269 return 0;
270}
271
d2b7d9c7 272static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
daba53ae 273{
abef9020 274 int kind = oid_object_info(oid, NULL);
daba53ae
JH
275 return kind == OBJ_BLOB;
276}
277
5b33cb1f
JK
278static disambiguate_hint_fn default_disambiguate_hint;
279
280int set_disambiguate_hint_config(const char *var, const char *value)
281{
282 static const struct {
283 const char *name;
284 disambiguate_hint_fn fn;
285 } hints[] = {
286 { "none", NULL },
287 { "commit", disambiguate_commit_only },
288 { "committish", disambiguate_committish_only },
289 { "tree", disambiguate_tree_only },
290 { "treeish", disambiguate_treeish_only },
291 { "blob", disambiguate_blob_only }
292 };
293 int i;
294
295 if (!value)
296 return config_error_nonbool(var);
297
298 for (i = 0; i < ARRAY_SIZE(hints); i++) {
299 if (!strcasecmp(value, hints[i].name)) {
300 default_disambiguate_hint = hints[i].fn;
301 return 0;
302 }
303 }
304
305 return error("unknown hint type for '%s': %s", var, value);
306}
307
0016043b
JK
308static int init_object_disambiguation(const char *name, int len,
309 struct disambiguate_state *ds)
9938af6a 310{
957d7406 311 int i;
9938af6a 312
0016043b
JK
313 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
314 return -1;
315
316 memset(ds, 0, sizeof(*ds));
0016043b 317
af61c6e0 318 for (i = 0; i < len ;i++) {
9938af6a
JH
319 unsigned char c = name[i];
320 unsigned char val;
9938af6a
JH
321 if (c >= '0' && c <= '9')
322 val = c - '0';
323 else if (c >= 'a' && c <= 'f')
324 val = c - 'a' + 10;
325 else if (c >= 'A' && c <='F') {
326 val = c - 'A' + 10;
327 c -= 'A' - 'a';
328 }
329 else
330 return -1;
0016043b 331 ds->hex_pfx[i] = c;
9938af6a
JH
332 if (!(i & 1))
333 val <<= 4;
d2ee1185 334 ds->bin_pfx.hash[i >> 1] |= val;
9938af6a 335 }
0016043b
JK
336
337 ds->len = len;
59e4e34f 338 ds->hex_pfx[len] = '\0';
0b209034 339 prepare_alt_odb(the_repository);
957d7406
JH
340 return 0;
341}
342
1b7ba794 343static int show_ambiguous_object(const struct object_id *oid, void *data)
1ffa26c4
JK
344{
345 const struct disambiguate_state *ds = data;
346 struct strbuf desc = STRBUF_INIT;
347 int type;
348
d2b7d9c7 349
1b7ba794 350 if (ds->fn && !ds->fn(oid, ds->cb_data))
1ffa26c4
JK
351 return 0;
352
abef9020 353 type = oid_object_info(oid, NULL);
1ffa26c4 354 if (type == OBJ_COMMIT) {
bc83266a 355 struct commit *commit = lookup_commit(oid);
1ffa26c4
JK
356 if (commit) {
357 struct pretty_print_context pp = {0};
358 pp.date_mode.type = DATE_SHORT;
359 format_commit_message(commit, " %ad - %s", &desc, &pp);
360 }
361 } else if (type == OBJ_TAG) {
d3101b53 362 struct tag *tag = lookup_tag(oid);
1ffa26c4
JK
363 if (!parse_tag(tag) && tag->tag)
364 strbuf_addf(&desc, " %s", tag->tag);
365 }
366
367 advise(" %s %s%s",
aab9583f 368 find_unique_abbrev(oid, DEFAULT_ABBREV),
debca9d2 369 type_name(type) ? type_name(type) : "unknown type",
1ffa26c4
JK
370 desc.buf);
371
372 strbuf_release(&desc);
373 return 0;
374}
375
e82caf38 376static int get_short_oid(const char *name, int len, struct object_id *oid,
957d7406
JH
377 unsigned flags)
378{
379 int status;
957d7406 380 struct disambiguate_state ds;
321c89bf 381 int quietly = !!(flags & GET_OID_QUIETLY);
957d7406 382
0016043b 383 if (init_object_disambiguation(name, len, &ds) < 0)
957d7406 384 return -1;
99a19b43 385
321c89bf 386 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
e82caf38 387 die("BUG: multiple get_short_oid disambiguator flags");
259942f5 388
321c89bf 389 if (flags & GET_OID_COMMIT)
aa1dec9e 390 ds.fn = disambiguate_commit_only;
321c89bf 391 else if (flags & GET_OID_COMMITTISH)
e2643617 392 ds.fn = disambiguate_committish_only;
321c89bf 393 else if (flags & GET_OID_TREE)
daba53ae 394 ds.fn = disambiguate_tree_only;
321c89bf 395 else if (flags & GET_OID_TREEISH)
daba53ae 396 ds.fn = disambiguate_treeish_only;
321c89bf 397 else if (flags & GET_OID_BLOB)
daba53ae 398 ds.fn = disambiguate_blob_only;
5b33cb1f
JK
399 else
400 ds.fn = default_disambiguate_hint;
aa1dec9e 401
0016043b
JK
402 find_short_object_filename(&ds);
403 find_short_packed_object(&ds);
e82caf38 404 status = finish_object_disambiguation(&ds, oid);
99a19b43 405
1ffa26c4
JK
406 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
407 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
408
409 /*
410 * We may still have ambiguity if we simply saw a series of
411 * candidates that did not satisfy our hint function. In
412 * that case, we still want to show them, so disable the hint
413 * function entirely.
414 */
415 if (!ds.ambiguous)
416 ds.fn = NULL;
417
418 advise(_("The candidates are:"));
419 for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
420 }
421
013f276e
JH
422 return status;
423}
424
d2b7d9c7 425static int collect_ambiguous(const struct object_id *oid, void *data)
fad6b9e5 426{
910650d2 427 oid_array_append(data, oid);
fad6b9e5
JK
428 return 0;
429}
430
957d7406
JH
431int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
432{
910650d2 433 struct oid_array collect = OID_ARRAY_INIT;
957d7406 434 struct disambiguate_state ds;
fad6b9e5 435 int ret;
957d7406 436
0016043b 437 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
957d7406 438 return -1;
957d7406 439
957d7406 440 ds.always_call_fn = 1;
fad6b9e5
JK
441 ds.fn = collect_ambiguous;
442 ds.cb_data = &collect;
0016043b
JK
443 find_short_object_filename(&ds);
444 find_short_packed_object(&ds);
fad6b9e5 445
910650d2 446 ret = oid_array_for_each_unique(&collect, fn, cb_data);
447 oid_array_clear(&collect);
fad6b9e5 448 return ret;
957d7406
JH
449}
450
8e3f52d7
JK
451/*
452 * Return the slot of the most-significant bit set in "val". There are various
453 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
454 * probably not a big deal here.
455 */
456static unsigned msb(unsigned long val)
457{
458 unsigned r = 0;
459 while (val >>= 1)
460 r++;
461 return r;
462}
463
5b20ace6
DS
464struct min_abbrev_data {
465 unsigned int init_len;
466 unsigned int cur_len;
467 char *hex;
626fd982 468 const struct object_id *oid;
5b20ace6
DS
469};
470
a42d6fd2
DS
471static inline char get_hex_char_from_oid(const struct object_id *oid,
472 unsigned int pos)
473{
474 static const char hex[] = "0123456789abcdef";
475
476 if ((pos & 1) == 0)
477 return hex[oid->hash[pos >> 1] >> 4];
478 else
479 return hex[oid->hash[pos >> 1] & 0xf];
480}
481
5b20ace6 482static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
013f276e 483{
5b20ace6 484 struct min_abbrev_data *mad = cb_data;
47dd0d59 485
5b20ace6 486 unsigned int i = mad->init_len;
a42d6fd2 487 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
5b20ace6
DS
488 i++;
489
490 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
491 mad->cur_len = i + 1;
492
493 return 0;
494}
495
0e87b856
DS
496static void find_abbrev_len_for_pack(struct packed_git *p,
497 struct min_abbrev_data *mad)
013f276e 498{
0e87b856 499 int match = 0;
0aaf05b3 500 uint32_t num, first = 0;
0e87b856 501 struct object_id oid;
0aaf05b3 502 const struct object_id *mad_oid;
0e87b856
DS
503
504 if (open_pack_index(p) || !p->num_objects)
505 return;
506
507 num = p->num_objects;
0aaf05b3
DS
508 mad_oid = mad->oid;
509 match = bsearch_pack(mad_oid, p, &first);
0e87b856
DS
510
511 /*
512 * first is now the position in the packfile where we would insert
513 * mad->hash if it does not exist (or the position of mad->hash if
21abed50 514 * it does exist). Hence, we consider a maximum of two objects
0e87b856
DS
515 * nearby for the abbreviation length.
516 */
517 mad->init_len = 0;
518 if (!match) {
21abed50
DS
519 if (nth_packed_object_oid(&oid, p, first))
520 extend_abbrev_len(&oid, mad);
0e87b856 521 } else if (first < num - 1) {
21abed50
DS
522 if (nth_packed_object_oid(&oid, p, first + 1))
523 extend_abbrev_len(&oid, mad);
0e87b856
DS
524 }
525 if (first > 0) {
21abed50
DS
526 if (nth_packed_object_oid(&oid, p, first - 1))
527 extend_abbrev_len(&oid, mad);
0e87b856
DS
528 }
529 mad->init_len = mad->cur_len;
530}
531
532static void find_abbrev_len_packed(struct min_abbrev_data *mad)
533{
534 struct packed_git *p;
535
a80d72db 536 for (p = get_packed_git(the_repository); p; p = p->next)
0e87b856
DS
537 find_abbrev_len_for_pack(p, mad);
538}
539
aab9583f 540int find_unique_abbrev_r(char *hex, const struct object_id *oid, int len)
5b20ace6
DS
541{
542 struct disambiguate_state ds;
543 struct min_abbrev_data mad;
544 struct object_id oid_ret;
e6c587c7 545 if (len < 0) {
8e3f52d7
JK
546 unsigned long count = approximate_object_count();
547 /*
548 * Add one because the MSB only tells us the highest bit set,
549 * not including the value of all the _other_ bits (so "15"
550 * is only one off of 2^4, but the MSB is the 3rd bit.
551 */
552 len = msb(count) + 1;
553 /*
554 * We now know we have on the order of 2^len objects, which
555 * expects a collision at 2^(len/2). But we also care about hex
556 * chars, not bits, and there are 4 bits per hex. So all
42c78a21 557 * together we need to divide by 2 and round up.
8e3f52d7 558 */
42c78a21 559 len = DIV_ROUND_UP(len, 2);
8e3f52d7
JK
560 /*
561 * For very small repos, we stick with our regular fallback.
562 */
563 if (len < FALLBACK_DEFAULT_ABBREV)
564 len = FALLBACK_DEFAULT_ABBREV;
e6c587c7 565 }
8e3f52d7 566
aab9583f 567 oid_to_hex_r(hex, oid);
ac53fe86 568 if (len == GIT_SHA1_HEXSZ || !len)
569 return GIT_SHA1_HEXSZ;
5b20ace6 570
5b20ace6
DS
571 mad.init_len = len;
572 mad.cur_len = len;
573 mad.hex = hex;
626fd982 574 mad.oid = oid;
0e87b856
DS
575
576 find_abbrev_len_packed(&mad);
577
578 if (init_object_disambiguation(hex, mad.cur_len, &ds) < 0)
579 return -1;
5b20ace6
DS
580
581 ds.fn = extend_abbrev_len;
582 ds.always_call_fn = 1;
583 ds.cb_data = (void *)&mad;
584
585 find_short_object_filename(&ds);
5b20ace6
DS
586 (void)finish_object_disambiguation(&ds, &oid_ret);
587
588 hex[mad.cur_len] = 0;
589 return mad.cur_len;
af49c6d0
JK
590}
591
aab9583f 592const char *find_unique_abbrev(const struct object_id *oid, int len)
af49c6d0 593{
ef2ed501 594 static int bufno;
dc01505f 595 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
3e98919a
RS
596 char *hex = hexbuffer[bufno];
597 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
aab9583f 598 find_unique_abbrev_r(hex, oid, len);
b66fde9a 599 return hex;
9938af6a
JH
600}
601
6677c466 602static int ambiguous_path(const char *path, int len)
af13cdf2
LT
603{
604 int slash = 1;
6677c466 605 int cnt;
af13cdf2 606
6677c466 607 for (cnt = 0; cnt < len; cnt++) {
af13cdf2
LT
608 switch (*path++) {
609 case '\0':
610 break;
611 case '/':
612 if (slash)
613 break;
614 slash = 1;
615 continue;
616 case '.':
617 continue;
618 default:
619 slash = 0;
620 continue;
621 }
c054d64e 622 break;
af13cdf2 623 }
6677c466 624 return slash;
af13cdf2
LT
625}
626
a1ad0eb0
JK
627static inline int at_mark(const char *string, int len,
628 const char **suffix, int nr)
ae0ba8e2 629{
ae0ba8e2
JH
630 int i;
631
a1ad0eb0 632 for (i = 0; i < nr; i++) {
ae0ba8e2
JH
633 int suffix_len = strlen(suffix[i]);
634 if (suffix_len <= len
244ea1b5 635 && !strncasecmp(string, suffix[i], suffix_len))
ae0ba8e2
JH
636 return suffix_len;
637 }
638 return 0;
639}
640
a1ad0eb0
JK
641static inline int upstream_mark(const char *string, int len)
642{
643 const char *suffix[] = { "@{upstream}", "@{u}" };
644 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
645}
646
adfe5d04
JK
647static inline int push_mark(const char *string, int len)
648{
649 const char *suffix[] = { "@{push}" };
650 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
651}
652
e82caf38 653static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags);
8cd4249c 654static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
d18ba221 655
e82caf38 656static int get_oid_basic(const char *str, int len, struct object_id *oid,
c41a87dd 657 unsigned int flags)
e86eb666 658{
eedce784 659 static const char *warn_msg = "refname '%.*s' is ambiguous.";
798c35fc
NTND
660 static const char *object_name_msg = N_(
661 "Git normally never creates a ref that ends with 40 hex characters\n"
662 "because it will be ignored when you just specify 40-hex. These refs\n"
663 "may be created by mistake. For example,\n"
664 "\n"
665 " git checkout -b $br $(git rev-parse ...)\n"
666 "\n"
667 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
668 "examine these refs and maybe delete them. Turn this message off by\n"
8dc84fdc 669 "running \"git config advice.objectNameWarning false\"");
e82caf38 670 struct object_id tmp_oid;
ed378ec7 671 char *real_ref = NULL;
ab2a1a32 672 int refs_found = 0;
128fd54d 673 int at, reflog_len, nth_prior = 0;
9938af6a 674
e82caf38 675 if (len == GIT_SHA1_HEXSZ && !get_oid_hex(str, oid)) {
832cf74c 676 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
cca5fa64 677 refs_found = dwim_ref(str, len, &tmp_oid, &real_ref);
832cf74c 678 if (refs_found > 0) {
25fba78d
JK
679 warning(warn_msg, len, str);
680 if (advice_object_name_warning)
681 fprintf(stderr, "%s\n", _(object_name_msg));
682 }
683 free(real_ref);
798c35fc 684 }
9938af6a 685 return 0;
798c35fc 686 }
9938af6a 687
d18ba221 688 /* basic@{time or number or -number} format to query ref-log */
694500ed 689 reflog_len = at = 0;
f265458f 690 if (len && str[len-1] == '}') {
e883a057 691 for (at = len-4; at >= 0; at--) {
ab2a1a32 692 if (str[at] == '@' && str[at+1] == '{') {
83d16bc7
RR
693 if (str[at+2] == '-') {
694 if (at != 0)
695 /* @{-N} not at start */
696 return -1;
128fd54d
FC
697 nth_prior = 1;
698 continue;
699 }
adfe5d04
JK
700 if (!upstream_mark(str + at, len - at) &&
701 !push_mark(str + at, len - at)) {
28fb8438
JS
702 reflog_len = (len-1) - (at+2);
703 len = at;
704 }
ab2a1a32
JH
705 break;
706 }
d556fae2
SP
707 }
708 }
709
af13cdf2 710 /* Accept only unambiguous ref paths. */
11cf8801 711 if (len && ambiguous_path(str, len))
af13cdf2
LT
712 return -1;
713
128fd54d 714 if (nth_prior) {
d18ba221 715 struct strbuf buf = STRBUF_INIT;
128fd54d
FC
716 int detached;
717
8cd4249c 718 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
e82caf38 719 detached = (buf.len == GIT_SHA1_HEXSZ && !get_oid_hex(buf.buf, oid));
128fd54d
FC
720 strbuf_release(&buf);
721 if (detached)
722 return 0;
d18ba221 723 }
128fd54d
FC
724 }
725
726 if (!len && reflog_len)
11cf8801 727 /* allow "@{...}" to mean the current branch reflog */
cca5fa64 728 refs_found = dwim_ref("HEAD", 4, oid, &real_ref);
128fd54d 729 else if (reflog_len)
334dc52f 730 refs_found = dwim_log(str, len, oid, &real_ref);
f2eba66d 731 else
cca5fa64 732 refs_found = dwim_ref(str, len, oid, &real_ref);
d556fae2
SP
733
734 if (!refs_found)
735 return -1;
736
321c89bf 737 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
798c35fc 738 (refs_found > 1 ||
321c89bf 739 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
eedce784 740 warning(warn_msg, len, str);
d556fae2 741
ab2a1a32 742 if (reflog_len) {
ab2a1a32 743 int nth, i;
dddbad72
JS
744 timestamp_t at_time;
745 timestamp_t co_time;
16d7cc90
JH
746 int co_tz, co_cnt;
747
fe558516 748 /* Is it asking for N-th entry, or approxidate? */
ab2a1a32
JH
749 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
750 char ch = str[at+2+i];
751 if ('0' <= ch && ch <= '9')
752 nth = nth * 10 + ch - '0';
753 else
754 nth = -1;
755 }
ea360dd0
SP
756 if (100000000 <= nth) {
757 at_time = nth;
758 nth = -1;
759 } else if (0 <= nth)
ab2a1a32 760 at_time = 0;
861f00e3 761 else {
93cfa7c7 762 int errors = 0;
861f00e3 763 char *tmp = xstrndup(str + at + 2, reflog_len);
93cfa7c7 764 at_time = approxidate_careful(tmp, &errors);
861f00e3 765 free(tmp);
28b35632
JK
766 if (errors) {
767 free(real_ref);
a5e10acb 768 return -1;
28b35632 769 }
861f00e3 770 }
8eb36d94 771 if (read_ref_at(real_ref, flags, at_time, nth, oid, NULL,
16d7cc90 772 &co_time, &co_tz, &co_cnt)) {
305ebea0 773 if (!len) {
59556548 774 if (starts_with(real_ref, "refs/heads/")) {
305ebea0
RR
775 str = real_ref + 11;
776 len = strlen(real_ref + 11);
777 } else {
778 /* detached HEAD */
779 str = "HEAD";
780 len = 4;
781 }
782 }
c41a87dd 783 if (at_time) {
321c89bf 784 if (!(flags & GET_OID_QUIETLY)) {
c41a87dd
DA
785 warning("Log for '%.*s' only goes "
786 "back to %s.", len, str,
a5481a6c 787 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
c41a87dd
DA
788 }
789 } else {
321c89bf 790 if (flags & GET_OID_QUIETLY) {
c41a87dd
DA
791 exit(128);
792 }
e6eedc31
JS
793 die("Log for '%.*s' only has %d entries.",
794 len, str, co_cnt);
795 }
16d7cc90 796 }
d556fae2
SP
797 }
798
ed378ec7 799 free(real_ref);
d556fae2 800 return 0;
9938af6a
JH
801}
802
9938af6a 803static int get_parent(const char *name, int len,
e82caf38 804 struct object_id *result, int idx)
9938af6a 805{
1e43ed98 806 struct object_id oid;
321c89bf 807 int ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
9938af6a
JH
808 struct commit *commit;
809 struct commit_list *p;
810
811 if (ret)
812 return ret;
bc83266a 813 commit = lookup_commit_reference(&oid);
9938af6a
JH
814 if (parse_commit(commit))
815 return -1;
816 if (!idx) {
e82caf38 817 oidcpy(result, &commit->object.oid);
9938af6a
JH
818 return 0;
819 }
820 p = commit->parents;
821 while (p) {
822 if (!--idx) {
e82caf38 823 oidcpy(result, &p->item->object.oid);
9938af6a
JH
824 return 0;
825 }
826 p = p->next;
827 }
828 return -1;
829}
830
4f7599ac 831static int get_nth_ancestor(const char *name, int len,
e82caf38 832 struct object_id *result, int generation)
4f7599ac 833{
1e43ed98 834 struct object_id oid;
621ff675
LT
835 struct commit *commit;
836 int ret;
837
321c89bf 838 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
4f7599ac
JH
839 if (ret)
840 return ret;
bc83266a 841 commit = lookup_commit_reference(&oid);
621ff675
LT
842 if (!commit)
843 return -1;
4f7599ac
JH
844
845 while (generation--) {
621ff675 846 if (parse_commit(commit) || !commit->parents)
4f7599ac 847 return -1;
621ff675 848 commit = commit->parents->item;
4f7599ac 849 }
e82caf38 850 oidcpy(result, &commit->object.oid);
4f7599ac
JH
851 return 0;
852}
853
81776315
JH
854struct object *peel_to_type(const char *name, int namelen,
855 struct object *o, enum object_type expected_type)
856{
857 if (name && !namelen)
858 namelen = strlen(name);
81776315 859 while (1) {
c251c83d 860 if (!o || (!o->parsed && !parse_object(&o->oid)))
81776315 861 return NULL;
a6a3f2cc 862 if (expected_type == OBJ_ANY || o->type == expected_type)
81776315
JH
863 return o;
864 if (o->type == OBJ_TAG)
865 o = ((struct tag*) o)->tagged;
866 else if (o->type == OBJ_COMMIT)
867 o = &(((struct commit *) o)->tree->object);
868 else {
869 if (name)
870 error("%.*s: expected %s type, but the object "
871 "dereferences to %s type",
debca9d2
BW
872 namelen, name, type_name(expected_type),
873 type_name(o->type));
81776315
JH
874 return NULL;
875 }
876 }
877}
878
e82caf38 879static int peel_onion(const char *name, int len, struct object_id *oid,
8a10fea4 880 unsigned lookup_flags)
5385f52d 881{
de37d50d 882 struct object_id outer;
5385f52d 883 const char *sp;
885a86ab 884 unsigned int expected_type = 0;
5385f52d
JH
885 struct object *o;
886
887 /*
888 * "ref^{type}" dereferences ref repeatedly until you cannot
889 * dereference anymore, or you get an object of given type,
890 * whichever comes first. "ref^{}" means just dereference
891 * tags until you get a non-tag. "ref^0" is a shorthand for
892 * "ref^{commit}". "commit^{tree}" could be used to find the
893 * top-level tree of the given commit.
894 */
895 if (len < 4 || name[len-1] != '}')
896 return -1;
897
898 for (sp = name + len - 1; name <= sp; sp--) {
899 int ch = *sp;
900 if (ch == '{' && name < sp && sp[-1] == '^')
901 break;
902 }
903 if (sp <= name)
904 return -1;
905
906 sp++; /* beginning of type name, or closing brace for empty */
59556548 907 if (starts_with(sp, "commit}"))
1974632c 908 expected_type = OBJ_COMMIT;
59556548 909 else if (starts_with(sp, "tag}"))
75aa26d3 910 expected_type = OBJ_TAG;
59556548 911 else if (starts_with(sp, "tree}"))
1974632c 912 expected_type = OBJ_TREE;
59556548 913 else if (starts_with(sp, "blob}"))
1974632c 914 expected_type = OBJ_BLOB;
59556548 915 else if (starts_with(sp, "object}"))
a6a3f2cc 916 expected_type = OBJ_ANY;
5385f52d 917 else if (sp[0] == '}')
1974632c 918 expected_type = OBJ_NONE;
32574b68
NTND
919 else if (sp[0] == '/')
920 expected_type = OBJ_COMMIT;
5385f52d
JH
921 else
922 return -1;
923
321c89bf 924 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
e2643617 925 if (expected_type == OBJ_COMMIT)
321c89bf 926 lookup_flags |= GET_OID_COMMITTISH;
ed1ca602 927 else if (expected_type == OBJ_TREE)
321c89bf 928 lookup_flags |= GET_OID_TREEISH;
e2643617 929
e82caf38 930 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
5385f52d
JH
931 return -1;
932
c251c83d 933 o = parse_object(&outer);
5385f52d
JH
934 if (!o)
935 return -1;
885a86ab 936 if (!expected_type) {
9534f40b 937 o = deref_tag(o, name, sp - name - 2);
c251c83d 938 if (!o || (!o->parsed && !parse_object(&o->oid)))
6e1c6c10 939 return -1;
e82caf38 940 oidcpy(oid, &o->oid);
32574b68 941 return 0;
5385f52d 942 }
32574b68
NTND
943
944 /*
945 * At this point, the syntax look correct, so
946 * if we do not get the needed object, we should
947 * barf.
948 */
949 o = peel_to_type(name, len, o, expected_type);
950 if (!o)
81776315 951 return -1;
32574b68 952
e82caf38 953 oidcpy(oid, &o->oid);
32574b68
NTND
954 if (sp[0] == '/') {
955 /* "$commit^{/foo}" */
956 char *prefix;
957 int ret;
958 struct commit_list *list = NULL;
959
81776315 960 /*
4322842a
NTND
961 * $commit^{/}. Some regex implementation may reject.
962 * We don't need regex anyway. '' pattern always matches.
5385f52d 963 */
4322842a 964 if (sp[1] == '}')
81776315 965 return 0;
4322842a 966
32574b68
NTND
967 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
968 commit_list_insert((struct commit *)o, &list);
e82caf38 969 ret = get_oid_oneline(prefix, oid, list);
32574b68
NTND
970 free(prefix);
971 return ret;
5385f52d
JH
972 }
973 return 0;
974}
975
e82caf38 976static int get_describe_name(const char *name, int len, struct object_id *oid)
7dd45e15
JH
977{
978 const char *cp;
321c89bf 979 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
7dd45e15
JH
980
981 for (cp = name + len - 1; name + 2 <= cp; cp--) {
982 char ch = *cp;
6f75d45b 983 if (!isxdigit(ch)) {
7dd45e15
JH
984 /* We must be looking at g in "SOMETHING-g"
985 * for it to be describe output.
986 */
987 if (ch == 'g' && cp[-1] == '-') {
988 cp++;
989 len -= cp - name;
e82caf38 990 return get_short_oid(cp, len, oid, flags);
7dd45e15
JH
991 }
992 }
993 }
994 return -1;
995}
996
e82caf38 997static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags)
9938af6a 998{
0601dbe1 999 int ret, has_suffix;
4f7599ac 1000 const char *cp;
9938af6a 1001
621ff675
LT
1002 /*
1003 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
4f7599ac 1004 */
0601dbe1 1005 has_suffix = 0;
4f7599ac
JH
1006 for (cp = name + len - 1; name <= cp; cp--) {
1007 int ch = *cp;
1008 if ('0' <= ch && ch <= '9')
1009 continue;
0601dbe1
JH
1010 if (ch == '~' || ch == '^')
1011 has_suffix = ch;
4f7599ac
JH
1012 break;
1013 }
0601dbe1
JH
1014
1015 if (has_suffix) {
1016 int num = 0;
4f7599ac
JH
1017 int len1 = cp - name;
1018 cp++;
1019 while (cp < name + len)
0601dbe1 1020 num = num * 10 + *cp++ - '0';
621ff675
LT
1021 if (!num && len1 == len - 1)
1022 num = 1;
1023 if (has_suffix == '^')
e82caf38 1024 return get_parent(name, len1, oid, num);
0601dbe1 1025 /* else if (has_suffix == '~') -- goes without saying */
e82caf38 1026 return get_nth_ancestor(name, len1, oid, num);
4f7599ac
JH
1027 }
1028
e82caf38 1029 ret = peel_onion(name, len, oid, lookup_flags);
5385f52d
JH
1030 if (!ret)
1031 return 0;
1032
e82caf38 1033 ret = get_oid_basic(name, len, oid, lookup_flags);
9938af6a
JH
1034 if (!ret)
1035 return 0;
7dd45e15
JH
1036
1037 /* It could be describe output that is "SOMETHING-gXXXX" */
e82caf38 1038 ret = get_describe_name(name, len, oid);
7dd45e15
JH
1039 if (!ret)
1040 return 0;
1041
e82caf38 1042 return get_short_oid(name, len, oid, lookup_flags);
9938af6a
JH
1043}
1044
f7bff003
JH
1045/*
1046 * This interprets names like ':/Initial revision of "git"' by searching
1047 * through history and returning the first commit whose message starts
3d045897 1048 * the given regular expression.
f7bff003 1049 *
0769854f
WP
1050 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1051 *
1052 * For a literal '!' character at the beginning of a pattern, you have to repeat
1053 * that, like: ':/!!foo'
1054 *
1055 * For future extension, all other sequences beginning with ':/!' are reserved.
f7bff003 1056 */
208acbfb
NTND
1057
1058/* Remember to update object flag allocation in object.h */
f7bff003
JH
1059#define ONELINE_SEEN (1u<<20)
1060
9c5fe0b8
MH
1061static int handle_one_ref(const char *path, const struct object_id *oid,
1062 int flag, void *cb_data)
28a4d940
JS
1063{
1064 struct commit_list **list = cb_data;
c251c83d 1065 struct object *object = parse_object(oid);
28a4d940
JS
1066 if (!object)
1067 return 0;
affeef12 1068 if (object->type == OBJ_TAG) {
28a4d940 1069 object = deref_tag(object, path, strlen(path));
affeef12
MK
1070 if (!object)
1071 return 0;
1072 }
28a4d940
JS
1073 if (object->type != OBJ_COMMIT)
1074 return 0;
e8d1dfe6 1075 commit_list_insert((struct commit *)object, list);
28a4d940
JS
1076 return 0;
1077}
1078
e82caf38 1079static int get_oid_oneline(const char *prefix, struct object_id *oid,
84baa31b 1080 struct commit_list *list)
28a4d940 1081{
84baa31b 1082 struct commit_list *backup = NULL, *l;
28042dbc 1083 int found = 0;
0769854f 1084 int negative = 0;
57895105 1085 regex_t regex;
28a4d940
JS
1086
1087 if (prefix[0] == '!') {
28a4d940 1088 prefix++;
0769854f
WP
1089
1090 if (prefix[0] == '-') {
1091 prefix++;
1092 negative = 1;
1093 } else if (prefix[0] != '!') {
e6a6a768 1094 return -1;
0769854f 1095 }
28a4d940 1096 }
57895105
LT
1097
1098 if (regcomp(&regex, prefix, REG_EXTENDED))
aac4fac1 1099 return -1;
57895105 1100
84baa31b
NTND
1101 for (l = list; l; l = l->next) {
1102 l->item->object.flags |= ONELINE_SEEN;
28a4d940 1103 commit_list_insert(l->item, &backup);
84baa31b 1104 }
ed8ad7e2 1105 while (list) {
ba41c1c9 1106 const char *p, *buf;
1358e7d6 1107 struct commit *commit;
28042dbc 1108 int matches;
ed8ad7e2
JM
1109
1110 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
c251c83d 1111 if (!parse_object(&commit->object.oid))
283cdbcf 1112 continue;
8597ea3a 1113 buf = get_commit_buffer(commit, NULL);
ba41c1c9 1114 p = strstr(buf, "\n\n");
0769854f 1115 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
ba41c1c9 1116 unuse_commit_buffer(commit, buf);
28042dbc
JH
1117
1118 if (matches) {
e82caf38 1119 oidcpy(oid, &commit->object.oid);
28042dbc 1120 found = 1;
28a4d940
JS
1121 break;
1122 }
1123 }
57895105 1124 regfree(&regex);
28a4d940
JS
1125 free_commit_list(list);
1126 for (l = backup; l; l = l->next)
1127 clear_commit_marks(l->item, ONELINE_SEEN);
28042dbc
JH
1128 free_commit_list(backup);
1129 return found ? 0 : -1;
28a4d940
JS
1130}
1131
ae5a6c36 1132struct grab_nth_branch_switch_cbdata {
98f85ff4
JH
1133 int remaining;
1134 struct strbuf buf;
ae5a6c36
JH
1135};
1136
9461d272 1137static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
dddbad72 1138 const char *email, timestamp_t timestamp, int tz,
ae5a6c36
JH
1139 const char *message, void *cb_data)
1140{
1141 struct grab_nth_branch_switch_cbdata *cb = cb_data;
a884d0cb
TR
1142 const char *match = NULL, *target = NULL;
1143 size_t len;
1144
95b567c7 1145 if (skip_prefix(message, "checkout: moving from ", &match))
d7c03c1f 1146 target = strstr(match, " to ");
ae5a6c36 1147
c829774c 1148 if (!match || !target)
ae5a6c36 1149 return 0;
98f85ff4
JH
1150 if (--(cb->remaining) == 0) {
1151 len = target - match;
1152 strbuf_reset(&cb->buf);
1153 strbuf_add(&cb->buf, match, len);
1154 return 1; /* we are done */
1155 }
ae5a6c36
JH
1156 return 0;
1157}
1158
1159/*
ae0ba8e2
JH
1160 * Parse @{-N} syntax, return the number of characters parsed
1161 * if successful; otherwise signal an error with negative value.
ae5a6c36 1162 */
8cd4249c
JK
1163static int interpret_nth_prior_checkout(const char *name, int namelen,
1164 struct strbuf *buf)
ae5a6c36 1165{
c2883e62 1166 long nth;
98f85ff4 1167 int retval;
ae5a6c36 1168 struct grab_nth_branch_switch_cbdata cb;
a884d0cb
TR
1169 const char *brace;
1170 char *num_end;
ae5a6c36 1171
8cd4249c
JK
1172 if (namelen < 4)
1173 return -1;
ae5a6c36
JH
1174 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1175 return -1;
8cd4249c 1176 brace = memchr(name, '}', namelen);
a884d0cb
TR
1177 if (!brace)
1178 return -1;
98f85ff4 1179 nth = strtol(name + 3, &num_end, 10);
a884d0cb 1180 if (num_end != brace)
ae5a6c36 1181 return -1;
c2883e62
JH
1182 if (nth <= 0)
1183 return -1;
98f85ff4
JH
1184 cb.remaining = nth;
1185 strbuf_init(&cb.buf, 20);
1186
39765e59 1187 retval = 0;
98f85ff4
JH
1188 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1189 strbuf_reset(buf);
e992d1eb 1190 strbuf_addbuf(buf, &cb.buf);
98f85ff4
JH
1191 retval = brace - name + 1;
1192 }
a884d0cb 1193
98f85ff4 1194 strbuf_release(&cb.buf);
39765e59 1195 return retval;
ae5a6c36
JH
1196}
1197
151b2911 1198int get_oid_mb(const char *name, struct object_id *oid)
619a644d
JH
1199{
1200 struct commit *one, *two;
1201 struct commit_list *mbs;
151b2911 1202 struct object_id oid_tmp;
619a644d
JH
1203 const char *dots;
1204 int st;
1205
1206 dots = strstr(name, "...");
1207 if (!dots)
151b2911 1208 return get_oid(name, oid);
619a644d 1209 if (dots == name)
151b2911 1210 st = get_oid("HEAD", &oid_tmp);
619a644d
JH
1211 else {
1212 struct strbuf sb;
1213 strbuf_init(&sb, dots - name);
1214 strbuf_add(&sb, name, dots - name);
e82caf38 1215 st = get_oid_committish(sb.buf, &oid_tmp);
619a644d
JH
1216 strbuf_release(&sb);
1217 }
1218 if (st)
1219 return st;
bc83266a 1220 one = lookup_commit_reference_gently(&oid_tmp, 0);
619a644d
JH
1221 if (!one)
1222 return -1;
1223
e82caf38 1224 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
619a644d 1225 return -1;
bc83266a 1226 two = lookup_commit_reference_gently(&oid_tmp, 0);
619a644d
JH
1227 if (!two)
1228 return -1;
2ce406cc 1229 mbs = get_merge_bases(one, two);
619a644d
JH
1230 if (!mbs || mbs->next)
1231 st = -1;
1232 else {
1233 st = 0;
151b2911 1234 oidcpy(oid, &mbs->item->object.oid);
619a644d
JH
1235 }
1236 free_commit_list(mbs);
1237 return st;
1238}
1239
9ba89f48
FC
1240/* parse @something syntax, when 'something' is not {.*} */
1241static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1242{
1243 const char *next;
1244
1245 if (len || name[1] == '{')
1246 return -1;
1247
1248 /* make sure it's a single @, or @@{.*}, not @foo */
8cd4249c 1249 next = memchr(name + len + 1, '@', namelen - len - 1);
9ba89f48
FC
1250 if (next && next[1] != '{')
1251 return -1;
1252 if (!next)
1253 next = name + namelen;
1254 if (next != name + 1)
1255 return -1;
1256
1257 strbuf_reset(buf);
1258 strbuf_add(buf, "HEAD", 4);
1259 return 1;
1260}
1261
0e9f62da
JK
1262static int reinterpret(const char *name, int namelen, int len,
1263 struct strbuf *buf, unsigned allowed)
7a0a49a7
FC
1264{
1265 /* we have extra data, which might need further processing */
1266 struct strbuf tmp = STRBUF_INIT;
1267 int used = buf->len;
1268 int ret;
1269
1270 strbuf_add(buf, name + len, namelen - len);
0e9f62da 1271 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
7a0a49a7
FC
1272 /* that data was not interpreted, remove our cruft */
1273 if (ret < 0) {
1274 strbuf_setlen(buf, used);
1275 return len;
1276 }
1277 strbuf_reset(buf);
1278 strbuf_addbuf(buf, &tmp);
1279 strbuf_release(&tmp);
1280 /* tweak for size of {-N} versus expanded ref name */
1281 return ret - used + len;
1282}
1283
a39c14af
JK
1284static void set_shortened_ref(struct strbuf *buf, const char *ref)
1285{
1286 char *s = shorten_unambiguous_ref(ref, 0);
1287 strbuf_reset(buf);
1288 strbuf_addstr(buf, s);
1289 free(s);
1290}
1291
0e9f62da
JK
1292static int branch_interpret_allowed(const char *refname, unsigned allowed)
1293{
1294 if (!allowed)
1295 return 1;
1296
1297 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1298 starts_with(refname, "refs/heads/"))
1299 return 1;
1300 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1301 starts_with(refname, "refs/remotes/"))
1302 return 1;
1303
1304 return 0;
1305}
1306
48c58471
JK
1307static int interpret_branch_mark(const char *name, int namelen,
1308 int at, struct strbuf *buf,
1309 int (*get_mark)(const char *, int),
1310 const char *(*get_data)(struct branch *,
0e9f62da
JK
1311 struct strbuf *),
1312 unsigned allowed)
a39c14af
JK
1313{
1314 int len;
48c58471
JK
1315 struct branch *branch;
1316 struct strbuf err = STRBUF_INIT;
1317 const char *value;
a39c14af 1318
48c58471 1319 len = get_mark(name + at, namelen - at);
a39c14af
JK
1320 if (!len)
1321 return -1;
1322
3f6eb30f
JK
1323 if (memchr(name, ':', at))
1324 return -1;
1325
48c58471
JK
1326 if (at) {
1327 char *name_str = xmemdupz(name, at);
1328 branch = branch_get(name_str);
1329 free(name_str);
1330 } else
1331 branch = branch_get(NULL);
1332
1333 value = get_data(branch, &err);
1334 if (!value)
1335 die("%s", err.buf);
1336
0e9f62da
JK
1337 if (!branch_interpret_allowed(value, allowed))
1338 return -1;
1339
48c58471 1340 set_shortened_ref(buf, value);
a39c14af
JK
1341 return len + at;
1342}
1343
0e9f62da
JK
1344int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1345 unsigned allowed)
ae0ba8e2 1346{
f278f40f 1347 char *at;
9892d5d4 1348 const char *start;
13228c30 1349 int len;
ae0ba8e2 1350
cf99a761
FC
1351 if (!namelen)
1352 namelen = strlen(name);
1353
0e9f62da
JK
1354 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1355 len = interpret_nth_prior_checkout(name, namelen, buf);
1356 if (!len) {
1357 return len; /* syntax Ok, not enough switches */
1358 } else if (len > 0) {
1359 if (len == namelen)
1360 return len; /* consumed all */
1361 else
1362 return reinterpret(name, namelen, len, buf, allowed);
1363 }
d46a8301
JK
1364 }
1365
9892d5d4
JK
1366 for (start = name;
1367 (at = memchr(start, '@', namelen - (start - name)));
1368 start = at + 1) {
9ba89f48 1369
0e9f62da
JK
1370 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1371 len = interpret_empty_at(name, namelen, at - name, buf);
1372 if (len > 0)
1373 return reinterpret(name, namelen, len, buf,
1374 allowed);
1375 }
9ba89f48 1376
48c58471 1377 len = interpret_branch_mark(name, namelen, at - name, buf,
0e9f62da
JK
1378 upstream_mark, branch_get_upstream,
1379 allowed);
9892d5d4
JK
1380 if (len > 0)
1381 return len;
adfe5d04
JK
1382
1383 len = interpret_branch_mark(name, namelen, at - name, buf,
0e9f62da
JK
1384 push_mark, branch_get_push,
1385 allowed);
9892d5d4
JK
1386 if (len > 0)
1387 return len;
bb0dab5d 1388 }
9ba89f48 1389
a39c14af 1390 return -1;
ae0ba8e2
JH
1391}
1392
0e9f62da 1393void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
6bab74e7
JN
1394{
1395 int len = strlen(name);
0e9f62da 1396 int used = interpret_branch_name(name, len, sb, allowed);
84cf2466 1397
84cf2466
JH
1398 if (used < 0)
1399 used = 0;
1400 strbuf_add(sb, name + used, len - used);
6bab74e7
JN
1401}
1402
1403int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1404{
7c3f847a
JH
1405 if (startup_info->have_repository)
1406 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1407 else
1408 strbuf_addstr(sb, name);
a625b092
JH
1409
1410 /*
1411 * This splice must be done even if we end up rejecting the
1412 * name; builtin/branch.c::copy_or_rename_branch() still wants
1413 * to see what the name expanded to so that "branch -m" can be
1414 * used as a tool to correct earlier mistakes.
1415 */
6bab74e7 1416 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
a625b092
JH
1417
1418 if (*name == '-' ||
1419 !strcmp(sb->buf, "refs/heads/HEAD"))
1420 return -1;
1421
8d9c5010 1422 return check_refname_format(sb->buf, 0);
6bab74e7
JN
1423}
1424
9938af6a 1425/*
e82caf38 1426 * This is like "get_oid_basic()", except it allows "object ID expressions",
9938af6a
JH
1427 * notably "xyz^" for "parent of xyz"
1428 */
2764fd93 1429int get_oid(const char *name, struct object_id *oid)
1430{
e82caf38 1431 struct object_context unused;
1432 return get_oid_with_context(name, 0, oid, &unused);
2764fd93 1433}
1434
1435
cd74e473 1436/*
a8a5406a 1437 * Many callers know that the user meant to name a commit-ish by
cd74e473
JH
1438 * syntactical positions where the object name appears. Calling this
1439 * function allows the machinery to disambiguate shorter-than-unique
a8a5406a 1440 * abbreviated object names between commit-ish and others.
cd74e473
JH
1441 *
1442 * Note that this does NOT error out when the named object is not a
a8a5406a 1443 * commit-ish. It is merely to give a hint to the disambiguation
cd74e473
JH
1444 * machinery.
1445 */
e82caf38 1446int get_oid_committish(const char *name, struct object_id *oid)
cd74e473
JH
1447{
1448 struct object_context unused;
321c89bf 1449 return get_oid_with_context(name, GET_OID_COMMITTISH,
e82caf38 1450 oid, &unused);
cd74e473
JH
1451}
1452
e82caf38 1453int get_oid_treeish(const char *name, struct object_id *oid)
daba53ae
JH
1454{
1455 struct object_context unused;
321c89bf 1456 return get_oid_with_context(name, GET_OID_TREEISH,
e82caf38 1457 oid, &unused);
daba53ae
JH
1458}
1459
e82caf38 1460int get_oid_commit(const char *name, struct object_id *oid)
daba53ae
JH
1461{
1462 struct object_context unused;
321c89bf 1463 return get_oid_with_context(name, GET_OID_COMMIT,
e82caf38 1464 oid, &unused);
daba53ae
JH
1465}
1466
e82caf38 1467int get_oid_tree(const char *name, struct object_id *oid)
daba53ae
JH
1468{
1469 struct object_context unused;
321c89bf 1470 return get_oid_with_context(name, GET_OID_TREE,
e82caf38 1471 oid, &unused);
daba53ae
JH
1472}
1473
e82caf38 1474int get_oid_blob(const char *name, struct object_id *oid)
daba53ae
JH
1475{
1476 struct object_context unused;
321c89bf 1477 return get_oid_with_context(name, GET_OID_BLOB,
e82caf38 1478 oid, &unused);
a0cd87a5
MK
1479}
1480
009fee47 1481/* Must be called only when object_name:filename doesn't exist. */
e82caf38 1482static void diagnose_invalid_oid_path(const char *prefix,
1483 const char *filename,
1484 const struct object_id *tree_oid,
1485 const char *object_name,
1486 int object_name_len)
009fee47 1487{
e82caf38 1488 struct object_id oid;
009fee47
MM
1489 unsigned mode;
1490
1491 if (!prefix)
1492 prefix = "";
1493
dbe44faa 1494 if (file_exists(filename))
b2981d06
RS
1495 die("Path '%s' exists on disk, but not in '%.*s'.",
1496 filename, object_name_len, object_name);
c7054209 1497 if (is_missing_file_error(errno)) {
b2724c87 1498 char *fullname = xstrfmt("%s%s", prefix, filename);
009fee47 1499
916bc35b 1500 if (!get_tree_entry(tree_oid, fullname, &oid, &mode)) {
009fee47 1501 die("Path '%s' exists, but not '%s'.\n"
b2981d06 1502 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
009fee47
MM
1503 fullname,
1504 filename,
b2981d06 1505 object_name_len, object_name,
e41d718c 1506 fullname,
b2981d06 1507 object_name_len, object_name,
e41d718c 1508 filename);
009fee47 1509 }
b2981d06
RS
1510 die("Path '%s' does not exist in '%.*s'",
1511 filename, object_name_len, object_name);
009fee47
MM
1512 }
1513}
1514
1515/* Must be called only when :stage:filename doesn't exist. */
1516static void diagnose_invalid_index_path(int stage,
1517 const char *prefix,
1518 const char *filename)
1519{
9c5e6c80 1520 const struct cache_entry *ce;
009fee47
MM
1521 int pos;
1522 unsigned namelen = strlen(filename);
43bb66ae 1523 struct strbuf fullname = STRBUF_INIT;
009fee47
MM
1524
1525 if (!prefix)
1526 prefix = "";
1527
1528 /* Wrong stage number? */
1529 pos = cache_name_pos(filename, namelen);
1530 if (pos < 0)
1531 pos = -pos - 1;
77e8466f
MH
1532 if (pos < active_nr) {
1533 ce = active_cache[pos];
1534 if (ce_namelen(ce) == namelen &&
1535 !memcmp(ce->name, filename, namelen))
1536 die("Path '%s' is in the index, but not at stage %d.\n"
1537 "Did you mean ':%d:%s'?",
1538 filename, stage,
1539 ce_stage(ce), filename);
1540 }
009fee47
MM
1541
1542 /* Confusion between relative and absolute filenames? */
43bb66ae
JK
1543 strbuf_addstr(&fullname, prefix);
1544 strbuf_addstr(&fullname, filename);
1545 pos = cache_name_pos(fullname.buf, fullname.len);
009fee47
MM
1546 if (pos < 0)
1547 pos = -pos - 1;
77e8466f
MH
1548 if (pos < active_nr) {
1549 ce = active_cache[pos];
43bb66ae
JK
1550 if (ce_namelen(ce) == fullname.len &&
1551 !memcmp(ce->name, fullname.buf, fullname.len))
77e8466f 1552 die("Path '%s' is in the index, but not '%s'.\n"
e41d718c 1553 "Did you mean ':%d:%s' aka ':%d:./%s'?",
43bb66ae
JK
1554 fullname.buf, filename,
1555 ce_stage(ce), fullname.buf,
e41d718c 1556 ce_stage(ce), filename);
77e8466f 1557 }
009fee47 1558
dbe44faa 1559 if (file_exists(filename))
009fee47 1560 die("Path '%s' exists on disk, but not in the index.", filename);
c7054209 1561 if (is_missing_file_error(errno))
009fee47
MM
1562 die("Path '%s' does not exist (neither on disk nor in the index).",
1563 filename);
1564
43bb66ae 1565 strbuf_release(&fullname);
009fee47
MM
1566}
1567
1568
979f7929
NTND
1569static char *resolve_relative_path(const char *rel)
1570{
59556548 1571 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
979f7929
NTND
1572 return NULL;
1573
979f7929
NTND
1574 if (!is_inside_work_tree())
1575 die("relative path syntax can't be used outside working tree.");
1576
1577 /* die() inside prefix_path() if resolved path is outside worktree */
1578 return prefix_path(startup_info->prefix,
1579 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1580 rel);
1581}
1582
e82caf38 1583static int get_oid_with_context_1(const char *name,
1584 unsigned flags,
1585 const char *prefix,
1586 struct object_id *oid,
1587 struct object_context *oc)
a0cd87a5
MK
1588{
1589 int ret, bracket_depth;
73b0e5af
JH
1590 int namelen = strlen(name);
1591 const char *cp;
321c89bf 1592 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
5119602a 1593
7243ffdd 1594 if (only_to_die)
321c89bf 1595 flags |= GET_OID_QUIETLY;
7243ffdd 1596
573285e5
CP
1597 memset(oc, 0, sizeof(*oc));
1598 oc->mode = S_IFINVALID;
d72cae12 1599 strbuf_init(&oc->symlink_path, 0);
e82caf38 1600 ret = get_oid_1(name, namelen, oid, flags);
73b0e5af
JH
1601 if (!ret)
1602 return ret;
33bd598c
JH
1603 /*
1604 * sha1:path --> object name of path in ent sha1
979f7929
NTND
1605 * :path -> object name of absolute path in index
1606 * :./path -> object name of path relative to cwd in index
73b0e5af 1607 * :[0-3]:path -> object name of path in index at stage
95ad6d2d 1608 * :/foo -> recent commit matching foo
73b0e5af
JH
1609 */
1610 if (name[0] == ':') {
1611 int stage = 0;
9c5e6c80 1612 const struct cache_entry *ce;
979f7929 1613 char *new_path = NULL;
73b0e5af 1614 int pos;
2e83b66c 1615 if (!only_to_die && namelen > 2 && name[1] == '/') {
84baa31b 1616 struct commit_list *list = NULL;
2b2a5be3 1617
84baa31b 1618 for_each_ref(handle_one_ref, &list);
e8d1dfe6 1619 commit_list_sort_by_date(&list);
e82caf38 1620 return get_oid_oneline(name + 2, oid, list);
84baa31b 1621 }
73b0e5af
JH
1622 if (namelen < 3 ||
1623 name[2] != ':' ||
1624 name[1] < '0' || '3' < name[1])
1625 cp = name + 1;
1626 else {
1627 stage = name[1] - '0';
1628 cp = name + 3;
5119602a 1629 }
3d6e0f74
JH
1630 new_path = resolve_relative_path(cp);
1631 if (!new_path) {
1632 namelen = namelen - (cp - name);
1633 } else {
1634 cp = new_path;
1635 namelen = strlen(cp);
1636 }
573285e5 1637
321c89bf 1638 if (flags & GET_OID_RECORD_PATH)
dc944b65 1639 oc->path = xstrdup(cp);
573285e5 1640
73b0e5af
JH
1641 if (!active_cache)
1642 read_cache();
73b0e5af
JH
1643 pos = cache_name_pos(cp, namelen);
1644 if (pos < 0)
1645 pos = -pos - 1;
1646 while (pos < active_nr) {
1647 ce = active_cache[pos];
1648 if (ce_namelen(ce) != namelen ||
1649 memcmp(ce->name, cp, namelen))
1650 break;
1651 if (ce_stage(ce) == stage) {
e82caf38 1652 oidcpy(oid, &ce->oid);
90064710 1653 oc->mode = ce->ce_mode;
979f7929 1654 free(new_path);
73b0e5af
JH
1655 return 0;
1656 }
e7cef45f 1657 pos++;
73b0e5af 1658 }
2e83b66c 1659 if (only_to_die && name[1] && name[1] != '/')
009fee47 1660 diagnose_invalid_index_path(stage, prefix, cp);
979f7929 1661 free(new_path);
73b0e5af
JH
1662 return -1;
1663 }
cce91a2c
SP
1664 for (cp = name, bracket_depth = 0; *cp; cp++) {
1665 if (*cp == '{')
1666 bracket_depth++;
1667 else if (bracket_depth && *cp == '}')
1668 bracket_depth--;
1669 else if (!bracket_depth && *cp == ':')
1670 break;
1671 }
1672 if (*cp == ':') {
e82caf38 1673 struct object_id tree_oid;
b2981d06 1674 int len = cp - name;
8a10fea4
JK
1675 unsigned sub_flags = flags;
1676
321c89bf 1677 sub_flags &= ~GET_OID_DISAMBIGUATORS;
1678 sub_flags |= GET_OID_TREEISH;
8a10fea4 1679
e82caf38 1680 if (!get_oid_1(name, len, &tree_oid, sub_flags)) {
009fee47 1681 const char *filename = cp+1;
979f7929
NTND
1682 char *new_filename = NULL;
1683
1684 new_filename = resolve_relative_path(filename);
1685 if (new_filename)
1686 filename = new_filename;
321c89bf 1687 if (flags & GET_OID_FOLLOW_SYMLINKS) {
e82caf38 1688 ret = get_tree_entry_follow_symlinks(tree_oid.hash,
1689 filename, oid->hash, &oc->symlink_path,
c4ec9677
DT
1690 &oc->mode);
1691 } else {
916bc35b 1692 ret = get_tree_entry(&tree_oid, filename, oid,
1693 &oc->mode);
c4ec9677 1694 if (ret && only_to_die) {
e82caf38 1695 diagnose_invalid_oid_path(prefix,
c4ec9677 1696 filename,
e82caf38 1697 &tree_oid,
c4ec9677
DT
1698 name, len);
1699 }
009fee47 1700 }
e82caf38 1701 hashcpy(oc->tree, tree_oid.hash);
321c89bf 1702 if (flags & GET_OID_RECORD_PATH)
dc944b65 1703 oc->path = xstrdup(filename);
573285e5 1704
979f7929 1705 free(new_filename);
009fee47
MM
1706 return ret;
1707 } else {
2e83b66c 1708 if (only_to_die)
b2981d06 1709 die("Invalid object name '%.*s'.", len, name);
009fee47 1710 }
5119602a
LT
1711 }
1712 return ret;
9938af6a 1713}
f01cc14c 1714
8c135ea2
JH
1715/*
1716 * Call this function when you know "name" given by the end user must
1717 * name an object but it doesn't; the function _may_ die with a better
1718 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1719 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1720 * you have a chance to diagnose the error further.
1721 */
1722void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
f01cc14c
JH
1723{
1724 struct object_context oc;
e82caf38 1725 struct object_id oid;
321c89bf 1726 get_oid_with_context_1(name, GET_OID_ONLY_TO_DIE, prefix, &oid, &oc);
8c135ea2
JH
1727}
1728
e82caf38 1729int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
f01cc14c 1730{
321c89bf 1731 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
c4ec9677 1732 die("BUG: incompatible flags for get_sha1_with_context");
e82caf38 1733 return get_oid_with_context_1(str, flags, NULL, oid, oc);
f01cc14c 1734}