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