THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1948 lines
48KB

  1. #include "cache.h"
  2. #include "config.h"
  3. #include "tag.h"
  4. #include "commit.h"
  5. #include "tree.h"
  6. #include "blob.h"
  7. #include "tree-walk.h"
  8. #include "refs.h"
  9. #include "remote.h"
  10. #include "dir.h"
  11. #include "sha1-array.h"
  12. #include "packfile.h"
  13. #include "object-store.h"
  14. #include "repository.h"
  15. #include "submodule.h"
  16. #include "midx.h"
  17. #include "commit-reach.h"
  18. static int get_oid_oneline(struct repository *r, const char *, struct object_id *, struct commit_list *);
  19. typedef int (*disambiguate_hint_fn)(struct repository *, const struct object_id *, void *);
  20. struct disambiguate_state {
  21. int len; /* length of prefix in hex chars */
  22. char hex_pfx[GIT_MAX_HEXSZ + 1];
  23. struct object_id bin_pfx;
  24. struct repository *repo;
  25. disambiguate_hint_fn fn;
  26. void *cb_data;
  27. struct object_id candidate;
  28. unsigned candidate_exists:1;
  29. unsigned candidate_checked:1;
  30. unsigned candidate_ok:1;
  31. unsigned disambiguate_fn_used:1;
  32. unsigned ambiguous:1;
  33. unsigned always_call_fn:1;
  34. };
  35. static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
  36. {
  37. if (ds->always_call_fn) {
  38. ds->ambiguous = ds->fn(ds->repo, current, ds->cb_data) ? 1 : 0;
  39. return;
  40. }
  41. if (!ds->candidate_exists) {
  42. /* this is the first candidate */
  43. oidcpy(&ds->candidate, current);
  44. ds->candidate_exists = 1;
  45. return;
  46. } else if (oideq(&ds->candidate, current)) {
  47. /* the same as what we already have seen */
  48. return;
  49. }
  50. if (!ds->fn) {
  51. /* cannot disambiguate between ds->candidate and current */
  52. ds->ambiguous = 1;
  53. return;
  54. }
  55. if (!ds->candidate_checked) {
  56. ds->candidate_ok = ds->fn(ds->repo, &ds->candidate, ds->cb_data);
  57. ds->disambiguate_fn_used = 1;
  58. ds->candidate_checked = 1;
  59. }
  60. if (!ds->candidate_ok) {
  61. /* discard the candidate; we know it does not satisfy fn */
  62. oidcpy(&ds->candidate, current);
  63. ds->candidate_checked = 0;
  64. return;
  65. }
  66. /* if we reach this point, we know ds->candidate satisfies fn */
  67. if (ds->fn(ds->repo, current, ds->cb_data)) {
  68. /*
  69. * if both current and candidate satisfy fn, we cannot
  70. * disambiguate.
  71. */
  72. ds->candidate_ok = 0;
  73. ds->ambiguous = 1;
  74. }
  75. /* otherwise, current can be discarded and candidate is still good */
  76. }
  77. static int match_sha(unsigned, const unsigned char *, const unsigned char *);
  78. static void find_short_object_filename(struct disambiguate_state *ds)
  79. {
  80. struct object_directory *odb;
  81. for (odb = ds->repo->objects->odb; odb && !ds->ambiguous; odb = odb->next) {
  82. int pos;
  83. struct oid_array *loose_objects;
  84. loose_objects = odb_loose_cache(odb, &ds->bin_pfx);
  85. pos = oid_array_lookup(loose_objects, &ds->bin_pfx);
  86. if (pos < 0)
  87. pos = -1 - pos;
  88. while (!ds->ambiguous && pos < loose_objects->nr) {
  89. const struct object_id *oid;
  90. oid = loose_objects->oid + pos;
  91. if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
  92. break;
  93. update_candidates(ds, oid);
  94. pos++;
  95. }
  96. }
  97. }
  98. static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
  99. {
  100. do {
  101. if (*a != *b)
  102. return 0;
  103. a++;
  104. b++;
  105. len -= 2;
  106. } while (len > 1);
  107. if (len)
  108. if ((*a ^ *b) & 0xf0)
  109. return 0;
  110. return 1;
  111. }
  112. static void unique_in_midx(struct multi_pack_index *m,
  113. struct disambiguate_state *ds)
  114. {
  115. uint32_t num, i, first = 0;
  116. const struct object_id *current = NULL;
  117. num = m->num_objects;
  118. if (!num)
  119. return;
  120. bsearch_midx(&ds->bin_pfx, m, &first);
  121. /*
  122. * At this point, "first" is the location of the lowest object
  123. * with an object name that could match "bin_pfx". See if we have
  124. * 0, 1 or more objects that actually match(es).
  125. */
  126. for (i = first; i < num && !ds->ambiguous; i++) {
  127. struct object_id oid;
  128. current = nth_midxed_object_oid(&oid, m, i);
  129. if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
  130. break;
  131. update_candidates(ds, current);
  132. }
  133. }
  134. static void unique_in_pack(struct packed_git *p,
  135. struct disambiguate_state *ds)
  136. {
  137. uint32_t num, i, first = 0;
  138. const struct object_id *current = NULL;
  139. if (p->multi_pack_index)
  140. return;
  141. if (open_pack_index(p) || !p->num_objects)
  142. return;
  143. num = p->num_objects;
  144. bsearch_pack(&ds->bin_pfx, p, &first);
  145. /*
  146. * At this point, "first" is the location of the lowest object
  147. * with an object name that could match "bin_pfx". See if we have
  148. * 0, 1 or more objects that actually match(es).
  149. */
  150. for (i = first; i < num && !ds->ambiguous; i++) {
  151. struct object_id oid;
  152. current = nth_packed_object_oid(&oid, p, i);
  153. if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
  154. break;
  155. update_candidates(ds, current);
  156. }
  157. }
  158. static void find_short_packed_object(struct disambiguate_state *ds)
  159. {
  160. struct multi_pack_index *m;
  161. struct packed_git *p;
  162. for (m = get_multi_pack_index(ds->repo); m && !ds->ambiguous;
  163. m = m->next)
  164. unique_in_midx(m, ds);
  165. for (p = get_packed_git(ds->repo); p && !ds->ambiguous;
  166. p = p->next)
  167. unique_in_pack(p, ds);
  168. }
  169. static int finish_object_disambiguation(struct disambiguate_state *ds,
  170. struct object_id *oid)
  171. {
  172. if (ds->ambiguous)
  173. return SHORT_NAME_AMBIGUOUS;
  174. if (!ds->candidate_exists)
  175. return MISSING_OBJECT;
  176. if (!ds->candidate_checked)
  177. /*
  178. * If this is the only candidate, there is no point
  179. * calling the disambiguation hint callback.
  180. *
  181. * On the other hand, if the current candidate
  182. * replaced an earlier candidate that did _not_ pass
  183. * the disambiguation hint callback, then we do have
  184. * more than one objects that match the short name
  185. * given, so we should make sure this one matches;
  186. * otherwise, if we discovered this one and the one
  187. * that we previously discarded in the reverse order,
  188. * we would end up showing different results in the
  189. * same repository!
  190. */
  191. ds->candidate_ok = (!ds->disambiguate_fn_used ||
  192. ds->fn(ds->repo, &ds->candidate, ds->cb_data));
  193. if (!ds->candidate_ok)
  194. return SHORT_NAME_AMBIGUOUS;
  195. oidcpy(oid, &ds->candidate);
  196. return 0;
  197. }
  198. static int disambiguate_commit_only(struct repository *r,
  199. const struct object_id *oid,
  200. void *cb_data_unused)
  201. {
  202. int kind = oid_object_info(r, oid, NULL);
  203. return kind == OBJ_COMMIT;
  204. }
  205. static int disambiguate_committish_only(struct repository *r,
  206. const struct object_id *oid,
  207. void *cb_data_unused)
  208. {
  209. struct object *obj;
  210. int kind;
  211. kind = oid_object_info(r, oid, NULL);
  212. if (kind == OBJ_COMMIT)
  213. return 1;
  214. if (kind != OBJ_TAG)
  215. return 0;
  216. /* We need to do this the hard way... */
  217. obj = deref_tag(r, parse_object(r, oid), NULL, 0);
  218. if (obj && obj->type == OBJ_COMMIT)
  219. return 1;
  220. return 0;
  221. }
  222. static int disambiguate_tree_only(struct repository *r,
  223. const struct object_id *oid,
  224. void *cb_data_unused)
  225. {
  226. int kind = oid_object_info(r, oid, NULL);
  227. return kind == OBJ_TREE;
  228. }
  229. static int disambiguate_treeish_only(struct repository *r,
  230. const struct object_id *oid,
  231. void *cb_data_unused)
  232. {
  233. struct object *obj;
  234. int kind;
  235. kind = oid_object_info(r, oid, NULL);
  236. if (kind == OBJ_TREE || kind == OBJ_COMMIT)
  237. return 1;
  238. if (kind != OBJ_TAG)
  239. return 0;
  240. /* We need to do this the hard way... */
  241. obj = deref_tag(r, parse_object(r, oid), NULL, 0);
  242. if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
  243. return 1;
  244. return 0;
  245. }
  246. static int disambiguate_blob_only(struct repository *r,
  247. const struct object_id *oid,
  248. void *cb_data_unused)
  249. {
  250. int kind = oid_object_info(r, oid, NULL);
  251. return kind == OBJ_BLOB;
  252. }
  253. static disambiguate_hint_fn default_disambiguate_hint;
  254. int set_disambiguate_hint_config(const char *var, const char *value)
  255. {
  256. static const struct {
  257. const char *name;
  258. disambiguate_hint_fn fn;
  259. } hints[] = {
  260. { "none", NULL },
  261. { "commit", disambiguate_commit_only },
  262. { "committish", disambiguate_committish_only },
  263. { "tree", disambiguate_tree_only },
  264. { "treeish", disambiguate_treeish_only },
  265. { "blob", disambiguate_blob_only }
  266. };
  267. int i;
  268. if (!value)
  269. return config_error_nonbool(var);
  270. for (i = 0; i < ARRAY_SIZE(hints); i++) {
  271. if (!strcasecmp(value, hints[i].name)) {
  272. default_disambiguate_hint = hints[i].fn;
  273. return 0;
  274. }
  275. }
  276. return error("unknown hint type for '%s': %s", var, value);
  277. }
  278. static int init_object_disambiguation(struct repository *r,
  279. const char *name, int len,
  280. struct disambiguate_state *ds)
  281. {
  282. int i;
  283. if (len < MINIMUM_ABBREV || len > the_hash_algo->hexsz)
  284. return -1;
  285. memset(ds, 0, sizeof(*ds));
  286. for (i = 0; i < len ;i++) {
  287. unsigned char c = name[i];
  288. unsigned char val;
  289. if (c >= '0' && c <= '9')
  290. val = c - '0';
  291. else if (c >= 'a' && c <= 'f')
  292. val = c - 'a' + 10;
  293. else if (c >= 'A' && c <='F') {
  294. val = c - 'A' + 10;
  295. c -= 'A' - 'a';
  296. }
  297. else
  298. return -1;
  299. ds->hex_pfx[i] = c;
  300. if (!(i & 1))
  301. val <<= 4;
  302. ds->bin_pfx.hash[i >> 1] |= val;
  303. }
  304. ds->len = len;
  305. ds->hex_pfx[len] = '\0';
  306. ds->repo = r;
  307. prepare_alt_odb(r);
  308. return 0;
  309. }
  310. static int show_ambiguous_object(const struct object_id *oid, void *data)
  311. {
  312. const struct disambiguate_state *ds = data;
  313. struct strbuf desc = STRBUF_INIT;
  314. int type;
  315. if (ds->fn && !ds->fn(ds->repo, oid, ds->cb_data))
  316. return 0;
  317. type = oid_object_info(ds->repo, oid, NULL);
  318. if (type == OBJ_COMMIT) {
  319. struct commit *commit = lookup_commit(ds->repo, oid);
  320. if (commit) {
  321. struct pretty_print_context pp = {0};
  322. pp.date_mode.type = DATE_SHORT;
  323. format_commit_message(commit, " %ad - %s", &desc, &pp);
  324. }
  325. } else if (type == OBJ_TAG) {
  326. struct tag *tag = lookup_tag(ds->repo, oid);
  327. if (!parse_tag(tag) && tag->tag)
  328. strbuf_addf(&desc, " %s", tag->tag);
  329. }
  330. advise(" %s %s%s",
  331. repo_find_unique_abbrev(ds->repo, oid, DEFAULT_ABBREV),
  332. type_name(type) ? type_name(type) : "unknown type",
  333. desc.buf);
  334. strbuf_release(&desc);
  335. return 0;
  336. }
  337. static int collect_ambiguous(const struct object_id *oid, void *data)
  338. {
  339. oid_array_append(data, oid);
  340. return 0;
  341. }
  342. static int repo_collect_ambiguous(struct repository *r,
  343. const struct object_id *oid,
  344. void *data)
  345. {
  346. return collect_ambiguous(oid, data);
  347. }
  348. static int sort_ambiguous(const void *a, const void *b, void *ctx)
  349. {
  350. struct repository *sort_ambiguous_repo = ctx;
  351. int a_type = oid_object_info(sort_ambiguous_repo, a, NULL);
  352. int b_type = oid_object_info(sort_ambiguous_repo, b, NULL);
  353. int a_type_sort;
  354. int b_type_sort;
  355. /*
  356. * Sorts by hash within the same object type, just as
  357. * oid_array_for_each_unique() would do.
  358. */
  359. if (a_type == b_type)
  360. return oidcmp(a, b);
  361. /*
  362. * Between object types show tags, then commits, and finally
  363. * trees and blobs.
  364. *
  365. * The object_type enum is commit, tree, blob, tag, but we
  366. * want tag, commit, tree blob. Cleverly (perhaps too
  367. * cleverly) do that with modulus, since the enum assigns 1 to
  368. * commit, so tag becomes 0.
  369. */
  370. a_type_sort = a_type % 4;
  371. b_type_sort = b_type % 4;
  372. return a_type_sort > b_type_sort ? 1 : -1;
  373. }
  374. static void sort_ambiguous_oid_array(struct repository *r, struct oid_array *a)
  375. {
  376. QSORT_S(a->oid, a->nr, sort_ambiguous, r);
  377. }
  378. static enum get_oid_result get_short_oid(struct repository *r,
  379. const char *name, int len,
  380. struct object_id *oid,
  381. unsigned flags)
  382. {
  383. int status;
  384. struct disambiguate_state ds;
  385. int quietly = !!(flags & GET_OID_QUIETLY);
  386. if (init_object_disambiguation(r, name, len, &ds) < 0)
  387. return -1;
  388. if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
  389. BUG("multiple get_short_oid disambiguator flags");
  390. if (flags & GET_OID_COMMIT)
  391. ds.fn = disambiguate_commit_only;
  392. else if (flags & GET_OID_COMMITTISH)
  393. ds.fn = disambiguate_committish_only;
  394. else if (flags & GET_OID_TREE)
  395. ds.fn = disambiguate_tree_only;
  396. else if (flags & GET_OID_TREEISH)
  397. ds.fn = disambiguate_treeish_only;
  398. else if (flags & GET_OID_BLOB)
  399. ds.fn = disambiguate_blob_only;
  400. else
  401. ds.fn = default_disambiguate_hint;
  402. find_short_object_filename(&ds);
  403. find_short_packed_object(&ds);
  404. status = finish_object_disambiguation(&ds, oid);
  405. /*
  406. * If we didn't find it, do the usual reprepare() slow-path,
  407. * since the object may have recently been added to the repository
  408. * or migrated from loose to packed.
  409. */
  410. if (status == MISSING_OBJECT) {
  411. reprepare_packed_git(r);
  412. find_short_object_filename(&ds);
  413. find_short_packed_object(&ds);
  414. status = finish_object_disambiguation(&ds, oid);
  415. }
  416. if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
  417. struct oid_array collect = OID_ARRAY_INIT;
  418. error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
  419. /*
  420. * We may still have ambiguity if we simply saw a series of
  421. * candidates that did not satisfy our hint function. In
  422. * that case, we still want to show them, so disable the hint
  423. * function entirely.
  424. */
  425. if (!ds.ambiguous)
  426. ds.fn = NULL;
  427. advise(_("The candidates are:"));
  428. repo_for_each_abbrev(r, ds.hex_pfx, collect_ambiguous, &collect);
  429. sort_ambiguous_oid_array(r, &collect);
  430. if (oid_array_for_each(&collect, show_ambiguous_object, &ds))
  431. BUG("show_ambiguous_object shouldn't return non-zero");
  432. oid_array_clear(&collect);
  433. }
  434. return status;
  435. }
  436. int repo_for_each_abbrev(struct repository *r, const char *prefix,
  437. each_abbrev_fn fn, void *cb_data)
  438. {
  439. struct oid_array collect = OID_ARRAY_INIT;
  440. struct disambiguate_state ds;
  441. int ret;
  442. if (init_object_disambiguation(r, prefix, strlen(prefix), &ds) < 0)
  443. return -1;
  444. ds.always_call_fn = 1;
  445. ds.fn = repo_collect_ambiguous;
  446. ds.cb_data = &collect;
  447. find_short_object_filename(&ds);
  448. find_short_packed_object(&ds);
  449. ret = oid_array_for_each_unique(&collect, fn, cb_data);
  450. oid_array_clear(&collect);
  451. return ret;
  452. }
  453. /*
  454. * Return the slot of the most-significant bit set in "val". There are various
  455. * ways to do this quickly with fls() or __builtin_clzl(), but speed is
  456. * probably not a big deal here.
  457. */
  458. static unsigned msb(unsigned long val)
  459. {
  460. unsigned r = 0;
  461. while (val >>= 1)
  462. r++;
  463. return r;
  464. }
  465. struct min_abbrev_data {
  466. unsigned int init_len;
  467. unsigned int cur_len;
  468. char *hex;
  469. struct repository *repo;
  470. const struct object_id *oid;
  471. };
  472. static inline char get_hex_char_from_oid(const struct object_id *oid,
  473. unsigned int pos)
  474. {
  475. static const char hex[] = "0123456789abcdef";
  476. if ((pos & 1) == 0)
  477. return hex[oid->hash[pos >> 1] >> 4];
  478. else
  479. return hex[oid->hash[pos >> 1] & 0xf];
  480. }
  481. static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
  482. {
  483. struct min_abbrev_data *mad = cb_data;
  484. unsigned int i = mad->init_len;
  485. while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
  486. i++;
  487. if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
  488. mad->cur_len = i + 1;
  489. return 0;
  490. }
  491. static int repo_extend_abbrev_len(struct repository *r,
  492. const struct object_id *oid,
  493. void *cb_data)
  494. {
  495. return extend_abbrev_len(oid, cb_data);
  496. }
  497. static void find_abbrev_len_for_midx(struct multi_pack_index *m,
  498. struct min_abbrev_data *mad)
  499. {
  500. int match = 0;
  501. uint32_t num, first = 0;
  502. struct object_id oid;
  503. const struct object_id *mad_oid;
  504. if (!m->num_objects)
  505. return;
  506. num = m->num_objects;
  507. mad_oid = mad->oid;
  508. match = bsearch_midx(mad_oid, m, &first);
  509. /*
  510. * first is now the position in the packfile where we would insert
  511. * mad->hash if it does not exist (or the position of mad->hash if
  512. * it does exist). Hence, we consider a maximum of two objects
  513. * nearby for the abbreviation length.
  514. */
  515. mad->init_len = 0;
  516. if (!match) {
  517. if (nth_midxed_object_oid(&oid, m, first))
  518. extend_abbrev_len(&oid, mad);
  519. } else if (first < num - 1) {
  520. if (nth_midxed_object_oid(&oid, m, first + 1))
  521. extend_abbrev_len(&oid, mad);
  522. }
  523. if (first > 0) {
  524. if (nth_midxed_object_oid(&oid, m, first - 1))
  525. extend_abbrev_len(&oid, mad);
  526. }
  527. mad->init_len = mad->cur_len;
  528. }
  529. static void find_abbrev_len_for_pack(struct packed_git *p,
  530. struct min_abbrev_data *mad)
  531. {
  532. int match = 0;
  533. uint32_t num, first = 0;
  534. struct object_id oid;
  535. const struct object_id *mad_oid;
  536. if (p->multi_pack_index)
  537. return;
  538. if (open_pack_index(p) || !p->num_objects)
  539. return;
  540. num = p->num_objects;
  541. mad_oid = mad->oid;
  542. match = bsearch_pack(mad_oid, p, &first);
  543. /*
  544. * first is now the position in the packfile where we would insert
  545. * mad->hash if it does not exist (or the position of mad->hash if
  546. * it does exist). Hence, we consider a maximum of two objects
  547. * nearby for the abbreviation length.
  548. */
  549. mad->init_len = 0;
  550. if (!match) {
  551. if (nth_packed_object_oid(&oid, p, first))
  552. extend_abbrev_len(&oid, mad);
  553. } else if (first < num - 1) {
  554. if (nth_packed_object_oid(&oid, p, first + 1))
  555. extend_abbrev_len(&oid, mad);
  556. }
  557. if (first > 0) {
  558. if (nth_packed_object_oid(&oid, p, first - 1))
  559. extend_abbrev_len(&oid, mad);
  560. }
  561. mad->init_len = mad->cur_len;
  562. }
  563. static void find_abbrev_len_packed(struct min_abbrev_data *mad)
  564. {
  565. struct multi_pack_index *m;
  566. struct packed_git *p;
  567. for (m = get_multi_pack_index(mad->repo); m; m = m->next)
  568. find_abbrev_len_for_midx(m, mad);
  569. for (p = get_packed_git(mad->repo); p; p = p->next)
  570. find_abbrev_len_for_pack(p, mad);
  571. }
  572. int repo_find_unique_abbrev_r(struct repository *r, char *hex,
  573. const struct object_id *oid, int len)
  574. {
  575. struct disambiguate_state ds;
  576. struct min_abbrev_data mad;
  577. struct object_id oid_ret;
  578. const unsigned hexsz = r->hash_algo->hexsz;
  579. if (len < 0) {
  580. unsigned long count = repo_approximate_object_count(r);
  581. /*
  582. * Add one because the MSB only tells us the highest bit set,
  583. * not including the value of all the _other_ bits (so "15"
  584. * is only one off of 2^4, but the MSB is the 3rd bit.
  585. */
  586. len = msb(count) + 1;
  587. /*
  588. * We now know we have on the order of 2^len objects, which
  589. * expects a collision at 2^(len/2). But we also care about hex
  590. * chars, not bits, and there are 4 bits per hex. So all
  591. * together we need to divide by 2 and round up.
  592. */
  593. len = DIV_ROUND_UP(len, 2);
  594. /*
  595. * For very small repos, we stick with our regular fallback.
  596. */
  597. if (len < FALLBACK_DEFAULT_ABBREV)
  598. len = FALLBACK_DEFAULT_ABBREV;
  599. }
  600. oid_to_hex_r(hex, oid);
  601. if (len == hexsz || !len)
  602. return hexsz;
  603. mad.repo = r;
  604. mad.init_len = len;
  605. mad.cur_len = len;
  606. mad.hex = hex;
  607. mad.oid = oid;
  608. find_abbrev_len_packed(&mad);
  609. if (init_object_disambiguation(r, hex, mad.cur_len, &ds) < 0)
  610. return -1;
  611. ds.fn = repo_extend_abbrev_len;
  612. ds.always_call_fn = 1;
  613. ds.cb_data = (void *)&mad;
  614. find_short_object_filename(&ds);
  615. (void)finish_object_disambiguation(&ds, &oid_ret);
  616. hex[mad.cur_len] = 0;
  617. return mad.cur_len;
  618. }
  619. const char *repo_find_unique_abbrev(struct repository *r,
  620. const struct object_id *oid,
  621. int len)
  622. {
  623. static int bufno;
  624. static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
  625. char *hex = hexbuffer[bufno];
  626. bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
  627. repo_find_unique_abbrev_r(r, hex, oid, len);
  628. return hex;
  629. }
  630. static int ambiguous_path(const char *path, int len)
  631. {
  632. int slash = 1;
  633. int cnt;
  634. for (cnt = 0; cnt < len; cnt++) {
  635. switch (*path++) {
  636. case '\0':
  637. break;
  638. case '/':
  639. if (slash)
  640. break;
  641. slash = 1;
  642. continue;
  643. case '.':
  644. continue;
  645. default:
  646. slash = 0;
  647. continue;
  648. }
  649. break;
  650. }
  651. return slash;
  652. }
  653. static inline int at_mark(const char *string, int len,
  654. const char **suffix, int nr)
  655. {
  656. int i;
  657. for (i = 0; i < nr; i++) {
  658. int suffix_len = strlen(suffix[i]);
  659. if (suffix_len <= len
  660. && !strncasecmp(string, suffix[i], suffix_len))
  661. return suffix_len;
  662. }
  663. return 0;
  664. }
  665. static inline int upstream_mark(const char *string, int len)
  666. {
  667. const char *suffix[] = { "@{upstream}", "@{u}" };
  668. return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
  669. }
  670. static inline int push_mark(const char *string, int len)
  671. {
  672. const char *suffix[] = { "@{push}" };
  673. return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
  674. }
  675. static enum get_oid_result get_oid_1(struct repository *r, const char *name, int len, struct object_id *oid, unsigned lookup_flags);
  676. static int interpret_nth_prior_checkout(struct repository *r, const char *name, int namelen, struct strbuf *buf);
  677. static int get_oid_basic(struct repository *r, const char *str, int len,
  678. struct object_id *oid, unsigned int flags)
  679. {
  680. static const char *warn_msg = "refname '%.*s' is ambiguous.";
  681. static const char *object_name_msg = N_(
  682. "Git normally never creates a ref that ends with 40 hex characters\n"
  683. "because it will be ignored when you just specify 40-hex. These refs\n"
  684. "may be created by mistake. For example,\n"
  685. "\n"
  686. " git switch -c $br $(git rev-parse ...)\n"
  687. "\n"
  688. "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
  689. "examine these refs and maybe delete them. Turn this message off by\n"
  690. "running \"git config advice.objectNameWarning false\"");
  691. struct object_id tmp_oid;
  692. char *real_ref = NULL;
  693. int refs_found = 0;
  694. int at, reflog_len, nth_prior = 0;
  695. if (len == r->hash_algo->hexsz && !get_oid_hex(str, oid)) {
  696. if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
  697. refs_found = repo_dwim_ref(r, str, len, &tmp_oid, &real_ref);
  698. if (refs_found > 0) {
  699. warning(warn_msg, len, str);
  700. if (advice_object_name_warning)
  701. fprintf(stderr, "%s\n", _(object_name_msg));
  702. }
  703. free(real_ref);
  704. }
  705. return 0;
  706. }
  707. /* basic@{time or number or -number} format to query ref-log */
  708. reflog_len = at = 0;
  709. if (len && str[len-1] == '}') {
  710. for (at = len-4; at >= 0; at--) {
  711. if (str[at] == '@' && str[at+1] == '{') {
  712. if (str[at+2] == '-') {
  713. if (at != 0)
  714. /* @{-N} not at start */
  715. return -1;
  716. nth_prior = 1;
  717. continue;
  718. }
  719. if (!upstream_mark(str + at, len - at) &&
  720. !push_mark(str + at, len - at)) {
  721. reflog_len = (len-1) - (at+2);
  722. len = at;
  723. }
  724. break;
  725. }
  726. }
  727. }
  728. /* Accept only unambiguous ref paths. */
  729. if (len && ambiguous_path(str, len))
  730. return -1;
  731. if (nth_prior) {
  732. struct strbuf buf = STRBUF_INIT;
  733. int detached;
  734. if (interpret_nth_prior_checkout(r, str, len, &buf) > 0) {
  735. detached = (buf.len == r->hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
  736. strbuf_release(&buf);
  737. if (detached)
  738. return 0;
  739. }
  740. }
  741. if (!len && reflog_len)
  742. /* allow "@{...}" to mean the current branch reflog */
  743. refs_found = repo_dwim_ref(r, "HEAD", 4, oid, &real_ref);
  744. else if (reflog_len)
  745. refs_found = repo_dwim_log(r, str, len, oid, &real_ref);
  746. else
  747. refs_found = repo_dwim_ref(r, str, len, oid, &real_ref);
  748. if (!refs_found)
  749. return -1;
  750. if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
  751. (refs_found > 1 ||
  752. !get_short_oid(r, str, len, &tmp_oid, GET_OID_QUIETLY)))
  753. warning(warn_msg, len, str);
  754. if (reflog_len) {
  755. int nth, i;
  756. timestamp_t at_time;
  757. timestamp_t co_time;
  758. int co_tz, co_cnt;
  759. /* Is it asking for N-th entry, or approxidate? */
  760. for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
  761. char ch = str[at+2+i];
  762. if ('0' <= ch && ch <= '9')
  763. nth = nth * 10 + ch - '0';
  764. else
  765. nth = -1;
  766. }
  767. if (100000000 <= nth) {
  768. at_time = nth;
  769. nth = -1;
  770. } else if (0 <= nth)
  771. at_time = 0;
  772. else {
  773. int errors = 0;
  774. char *tmp = xstrndup(str + at + 2, reflog_len);
  775. at_time = approxidate_careful(tmp, &errors);
  776. free(tmp);
  777. if (errors) {
  778. free(real_ref);
  779. return -1;
  780. }
  781. }
  782. if (read_ref_at(get_main_ref_store(r),
  783. real_ref, flags, at_time, nth, oid, NULL,
  784. &co_time, &co_tz, &co_cnt)) {
  785. if (!len) {
  786. if (starts_with(real_ref, "refs/heads/")) {
  787. str = real_ref + 11;
  788. len = strlen(real_ref + 11);
  789. } else {
  790. /* detached HEAD */
  791. str = "HEAD";
  792. len = 4;
  793. }
  794. }
  795. if (at_time) {
  796. if (!(flags & GET_OID_QUIETLY)) {
  797. warning("Log for '%.*s' only goes "
  798. "back to %s.", len, str,
  799. show_date(co_time, co_tz, DATE_MODE(RFC2822)));
  800. }
  801. } else {
  802. if (flags & GET_OID_QUIETLY) {
  803. exit(128);
  804. }
  805. die("Log for '%.*s' only has %d entries.",
  806. len, str, co_cnt);
  807. }
  808. }
  809. }
  810. free(real_ref);
  811. return 0;
  812. }
  813. static enum get_oid_result get_parent(struct repository *r,
  814. const char *name, int len,
  815. struct object_id *result, int idx)
  816. {
  817. struct object_id oid;
  818. enum get_oid_result ret = get_oid_1(r, name, len, &oid,
  819. GET_OID_COMMITTISH);
  820. struct commit *commit;
  821. struct commit_list *p;
  822. if (ret)
  823. return ret;
  824. commit = lookup_commit_reference(r, &oid);
  825. if (parse_commit(commit))
  826. return MISSING_OBJECT;
  827. if (!idx) {
  828. oidcpy(result, &commit->object.oid);
  829. return FOUND;
  830. }
  831. p = commit->parents;
  832. while (p) {
  833. if (!--idx) {
  834. oidcpy(result, &p->item->object.oid);
  835. return FOUND;
  836. }
  837. p = p->next;
  838. }
  839. return MISSING_OBJECT;
  840. }
  841. static enum get_oid_result get_nth_ancestor(struct repository *r,
  842. const char *name, int len,
  843. struct object_id *result,
  844. int generation)
  845. {
  846. struct object_id oid;
  847. struct commit *commit;
  848. int ret;
  849. ret = get_oid_1(r, name, len, &oid, GET_OID_COMMITTISH);
  850. if (ret)
  851. return ret;
  852. commit = lookup_commit_reference(r, &oid);
  853. if (!commit)
  854. return MISSING_OBJECT;
  855. while (generation--) {
  856. if (parse_commit(commit) || !commit->parents)
  857. return MISSING_OBJECT;
  858. commit = commit->parents->item;
  859. }
  860. oidcpy(result, &commit->object.oid);
  861. return FOUND;
  862. }
  863. struct object *repo_peel_to_type(struct repository *r, const char *name, int namelen,
  864. struct object *o, enum object_type expected_type)
  865. {
  866. if (name && !namelen)
  867. namelen = strlen(name);
  868. while (1) {
  869. if (!o || (!o->parsed && !parse_object(r, &o->oid)))
  870. return NULL;
  871. if (expected_type == OBJ_ANY || o->type == expected_type)
  872. return o;
  873. if (o->type == OBJ_TAG)
  874. o = ((struct tag*) o)->tagged;
  875. else if (o->type == OBJ_COMMIT)
  876. o = &(repo_get_commit_tree(r, ((struct commit *)o))->object);
  877. else {
  878. if (name)
  879. error("%.*s: expected %s type, but the object "
  880. "dereferences to %s type",
  881. namelen, name, type_name(expected_type),
  882. type_name(o->type));
  883. return NULL;
  884. }
  885. }
  886. }
  887. static int peel_onion(struct repository *r, const char *name, int len,
  888. struct object_id *oid, unsigned lookup_flags)
  889. {
  890. struct object_id outer;
  891. const char *sp;
  892. unsigned int expected_type = 0;
  893. struct object *o;
  894. /*
  895. * "ref^{type}" dereferences ref repeatedly until you cannot
  896. * dereference anymore, or you get an object of given type,
  897. * whichever comes first. "ref^{}" means just dereference
  898. * tags until you get a non-tag. "ref^0" is a shorthand for
  899. * "ref^{commit}". "commit^{tree}" could be used to find the
  900. * top-level tree of the given commit.
  901. */
  902. if (len < 4 || name[len-1] != '}')
  903. return -1;
  904. for (sp = name + len - 1; name <= sp; sp--) {
  905. int ch = *sp;
  906. if (ch == '{' && name < sp && sp[-1] == '^')
  907. break;
  908. }
  909. if (sp <= name)
  910. return -1;
  911. sp++; /* beginning of type name, or closing brace for empty */
  912. if (starts_with(sp, "commit}"))
  913. expected_type = OBJ_COMMIT;
  914. else if (starts_with(sp, "tag}"))
  915. expected_type = OBJ_TAG;
  916. else if (starts_with(sp, "tree}"))
  917. expected_type = OBJ_TREE;
  918. else if (starts_with(sp, "blob}"))
  919. expected_type = OBJ_BLOB;
  920. else if (starts_with(sp, "object}"))
  921. expected_type = OBJ_ANY;
  922. else if (sp[0] == '}')
  923. expected_type = OBJ_NONE;
  924. else if (sp[0] == '/')
  925. expected_type = OBJ_COMMIT;
  926. else
  927. return -1;
  928. lookup_flags &= ~GET_OID_DISAMBIGUATORS;
  929. if (expected_type == OBJ_COMMIT)
  930. lookup_flags |= GET_OID_COMMITTISH;
  931. else if (expected_type == OBJ_TREE)
  932. lookup_flags |= GET_OID_TREEISH;
  933. if (get_oid_1(r, name, sp - name - 2, &outer, lookup_flags))
  934. return -1;
  935. o = parse_object(r, &outer);
  936. if (!o)
  937. return -1;
  938. if (!expected_type) {
  939. o = deref_tag(r, o, name, sp - name - 2);
  940. if (!o || (!o->parsed && !parse_object(r, &o->oid)))
  941. return -1;
  942. oidcpy(oid, &o->oid);
  943. return 0;
  944. }
  945. /*
  946. * At this point, the syntax look correct, so
  947. * if we do not get the needed object, we should
  948. * barf.
  949. */
  950. o = repo_peel_to_type(r, name, len, o, expected_type);
  951. if (!o)
  952. return -1;
  953. oidcpy(oid, &o->oid);
  954. if (sp[0] == '/') {
  955. /* "$commit^{/foo}" */
  956. char *prefix;
  957. int ret;
  958. struct commit_list *list = NULL;
  959. /*
  960. * $commit^{/}. Some regex implementation may reject.
  961. * We don't need regex anyway. '' pattern always matches.
  962. */
  963. if (sp[1] == '}')
  964. return 0;
  965. prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
  966. commit_list_insert((struct commit *)o, &list);
  967. ret = get_oid_oneline(r, prefix, oid, list);
  968. free(prefix);
  969. return ret;
  970. }
  971. return 0;
  972. }
  973. static int get_describe_name(struct repository *r,
  974. const char *name, int len,
  975. struct object_id *oid)
  976. {
  977. const char *cp;
  978. unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
  979. for (cp = name + len - 1; name + 2 <= cp; cp--) {
  980. char ch = *cp;
  981. if (!isxdigit(ch)) {
  982. /* We must be looking at g in "SOMETHING-g"
  983. * for it to be describe output.
  984. */
  985. if (ch == 'g' && cp[-1] == '-') {
  986. cp++;
  987. len -= cp - name;
  988. return get_short_oid(r,
  989. cp, len, oid, flags);
  990. }
  991. }
  992. }
  993. return -1;
  994. }
  995. static enum get_oid_result get_oid_1(struct repository *r,
  996. const char *name, int len,
  997. struct object_id *oid,
  998. unsigned lookup_flags)
  999. {
  1000. int ret, has_suffix;
  1001. const char *cp;
  1002. /*
  1003. * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
  1004. */
  1005. has_suffix = 0;
  1006. for (cp = name + len - 1; name <= cp; cp--) {
  1007. int ch = *cp;
  1008. if ('0' <= ch && ch <= '9')
  1009. continue;
  1010. if (ch == '~' || ch == '^')
  1011. has_suffix = ch;
  1012. break;
  1013. }
  1014. if (has_suffix) {
  1015. unsigned int num = 0;
  1016. int len1 = cp - name;
  1017. cp++;
  1018. while (cp < name + len) {
  1019. unsigned int digit = *cp++ - '0';
  1020. if (unsigned_mult_overflows(num, 10))
  1021. return MISSING_OBJECT;
  1022. num *= 10;
  1023. if (unsigned_add_overflows(num, digit))
  1024. return MISSING_OBJECT;
  1025. num += digit;
  1026. }
  1027. if (!num && len1 == len - 1)
  1028. num = 1;
  1029. else if (num > INT_MAX)
  1030. return MISSING_OBJECT;
  1031. if (has_suffix == '^')
  1032. return get_parent(r, name, len1, oid, num);
  1033. /* else if (has_suffix == '~') -- goes without saying */
  1034. return get_nth_ancestor(r, name, len1, oid, num);
  1035. }
  1036. ret = peel_onion(r, name, len, oid, lookup_flags);
  1037. if (!ret)
  1038. return FOUND;
  1039. ret = get_oid_basic(r, name, len, oid, lookup_flags);
  1040. if (!ret)
  1041. return FOUND;
  1042. /* It could be describe output that is "SOMETHING-gXXXX" */
  1043. ret = get_describe_name(r, name, len, oid);
  1044. if (!ret)
  1045. return FOUND;
  1046. return get_short_oid(r, name, len, oid, lookup_flags);
  1047. }
  1048. /*
  1049. * This interprets names like ':/Initial revision of "git"' by searching
  1050. * through history and returning the first commit whose message starts
  1051. * the given regular expression.
  1052. *
  1053. * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
  1054. *
  1055. * For a literal '!' character at the beginning of a pattern, you have to repeat
  1056. * that, like: ':/!!foo'
  1057. *
  1058. * For future extension, all other sequences beginning with ':/!' are reserved.
  1059. */
  1060. /* Remember to update object flag allocation in object.h */
  1061. #define ONELINE_SEEN (1u<<20)
  1062. struct handle_one_ref_cb {
  1063. struct repository *repo;
  1064. struct commit_list **list;
  1065. };
  1066. static int handle_one_ref(const char *path, const struct object_id *oid,
  1067. int flag, void *cb_data)
  1068. {
  1069. struct handle_one_ref_cb *cb = cb_data;
  1070. struct commit_list **list = cb->list;
  1071. struct object *object = parse_object(cb->repo, oid);
  1072. if (!object)
  1073. return 0;
  1074. if (object->type == OBJ_TAG) {
  1075. object = deref_tag(cb->repo, object, path,
  1076. strlen(path));
  1077. if (!object)
  1078. return 0;
  1079. }
  1080. if (object->type != OBJ_COMMIT)
  1081. return 0;
  1082. commit_list_insert((struct commit *)object, list);
  1083. return 0;
  1084. }
  1085. static int get_oid_oneline(struct repository *r,
  1086. const char *prefix, struct object_id *oid,
  1087. struct commit_list *list)
  1088. {
  1089. struct commit_list *backup = NULL, *l;
  1090. int found = 0;
  1091. int negative = 0;
  1092. regex_t regex;
  1093. if (prefix[0] == '!') {
  1094. prefix++;
  1095. if (prefix[0] == '-') {
  1096. prefix++;
  1097. negative = 1;
  1098. } else if (prefix[0] != '!') {
  1099. return -1;
  1100. }
  1101. }
  1102. if (regcomp(&regex, prefix, REG_EXTENDED))
  1103. return -1;
  1104. for (l = list; l; l = l->next) {
  1105. l->item->object.flags |= ONELINE_SEEN;
  1106. commit_list_insert(l->item, &backup);
  1107. }
  1108. while (list) {
  1109. const char *p, *buf;
  1110. struct commit *commit;
  1111. int matches;
  1112. commit = pop_most_recent_commit(&list, ONELINE_SEEN);
  1113. if (!parse_object(r, &commit->object.oid))
  1114. continue;
  1115. buf = get_commit_buffer(commit, NULL);
  1116. p = strstr(buf, "\n\n");
  1117. matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
  1118. unuse_commit_buffer(commit, buf);
  1119. if (matches) {
  1120. oidcpy(oid, &commit->object.oid);
  1121. found = 1;
  1122. break;
  1123. }
  1124. }
  1125. regfree(&regex);
  1126. free_commit_list(list);
  1127. for (l = backup; l; l = l->next)
  1128. clear_commit_marks(l->item, ONELINE_SEEN);
  1129. free_commit_list(backup);
  1130. return found ? 0 : -1;
  1131. }
  1132. struct grab_nth_branch_switch_cbdata {
  1133. int remaining;
  1134. struct strbuf *sb;
  1135. };
  1136. static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
  1137. const char *email, timestamp_t timestamp, int tz,
  1138. const char *message, void *cb_data)
  1139. {
  1140. struct grab_nth_branch_switch_cbdata *cb = cb_data;
  1141. const char *match = NULL, *target = NULL;
  1142. size_t len;
  1143. if (skip_prefix(message, "checkout: moving from ", &match))
  1144. target = strstr(match, " to ");
  1145. if (!match || !target)
  1146. return 0;
  1147. if (--(cb->remaining) == 0) {
  1148. len = target - match;
  1149. strbuf_reset(cb->sb);
  1150. strbuf_add(cb->sb, match, len);
  1151. return 1; /* we are done */
  1152. }
  1153. return 0;
  1154. }
  1155. /*
  1156. * Parse @{-N} syntax, return the number of characters parsed
  1157. * if successful; otherwise signal an error with negative value.
  1158. */
  1159. static int interpret_nth_prior_checkout(struct repository *r,
  1160. const char *name, int namelen,
  1161. struct strbuf *buf)
  1162. {
  1163. long nth;
  1164. int retval;
  1165. struct grab_nth_branch_switch_cbdata cb;
  1166. const char *brace;
  1167. char *num_end;
  1168. if (namelen < 4)
  1169. return -1;
  1170. if (name[0] != '@' || name[1] != '{' || name[2] != '-')
  1171. return -1;
  1172. brace = memchr(name, '}', namelen);
  1173. if (!brace)
  1174. return -1;
  1175. nth = strtol(name + 3, &num_end, 10);
  1176. if (num_end != brace)
  1177. return -1;
  1178. if (nth <= 0)
  1179. return -1;
  1180. cb.remaining = nth;
  1181. cb.sb = buf;
  1182. retval = refs_for_each_reflog_ent_reverse(get_main_ref_store(r),
  1183. "HEAD", grab_nth_branch_switch, &cb);
  1184. if (0 < retval) {
  1185. retval = brace - name + 1;
  1186. } else
  1187. retval = 0;
  1188. return retval;
  1189. }
  1190. int repo_get_oid_mb(struct repository *r,
  1191. const char *name,
  1192. struct object_id *oid)
  1193. {
  1194. struct commit *one, *two;
  1195. struct commit_list *mbs;
  1196. struct object_id oid_tmp;
  1197. const char *dots;
  1198. int st;
  1199. dots = strstr(name, "...");
  1200. if (!dots)
  1201. return repo_get_oid(r, name, oid);
  1202. if (dots == name)
  1203. st = repo_get_oid(r, "HEAD", &oid_tmp);
  1204. else {
  1205. struct strbuf sb;
  1206. strbuf_init(&sb, dots - name);
  1207. strbuf_add(&sb, name, dots - name);
  1208. st = repo_get_oid_committish(r, sb.buf, &oid_tmp);
  1209. strbuf_release(&sb);
  1210. }
  1211. if (st)
  1212. return st;
  1213. one = lookup_commit_reference_gently(r, &oid_tmp, 0);
  1214. if (!one)
  1215. return -1;
  1216. if (repo_get_oid_committish(r, dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
  1217. return -1;
  1218. two = lookup_commit_reference_gently(r, &oid_tmp, 0);
  1219. if (!two)
  1220. return -1;
  1221. mbs = repo_get_merge_bases(r, one, two);
  1222. if (!mbs || mbs->next)
  1223. st = -1;
  1224. else {
  1225. st = 0;
  1226. oidcpy(oid, &mbs->item->object.oid);
  1227. }
  1228. free_commit_list(mbs);
  1229. return st;
  1230. }
  1231. /* parse @something syntax, when 'something' is not {.*} */
  1232. static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
  1233. {
  1234. const char *next;
  1235. if (len || name[1] == '{')
  1236. return -1;
  1237. /* make sure it's a single @, or @@{.*}, not @foo */
  1238. next = memchr(name + len + 1, '@', namelen - len - 1);
  1239. if (next && next[1] != '{')
  1240. return -1;
  1241. if (!next)
  1242. next = name + namelen;
  1243. if (next != name + 1)
  1244. return -1;
  1245. strbuf_reset(buf);
  1246. strbuf_add(buf, "HEAD", 4);
  1247. return 1;
  1248. }
  1249. static int reinterpret(struct repository *r,
  1250. const char *name, int namelen, int len,
  1251. struct strbuf *buf, unsigned allowed)
  1252. {
  1253. /* we have extra data, which might need further processing */
  1254. struct strbuf tmp = STRBUF_INIT;
  1255. int used = buf->len;
  1256. int ret;
  1257. strbuf_add(buf, name + len, namelen - len);
  1258. ret = repo_interpret_branch_name(r, buf->buf, buf->len, &tmp, allowed);
  1259. /* that data was not interpreted, remove our cruft */
  1260. if (ret < 0) {
  1261. strbuf_setlen(buf, used);
  1262. return len;
  1263. }
  1264. strbuf_reset(buf);
  1265. strbuf_addbuf(buf, &tmp);
  1266. strbuf_release(&tmp);
  1267. /* tweak for size of {-N} versus expanded ref name */
  1268. return ret - used + len;
  1269. }
  1270. static void set_shortened_ref(struct repository *r, struct strbuf *buf, const char *ref)
  1271. {
  1272. char *s = refs_shorten_unambiguous_ref(get_main_ref_store(r), ref, 0);
  1273. strbuf_reset(buf);
  1274. strbuf_addstr(buf, s);
  1275. free(s);
  1276. }
  1277. static int branch_interpret_allowed(const char *refname, unsigned allowed)
  1278. {
  1279. if (!allowed)
  1280. return 1;
  1281. if ((allowed & INTERPRET_BRANCH_LOCAL) &&
  1282. starts_with(refname, "refs/heads/"))
  1283. return 1;
  1284. if ((allowed & INTERPRET_BRANCH_REMOTE) &&
  1285. starts_with(refname, "refs/remotes/"))
  1286. return 1;
  1287. return 0;
  1288. }
  1289. static int interpret_branch_mark(struct repository *r,
  1290. const char *name, int namelen,
  1291. int at, struct strbuf *buf,
  1292. int (*get_mark)(const char *, int),
  1293. const char *(*get_data)(struct branch *,
  1294. struct strbuf *),
  1295. unsigned allowed)
  1296. {
  1297. int len;
  1298. struct branch *branch;
  1299. struct strbuf err = STRBUF_INIT;
  1300. const char *value;
  1301. len = get_mark(name + at, namelen - at);
  1302. if (!len)
  1303. return -1;
  1304. if (memchr(name, ':', at))
  1305. return -1;
  1306. if (at) {
  1307. char *name_str = xmemdupz(name, at);
  1308. branch = branch_get(name_str);
  1309. free(name_str);
  1310. } else
  1311. branch = branch_get(NULL);
  1312. value = get_data(branch, &err);
  1313. if (!value)
  1314. die("%s", err.buf);
  1315. if (!branch_interpret_allowed(value, allowed))
  1316. return -1;
  1317. set_shortened_ref(r, buf, value);
  1318. return len + at;
  1319. }
  1320. int repo_interpret_branch_name(struct repository *r,
  1321. const char *name, int namelen,
  1322. struct strbuf *buf,
  1323. unsigned allowed)
  1324. {
  1325. char *at;
  1326. const char *start;
  1327. int len;
  1328. if (!namelen)
  1329. namelen = strlen(name);
  1330. if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
  1331. len = interpret_nth_prior_checkout(r, name, namelen, buf);
  1332. if (!len) {
  1333. return len; /* syntax Ok, not enough switches */
  1334. } else if (len > 0) {
  1335. if (len == namelen)
  1336. return len; /* consumed all */
  1337. else
  1338. return reinterpret(r, name, namelen, len, buf, allowed);
  1339. }
  1340. }
  1341. for (start = name;
  1342. (at = memchr(start, '@', namelen - (start - name)));
  1343. start = at + 1) {
  1344. if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
  1345. len = interpret_empty_at(name, namelen, at - name, buf);
  1346. if (len > 0)
  1347. return reinterpret(r, name, namelen, len, buf,
  1348. allowed);
  1349. }
  1350. len = interpret_branch_mark(r, name, namelen, at - name, buf,
  1351. upstream_mark, branch_get_upstream,
  1352. allowed);
  1353. if (len > 0)
  1354. return len;
  1355. len = interpret_branch_mark(r, name, namelen, at - name, buf,
  1356. push_mark, branch_get_push,
  1357. allowed);
  1358. if (len > 0)
  1359. return len;
  1360. }
  1361. return -1;
  1362. }
  1363. void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
  1364. {
  1365. int len = strlen(name);
  1366. int used = interpret_branch_name(name, len, sb, allowed);
  1367. if (used < 0)
  1368. used = 0;
  1369. strbuf_add(sb, name + used, len - used);
  1370. }
  1371. int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
  1372. {
  1373. if (startup_info->have_repository)
  1374. strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
  1375. else
  1376. strbuf_addstr(sb, name);
  1377. /*
  1378. * This splice must be done even if we end up rejecting the
  1379. * name; builtin/branch.c::copy_or_rename_branch() still wants
  1380. * to see what the name expanded to so that "branch -m" can be
  1381. * used as a tool to correct earlier mistakes.
  1382. */
  1383. strbuf_splice(sb, 0, 0, "refs/heads/", 11);
  1384. if (*name == '-' ||
  1385. !strcmp(sb->buf, "refs/heads/HEAD"))
  1386. return -1;
  1387. return check_refname_format(sb->buf, 0);
  1388. }
  1389. /*
  1390. * This is like "get_oid_basic()", except it allows "object ID expressions",
  1391. * notably "xyz^" for "parent of xyz"
  1392. */
  1393. int repo_get_oid(struct repository *r, const char *name, struct object_id *oid)
  1394. {
  1395. struct object_context unused;
  1396. return get_oid_with_context(r, name, 0, oid, &unused);
  1397. }
  1398. /*
  1399. * This returns a non-zero value if the string (built using printf
  1400. * format and the given arguments) is not a valid object.
  1401. */
  1402. int get_oidf(struct object_id *oid, const char *fmt, ...)
  1403. {
  1404. va_list ap;
  1405. int ret;
  1406. struct strbuf sb = STRBUF_INIT;
  1407. va_start(ap, fmt);
  1408. strbuf_vaddf(&sb, fmt, ap);
  1409. va_end(ap);
  1410. ret = get_oid(sb.buf, oid);
  1411. strbuf_release(&sb);
  1412. return ret;
  1413. }
  1414. /*
  1415. * Many callers know that the user meant to name a commit-ish by
  1416. * syntactical positions where the object name appears. Calling this
  1417. * function allows the machinery to disambiguate shorter-than-unique
  1418. * abbreviated object names between commit-ish and others.
  1419. *
  1420. * Note that this does NOT error out when the named object is not a
  1421. * commit-ish. It is merely to give a hint to the disambiguation
  1422. * machinery.
  1423. */
  1424. int repo_get_oid_committish(struct repository *r,
  1425. const char *name,
  1426. struct object_id *oid)
  1427. {
  1428. struct object_context unused;
  1429. return get_oid_with_context(r, name, GET_OID_COMMITTISH,
  1430. oid, &unused);
  1431. }
  1432. int repo_get_oid_treeish(struct repository *r,
  1433. const char *name,
  1434. struct object_id *oid)
  1435. {
  1436. struct object_context unused;
  1437. return get_oid_with_context(r, name, GET_OID_TREEISH,
  1438. oid, &unused);
  1439. }
  1440. int repo_get_oid_commit(struct repository *r,
  1441. const char *name,
  1442. struct object_id *oid)
  1443. {
  1444. struct object_context unused;
  1445. return get_oid_with_context(r, name, GET_OID_COMMIT,
  1446. oid, &unused);
  1447. }
  1448. int repo_get_oid_tree(struct repository *r,
  1449. const char *name,
  1450. struct object_id *oid)
  1451. {
  1452. struct object_context unused;
  1453. return get_oid_with_context(r, name, GET_OID_TREE,
  1454. oid, &unused);
  1455. }
  1456. int repo_get_oid_blob(struct repository *r,
  1457. const char *name,
  1458. struct object_id *oid)
  1459. {
  1460. struct object_context unused;
  1461. return get_oid_with_context(r, name, GET_OID_BLOB,
  1462. oid, &unused);
  1463. }
  1464. /* Must be called only when object_name:filename doesn't exist. */
  1465. static void diagnose_invalid_oid_path(struct repository *r,
  1466. const char *prefix,
  1467. const char *filename,
  1468. const struct object_id *tree_oid,
  1469. const char *object_name,
  1470. int object_name_len)
  1471. {
  1472. struct object_id oid;
  1473. unsigned short mode;
  1474. if (!prefix)
  1475. prefix = "";
  1476. if (file_exists(filename))
  1477. die("Path '%s' exists on disk, but not in '%.*s'.",
  1478. filename, object_name_len, object_name);
  1479. if (is_missing_file_error(errno)) {
  1480. char *fullname = xstrfmt("%s%s", prefix, filename);
  1481. if (!get_tree_entry(r, tree_oid, fullname, &oid, &mode)) {
  1482. die("Path '%s' exists, but not '%s'.\n"
  1483. "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
  1484. fullname,
  1485. filename,
  1486. object_name_len, object_name,
  1487. fullname,
  1488. object_name_len, object_name,
  1489. filename);
  1490. }
  1491. die("Path '%s' does not exist in '%.*s'",
  1492. filename, object_name_len, object_name);
  1493. }
  1494. }
  1495. /* Must be called only when :stage:filename doesn't exist. */
  1496. static void diagnose_invalid_index_path(struct repository *r,
  1497. int stage,
  1498. const char *prefix,
  1499. const char *filename)
  1500. {
  1501. struct index_state *istate = r->index;
  1502. const struct cache_entry *ce;
  1503. int pos;
  1504. unsigned namelen = strlen(filename);
  1505. struct strbuf fullname = STRBUF_INIT;
  1506. if (!prefix)
  1507. prefix = "";
  1508. /* Wrong stage number? */
  1509. pos = index_name_pos(istate, filename, namelen);
  1510. if (pos < 0)
  1511. pos = -pos - 1;
  1512. if (pos < istate->cache_nr) {
  1513. ce = istate->cache[pos];
  1514. if (ce_namelen(ce) == namelen &&
  1515. !memcmp(ce->name, filename, namelen))
  1516. die("Path '%s' is in the index, but not at stage %d.\n"
  1517. "Did you mean ':%d:%s'?",
  1518. filename, stage,
  1519. ce_stage(ce), filename);
  1520. }
  1521. /* Confusion between relative and absolute filenames? */
  1522. strbuf_addstr(&fullname, prefix);
  1523. strbuf_addstr(&fullname, filename);
  1524. pos = index_name_pos(istate, fullname.buf, fullname.len);
  1525. if (pos < 0)
  1526. pos = -pos - 1;
  1527. if (pos < istate->cache_nr) {
  1528. ce = istate->cache[pos];
  1529. if (ce_namelen(ce) == fullname.len &&
  1530. !memcmp(ce->name, fullname.buf, fullname.len))
  1531. die("Path '%s' is in the index, but not '%s'.\n"
  1532. "Did you mean ':%d:%s' aka ':%d:./%s'?",
  1533. fullname.buf, filename,
  1534. ce_stage(ce), fullname.buf,
  1535. ce_stage(ce), filename);
  1536. }
  1537. if (repo_file_exists(r, filename))
  1538. die("Path '%s' exists on disk, but not in the index.", filename);
  1539. if (is_missing_file_error(errno))
  1540. die("Path '%s' does not exist (neither on disk nor in the index).",
  1541. filename);
  1542. strbuf_release(&fullname);
  1543. }
  1544. static char *resolve_relative_path(struct repository *r, const char *rel)
  1545. {
  1546. if (!starts_with(rel, "./") && !starts_with(rel, "../"))
  1547. return NULL;
  1548. if (r != the_repository || !is_inside_work_tree())
  1549. die("relative path syntax can't be used outside working tree.");
  1550. /* die() inside prefix_path() if resolved path is outside worktree */
  1551. return prefix_path(startup_info->prefix,
  1552. startup_info->prefix ? strlen(startup_info->prefix) : 0,
  1553. rel);
  1554. }
  1555. static enum get_oid_result get_oid_with_context_1(struct repository *repo,
  1556. const char *name,
  1557. unsigned flags,
  1558. const char *prefix,
  1559. struct object_id *oid,
  1560. struct object_context *oc)
  1561. {
  1562. int ret, bracket_depth;
  1563. int namelen = strlen(name);
  1564. const char *cp;
  1565. int only_to_die = flags & GET_OID_ONLY_TO_DIE;
  1566. if (only_to_die)
  1567. flags |= GET_OID_QUIETLY;
  1568. memset(oc, 0, sizeof(*oc));
  1569. oc->mode = S_IFINVALID;
  1570. strbuf_init(&oc->symlink_path, 0);
  1571. ret = get_oid_1(repo, name, namelen, oid, flags);
  1572. if (!ret)
  1573. return ret;
  1574. /*
  1575. * sha1:path --> object name of path in ent sha1
  1576. * :path -> object name of absolute path in index
  1577. * :./path -> object name of path relative to cwd in index
  1578. * :[0-3]:path -> object name of path in index at stage
  1579. * :/foo -> recent commit matching foo
  1580. */
  1581. if (name[0] == ':') {
  1582. int stage = 0;
  1583. const struct cache_entry *ce;
  1584. char *new_path = NULL;
  1585. int pos;
  1586. if (!only_to_die && namelen > 2 && name[1] == '/') {
  1587. struct handle_one_ref_cb cb;
  1588. struct commit_list *list = NULL;
  1589. cb.repo = repo;
  1590. cb.list = &list;
  1591. refs_for_each_ref(repo->refs, handle_one_ref, &cb);
  1592. refs_head_ref(repo->refs, handle_one_ref, &cb);
  1593. commit_list_sort_by_date(&list);
  1594. return get_oid_oneline(repo, name + 2, oid, list);
  1595. }
  1596. if (namelen < 3 ||
  1597. name[2] != ':' ||
  1598. name[1] < '0' || '3' < name[1])
  1599. cp = name + 1;
  1600. else {
  1601. stage = name[1] - '0';
  1602. cp = name + 3;
  1603. }
  1604. new_path = resolve_relative_path(repo, cp);
  1605. if (!new_path) {
  1606. namelen = namelen - (cp - name);
  1607. } else {
  1608. cp = new_path;
  1609. namelen = strlen(cp);
  1610. }
  1611. if (flags & GET_OID_RECORD_PATH)
  1612. oc->path = xstrdup(cp);
  1613. if (!repo->index || !repo->index->cache)
  1614. repo_read_index(repo);
  1615. pos = index_name_pos(repo->index, cp, namelen);
  1616. if (pos < 0)
  1617. pos = -pos - 1;
  1618. while (pos < repo->index->cache_nr) {
  1619. ce = repo->index->cache[pos];
  1620. if (ce_namelen(ce) != namelen ||
  1621. memcmp(ce->name, cp, namelen))
  1622. break;
  1623. if (ce_stage(ce) == stage) {
  1624. oidcpy(oid, &ce->oid);
  1625. oc->mode = ce->ce_mode;
  1626. free(new_path);
  1627. return 0;
  1628. }
  1629. pos++;
  1630. }
  1631. if (only_to_die && name[1] && name[1] != '/')
  1632. diagnose_invalid_index_path(repo, stage, prefix, cp);
  1633. free(new_path);
  1634. return -1;
  1635. }
  1636. for (cp = name, bracket_depth = 0; *cp; cp++) {
  1637. if (*cp == '{')
  1638. bracket_depth++;
  1639. else if (bracket_depth && *cp == '}')
  1640. bracket_depth--;
  1641. else if (!bracket_depth && *cp == ':')
  1642. break;
  1643. }
  1644. if (*cp == ':') {
  1645. struct object_id tree_oid;
  1646. int len = cp - name;
  1647. unsigned sub_flags = flags;
  1648. sub_flags &= ~GET_OID_DISAMBIGUATORS;
  1649. sub_flags |= GET_OID_TREEISH;
  1650. if (!get_oid_1(repo, name, len, &tree_oid, sub_flags)) {
  1651. const char *filename = cp+1;
  1652. char *new_filename = NULL;
  1653. new_filename = resolve_relative_path(repo, filename);
  1654. if (new_filename)
  1655. filename = new_filename;
  1656. if (flags & GET_OID_FOLLOW_SYMLINKS) {
  1657. ret = get_tree_entry_follow_symlinks(repo, &tree_oid,
  1658. filename, oid, &oc->symlink_path,
  1659. &oc->mode);
  1660. } else {
  1661. ret = get_tree_entry(repo, &tree_oid, filename, oid,
  1662. &oc->mode);
  1663. if (ret && only_to_die) {
  1664. diagnose_invalid_oid_path(repo, prefix,
  1665. filename,
  1666. &tree_oid,
  1667. name, len);
  1668. }
  1669. }
  1670. if (flags & GET_OID_RECORD_PATH)
  1671. oc->path = xstrdup(filename);
  1672. free(new_filename);
  1673. return ret;
  1674. } else {
  1675. if (only_to_die)
  1676. die("Invalid object name '%.*s'.", len, name);
  1677. }
  1678. }
  1679. return ret;
  1680. }
  1681. /*
  1682. * Call this function when you know "name" given by the end user must
  1683. * name an object but it doesn't; the function _may_ die with a better
  1684. * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
  1685. * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
  1686. * you have a chance to diagnose the error further.
  1687. */
  1688. void maybe_die_on_misspelt_object_name(struct repository *r,
  1689. const char *name,
  1690. const char *prefix)
  1691. {
  1692. struct object_context oc;
  1693. struct object_id oid;
  1694. get_oid_with_context_1(r, name, GET_OID_ONLY_TO_DIE,
  1695. prefix, &oid, &oc);
  1696. }
  1697. enum get_oid_result get_oid_with_context(struct repository *repo,
  1698. const char *str,
  1699. unsigned flags,
  1700. struct object_id *oid,
  1701. struct object_context *oc)
  1702. {
  1703. if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
  1704. BUG("incompatible flags for get_sha1_with_context");
  1705. return get_oid_with_context_1(repo, str, flags, NULL, oid, oc);
  1706. }