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