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