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