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