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