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