refs.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. # refs.py -- For dealing with git refs
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Ref handling."""
  22. import os
  23. import warnings
  24. from collections.abc import Iterator
  25. from contextlib import suppress
  26. from typing import Any, Optional, Union
  27. from .errors import PackedRefsException, RefFormatError
  28. from .file import GitFile, ensure_dir_exists
  29. from .objects import ZERO_SHA, ObjectID, Tag, git_line, valid_hexsha
  30. from .pack import ObjectContainer
  31. Ref = bytes
  32. HEADREF = b"HEAD"
  33. SYMREF = b"ref: "
  34. LOCAL_BRANCH_PREFIX = b"refs/heads/"
  35. LOCAL_TAG_PREFIX = b"refs/tags/"
  36. LOCAL_REMOTE_PREFIX = b"refs/remotes/"
  37. BAD_REF_CHARS = set(b"\177 ~^:?*[")
  38. PEELED_TAG_SUFFIX = b"^{}"
  39. # For backwards compatibility
  40. ANNOTATED_TAG_SUFFIX = PEELED_TAG_SUFFIX
  41. class SymrefLoop(Exception):
  42. """There is a loop between one or more symrefs."""
  43. def __init__(self, ref, depth) -> None:
  44. self.ref = ref
  45. self.depth = depth
  46. def parse_symref_value(contents: bytes) -> bytes:
  47. """Parse a symref value.
  48. Args:
  49. contents: Contents to parse
  50. Returns: Destination
  51. """
  52. if contents.startswith(SYMREF):
  53. return contents[len(SYMREF) :].rstrip(b"\r\n")
  54. raise ValueError(contents)
  55. def check_ref_format(refname: Ref) -> bool:
  56. """Check if a refname is correctly formatted.
  57. Implements all the same rules as git-check-ref-format[1].
  58. [1]
  59. http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  60. Args:
  61. refname: The refname to check
  62. Returns: True if refname is valid, False otherwise
  63. """
  64. # These could be combined into one big expression, but are listed
  65. # separately to parallel [1].
  66. if b"/." in refname or refname.startswith(b"."):
  67. return False
  68. if b"/" not in refname:
  69. return False
  70. if b".." in refname:
  71. return False
  72. for i, c in enumerate(refname):
  73. if ord(refname[i : i + 1]) < 0o40 or c in BAD_REF_CHARS:
  74. return False
  75. if refname[-1] in b"/.":
  76. return False
  77. if refname.endswith(b".lock"):
  78. return False
  79. if b"@{" in refname:
  80. return False
  81. if b"\\" in refname:
  82. return False
  83. return True
  84. class RefsContainer:
  85. """A container for refs."""
  86. def __init__(self, logger=None) -> None:
  87. self._logger = logger
  88. def _log(
  89. self,
  90. ref,
  91. old_sha,
  92. new_sha,
  93. committer=None,
  94. timestamp=None,
  95. timezone=None,
  96. message=None,
  97. ) -> None:
  98. if self._logger is None:
  99. return
  100. if message is None:
  101. return
  102. self._logger(ref, old_sha, new_sha, committer, timestamp, timezone, message)
  103. def set_symbolic_ref(
  104. self,
  105. name,
  106. other,
  107. committer=None,
  108. timestamp=None,
  109. timezone=None,
  110. message=None,
  111. ) -> None:
  112. """Make a ref point at another ref.
  113. Args:
  114. name: Name of the ref to set
  115. other: Name of the ref to point at
  116. message: Optional message
  117. """
  118. raise NotImplementedError(self.set_symbolic_ref)
  119. def get_packed_refs(self) -> dict[Ref, ObjectID]:
  120. """Get contents of the packed-refs file.
  121. Returns: Dictionary mapping ref names to SHA1s
  122. Note: Will return an empty dictionary when no packed-refs file is
  123. present.
  124. """
  125. raise NotImplementedError(self.get_packed_refs)
  126. def add_packed_refs(self, new_refs: dict[Ref, Optional[ObjectID]]) -> None:
  127. """Add the given refs as packed refs.
  128. Args:
  129. new_refs: A mapping of ref names to targets; if a target is None that
  130. means remove the ref
  131. """
  132. raise NotImplementedError(self.add_packed_refs)
  133. def get_peeled(self, name) -> Optional[ObjectID]:
  134. """Return the cached peeled value of a ref, if available.
  135. Args:
  136. name: Name of the ref to peel
  137. Returns: The peeled value of the ref. If the ref is known not point to
  138. a tag, this will be the SHA the ref refers to. If the ref may point
  139. to a tag, but no cached information is available, None is returned.
  140. """
  141. return None
  142. def import_refs(
  143. self,
  144. base: Ref,
  145. other: dict[Ref, ObjectID],
  146. committer: Optional[bytes] = None,
  147. timestamp: Optional[bytes] = None,
  148. timezone: Optional[bytes] = None,
  149. message: Optional[bytes] = None,
  150. prune: bool = False,
  151. ) -> None:
  152. if prune:
  153. to_delete = set(self.subkeys(base))
  154. else:
  155. to_delete = set()
  156. for name, value in other.items():
  157. if value is None:
  158. to_delete.add(name)
  159. else:
  160. self.set_if_equals(
  161. b"/".join((base, name)), None, value, message=message
  162. )
  163. if to_delete:
  164. try:
  165. to_delete.remove(name)
  166. except KeyError:
  167. pass
  168. for ref in to_delete:
  169. self.remove_if_equals(b"/".join((base, ref)), None, message=message)
  170. def allkeys(self) -> Iterator[Ref]:
  171. """All refs present in this container."""
  172. raise NotImplementedError(self.allkeys)
  173. def __iter__(self):
  174. return iter(self.allkeys())
  175. def keys(self, base=None):
  176. """Refs present in this container.
  177. Args:
  178. base: An optional base to return refs under.
  179. Returns: An unsorted set of valid refs in this container, including
  180. packed refs.
  181. """
  182. if base is not None:
  183. return self.subkeys(base)
  184. else:
  185. return self.allkeys()
  186. def subkeys(self, base):
  187. """Refs present in this container under a base.
  188. Args:
  189. base: The base to return refs under.
  190. Returns: A set of valid refs in this container under the base; the base
  191. prefix is stripped from the ref names returned.
  192. """
  193. keys = set()
  194. base_len = len(base) + 1
  195. for refname in self.allkeys():
  196. if refname.startswith(base):
  197. keys.add(refname[base_len:])
  198. return keys
  199. def as_dict(self, base=None) -> dict[Ref, ObjectID]:
  200. """Return the contents of this container as a dictionary."""
  201. ret = {}
  202. keys = self.keys(base)
  203. if base is None:
  204. base = b""
  205. else:
  206. base = base.rstrip(b"/")
  207. for key in keys:
  208. try:
  209. ret[key] = self[(base + b"/" + key).strip(b"/")]
  210. except (SymrefLoop, KeyError):
  211. continue # Unable to resolve
  212. return ret
  213. def _check_refname(self, name) -> None:
  214. """Ensure a refname is valid and lives in refs or is HEAD.
  215. HEAD is not a valid refname according to git-check-ref-format, but this
  216. class needs to be able to touch HEAD. Also, check_ref_format expects
  217. refnames without the leading 'refs/', but this class requires that
  218. so it cannot touch anything outside the refs dir (or HEAD).
  219. Args:
  220. name: The name of the reference.
  221. Raises:
  222. KeyError: if a refname is not HEAD or is otherwise not valid.
  223. """
  224. if name in (HEADREF, b"refs/stash"):
  225. return
  226. if not name.startswith(b"refs/") or not check_ref_format(name[5:]):
  227. raise RefFormatError(name)
  228. def read_ref(self, refname):
  229. """Read a reference without following any references.
  230. Args:
  231. refname: The name of the reference
  232. Returns: The contents of the ref file, or None if it does
  233. not exist.
  234. """
  235. contents = self.read_loose_ref(refname)
  236. if not contents:
  237. contents = self.get_packed_refs().get(refname, None)
  238. return contents
  239. def read_loose_ref(self, name) -> bytes:
  240. """Read a loose reference and return its contents.
  241. Args:
  242. name: the refname to read
  243. Returns: The contents of the ref file, or None if it does
  244. not exist.
  245. """
  246. raise NotImplementedError(self.read_loose_ref)
  247. def follow(self, name) -> tuple[list[bytes], bytes]:
  248. """Follow a reference name.
  249. Returns: a tuple of (refnames, sha), wheres refnames are the names of
  250. references in the chain
  251. """
  252. contents = SYMREF + name
  253. depth = 0
  254. refnames = []
  255. while contents.startswith(SYMREF):
  256. refname = contents[len(SYMREF) :]
  257. refnames.append(refname)
  258. contents = self.read_ref(refname)
  259. if not contents:
  260. break
  261. depth += 1
  262. if depth > 5:
  263. raise SymrefLoop(name, depth)
  264. return refnames, contents
  265. def __contains__(self, refname) -> bool:
  266. if self.read_ref(refname):
  267. return True
  268. return False
  269. def __getitem__(self, name) -> ObjectID:
  270. """Get the SHA1 for a reference name.
  271. This method follows all symbolic references.
  272. """
  273. _, sha = self.follow(name)
  274. if sha is None:
  275. raise KeyError(name)
  276. return sha
  277. def set_if_equals(
  278. self,
  279. name,
  280. old_ref,
  281. new_ref,
  282. committer=None,
  283. timestamp=None,
  284. timezone=None,
  285. message=None,
  286. ) -> bool:
  287. """Set a refname to new_ref only if it currently equals old_ref.
  288. This method follows all symbolic references if applicable for the
  289. subclass, and can be used to perform an atomic compare-and-swap
  290. operation.
  291. Args:
  292. name: The refname to set.
  293. old_ref: The old sha the refname must refer to, or None to set
  294. unconditionally.
  295. new_ref: The new sha the refname will refer to.
  296. message: Message for reflog
  297. Returns: True if the set was successful, False otherwise.
  298. """
  299. raise NotImplementedError(self.set_if_equals)
  300. def add_if_new(
  301. self, name, ref, committer=None, timestamp=None, timezone=None, message=None
  302. ) -> bool:
  303. """Add a new reference only if it does not already exist.
  304. Args:
  305. name: Ref name
  306. ref: Ref value
  307. """
  308. raise NotImplementedError(self.add_if_new)
  309. def __setitem__(self, name, ref) -> None:
  310. """Set a reference name to point to the given SHA1.
  311. This method follows all symbolic references if applicable for the
  312. subclass.
  313. Note: This method unconditionally overwrites the contents of a
  314. reference. To update atomically only if the reference has not
  315. changed, use set_if_equals().
  316. Args:
  317. name: The refname to set.
  318. ref: The new sha the refname will refer to.
  319. """
  320. if not (valid_hexsha(ref) or ref.startswith(SYMREF)):
  321. raise ValueError(f"{ref!r} must be a valid sha (40 chars) or a symref")
  322. self.set_if_equals(name, None, ref)
  323. def remove_if_equals(
  324. self,
  325. name,
  326. old_ref,
  327. committer=None,
  328. timestamp=None,
  329. timezone=None,
  330. message=None,
  331. ) -> bool:
  332. """Remove a refname only if it currently equals old_ref.
  333. This method does not follow symbolic references, even if applicable for
  334. the subclass. It can be used to perform an atomic compare-and-delete
  335. operation.
  336. Args:
  337. name: The refname to delete.
  338. old_ref: The old sha the refname must refer to, or None to
  339. delete unconditionally.
  340. message: Message for reflog
  341. Returns: True if the delete was successful, False otherwise.
  342. """
  343. raise NotImplementedError(self.remove_if_equals)
  344. def __delitem__(self, name) -> None:
  345. """Remove a refname.
  346. This method does not follow symbolic references, even if applicable for
  347. the subclass.
  348. Note: This method unconditionally deletes the contents of a reference.
  349. To delete atomically only if the reference has not changed, use
  350. remove_if_equals().
  351. Args:
  352. name: The refname to delete.
  353. """
  354. self.remove_if_equals(name, None)
  355. def get_symrefs(self):
  356. """Get a dict with all symrefs in this container.
  357. Returns: Dictionary mapping source ref to target ref
  358. """
  359. ret = {}
  360. for src in self.allkeys():
  361. try:
  362. dst = parse_symref_value(self.read_ref(src))
  363. except ValueError:
  364. pass
  365. else:
  366. ret[src] = dst
  367. return ret
  368. class DictRefsContainer(RefsContainer):
  369. """RefsContainer backed by a simple dict.
  370. This container does not support symbolic or packed references and is not
  371. threadsafe.
  372. """
  373. def __init__(self, refs, logger=None) -> None:
  374. super().__init__(logger=logger)
  375. self._refs = refs
  376. self._peeled: dict[bytes, ObjectID] = {}
  377. self._watchers: set[Any] = set()
  378. def allkeys(self):
  379. return self._refs.keys()
  380. def read_loose_ref(self, name):
  381. return self._refs.get(name, None)
  382. def get_packed_refs(self):
  383. return {}
  384. def _notify(self, ref, newsha) -> None:
  385. for watcher in self._watchers:
  386. watcher._notify((ref, newsha))
  387. def set_symbolic_ref(
  388. self,
  389. name: Ref,
  390. other: Ref,
  391. committer=None,
  392. timestamp=None,
  393. timezone=None,
  394. message=None,
  395. ) -> None:
  396. old = self.follow(name)[-1]
  397. new = SYMREF + other
  398. self._refs[name] = new
  399. self._notify(name, new)
  400. self._log(
  401. name,
  402. old,
  403. new,
  404. committer=committer,
  405. timestamp=timestamp,
  406. timezone=timezone,
  407. message=message,
  408. )
  409. def set_if_equals(
  410. self,
  411. name,
  412. old_ref,
  413. new_ref,
  414. committer=None,
  415. timestamp=None,
  416. timezone=None,
  417. message=None,
  418. ) -> bool:
  419. if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref:
  420. return False
  421. realnames, _ = self.follow(name)
  422. for realname in realnames:
  423. self._check_refname(realname)
  424. old = self._refs.get(realname)
  425. self._refs[realname] = new_ref
  426. self._notify(realname, new_ref)
  427. self._log(
  428. realname,
  429. old,
  430. new_ref,
  431. committer=committer,
  432. timestamp=timestamp,
  433. timezone=timezone,
  434. message=message,
  435. )
  436. return True
  437. def add_if_new(
  438. self,
  439. name: Ref,
  440. ref: ObjectID,
  441. committer=None,
  442. timestamp=None,
  443. timezone=None,
  444. message: Optional[bytes] = None,
  445. ) -> bool:
  446. if name in self._refs:
  447. return False
  448. self._refs[name] = ref
  449. self._notify(name, ref)
  450. self._log(
  451. name,
  452. None,
  453. ref,
  454. committer=committer,
  455. timestamp=timestamp,
  456. timezone=timezone,
  457. message=message,
  458. )
  459. return True
  460. def remove_if_equals(
  461. self,
  462. name,
  463. old_ref,
  464. committer=None,
  465. timestamp=None,
  466. timezone=None,
  467. message=None,
  468. ) -> bool:
  469. if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref:
  470. return False
  471. try:
  472. old = self._refs.pop(name)
  473. except KeyError:
  474. pass
  475. else:
  476. self._notify(name, None)
  477. self._log(
  478. name,
  479. old,
  480. None,
  481. committer=committer,
  482. timestamp=timestamp,
  483. timezone=timezone,
  484. message=message,
  485. )
  486. return True
  487. def get_peeled(self, name):
  488. return self._peeled.get(name)
  489. def _update(self, refs) -> None:
  490. """Update multiple refs; intended only for testing."""
  491. # TODO(dborowitz): replace this with a public function that uses
  492. # set_if_equal.
  493. for ref, sha in refs.items():
  494. self.set_if_equals(ref, None, sha)
  495. def _update_peeled(self, peeled) -> None:
  496. """Update cached peeled refs; intended only for testing."""
  497. self._peeled.update(peeled)
  498. class InfoRefsContainer(RefsContainer):
  499. """Refs container that reads refs from a info/refs file."""
  500. def __init__(self, f) -> None:
  501. self._refs = {}
  502. self._peeled = {}
  503. refs = read_info_refs(f)
  504. (self._refs, self._peeled) = split_peeled_refs(refs)
  505. def allkeys(self):
  506. return self._refs.keys()
  507. def read_loose_ref(self, name):
  508. return self._refs.get(name, None)
  509. def get_packed_refs(self):
  510. return {}
  511. def get_peeled(self, name):
  512. try:
  513. return self._peeled[name]
  514. except KeyError:
  515. return self._refs[name]
  516. class DiskRefsContainer(RefsContainer):
  517. """Refs container that reads refs from disk."""
  518. def __init__(
  519. self,
  520. path: Union[str, bytes, os.PathLike],
  521. worktree_path: Optional[Union[str, bytes, os.PathLike]] = None,
  522. logger=None,
  523. ) -> None:
  524. super().__init__(logger=logger)
  525. # Convert path-like objects to strings, then to bytes for Git compatibility
  526. self.path = os.fsencode(os.fspath(path))
  527. if worktree_path is None:
  528. self.worktree_path = self.path
  529. else:
  530. self.worktree_path = os.fsencode(os.fspath(worktree_path))
  531. self._packed_refs = None
  532. self._peeled_refs = None
  533. def __repr__(self) -> str:
  534. return f"{self.__class__.__name__}({self.path!r})"
  535. def subkeys(self, base):
  536. subkeys = set()
  537. path = self.refpath(base)
  538. for root, unused_dirs, files in os.walk(path):
  539. dir = root[len(path) :]
  540. if os.path.sep != "/":
  541. dir = dir.replace(os.fsencode(os.path.sep), b"/")
  542. dir = dir.strip(b"/")
  543. for filename in files:
  544. refname = b"/".join(([dir] if dir else []) + [filename])
  545. # check_ref_format requires at least one /, so we prepend the
  546. # base before calling it.
  547. if check_ref_format(base + b"/" + refname):
  548. subkeys.add(refname)
  549. for key in self.get_packed_refs():
  550. if key.startswith(base):
  551. subkeys.add(key[len(base) :].strip(b"/"))
  552. return subkeys
  553. def allkeys(self):
  554. allkeys = set()
  555. if os.path.exists(self.refpath(HEADREF)):
  556. allkeys.add(HEADREF)
  557. path = self.refpath(b"")
  558. refspath = self.refpath(b"refs")
  559. for root, unused_dirs, files in os.walk(refspath):
  560. dir = root[len(path) :]
  561. if os.path.sep != "/":
  562. dir = dir.replace(os.fsencode(os.path.sep), b"/")
  563. for filename in files:
  564. refname = b"/".join([dir, filename])
  565. if check_ref_format(refname):
  566. allkeys.add(refname)
  567. allkeys.update(self.get_packed_refs())
  568. return allkeys
  569. def refpath(self, name):
  570. """Return the disk path of a ref."""
  571. if os.path.sep != "/":
  572. name = name.replace(b"/", os.fsencode(os.path.sep))
  573. # TODO: as the 'HEAD' reference is working tree specific, it
  574. # should actually not be a part of RefsContainer
  575. if name == HEADREF:
  576. return os.path.join(self.worktree_path, name)
  577. else:
  578. return os.path.join(self.path, name)
  579. def get_packed_refs(self):
  580. """Get contents of the packed-refs file.
  581. Returns: Dictionary mapping ref names to SHA1s
  582. Note: Will return an empty dictionary when no packed-refs file is
  583. present.
  584. """
  585. # TODO: invalidate the cache on repacking
  586. if self._packed_refs is None:
  587. # set both to empty because we want _peeled_refs to be
  588. # None if and only if _packed_refs is also None.
  589. self._packed_refs = {}
  590. self._peeled_refs = {}
  591. path = os.path.join(self.path, b"packed-refs")
  592. try:
  593. f = GitFile(path, "rb")
  594. except FileNotFoundError:
  595. return {}
  596. with f:
  597. first_line = next(iter(f)).rstrip()
  598. if first_line.startswith(b"# pack-refs") and b" peeled" in first_line:
  599. for sha, name, peeled in read_packed_refs_with_peeled(f):
  600. self._packed_refs[name] = sha
  601. if peeled:
  602. self._peeled_refs[name] = peeled
  603. else:
  604. f.seek(0)
  605. for sha, name in read_packed_refs(f):
  606. self._packed_refs[name] = sha
  607. return self._packed_refs
  608. def add_packed_refs(self, new_refs: dict[Ref, Optional[ObjectID]]) -> None:
  609. """Add the given refs as packed refs.
  610. Args:
  611. new_refs: A mapping of ref names to targets; if a target is None that
  612. means remove the ref
  613. """
  614. if not new_refs:
  615. return
  616. path = os.path.join(self.path, b"packed-refs")
  617. with GitFile(path, "wb") as f:
  618. # reread cached refs from disk, while holding the lock
  619. packed_refs = self.get_packed_refs().copy()
  620. for ref, target in new_refs.items():
  621. # sanity check
  622. if ref == HEADREF:
  623. raise ValueError("cannot pack HEAD")
  624. # remove any loose refs pointing to this one -- please
  625. # note that this bypasses remove_if_equals as we don't
  626. # want to affect packed refs in here
  627. with suppress(OSError):
  628. os.remove(self.refpath(ref))
  629. if target is not None:
  630. packed_refs[ref] = target
  631. else:
  632. packed_refs.pop(ref, None)
  633. write_packed_refs(f, packed_refs, self._peeled_refs)
  634. self._packed_refs = packed_refs
  635. def get_peeled(self, name):
  636. """Return the cached peeled value of a ref, if available.
  637. Args:
  638. name: Name of the ref to peel
  639. Returns: The peeled value of the ref. If the ref is known not point to
  640. a tag, this will be the SHA the ref refers to. If the ref may point
  641. to a tag, but no cached information is available, None is returned.
  642. """
  643. self.get_packed_refs()
  644. if self._peeled_refs is None or name not in self._packed_refs:
  645. # No cache: no peeled refs were read, or this ref is loose
  646. return None
  647. if name in self._peeled_refs:
  648. return self._peeled_refs[name]
  649. else:
  650. # Known not peelable
  651. return self[name]
  652. def read_loose_ref(self, name):
  653. """Read a reference file and return its contents.
  654. If the reference file a symbolic reference, only read the first line of
  655. the file. Otherwise, only read the first 40 bytes.
  656. Args:
  657. name: the refname to read, relative to refpath
  658. Returns: The contents of the ref file, or None if the file does not
  659. exist.
  660. Raises:
  661. IOError: if any other error occurs
  662. """
  663. filename = self.refpath(name)
  664. try:
  665. with GitFile(filename, "rb") as f:
  666. header = f.read(len(SYMREF))
  667. if header == SYMREF:
  668. # Read only the first line
  669. return header + next(iter(f)).rstrip(b"\r\n")
  670. else:
  671. # Read only the first 40 bytes
  672. return header + f.read(40 - len(SYMREF))
  673. except (OSError, UnicodeError):
  674. # don't assume anything specific about the error; in
  675. # particular, invalid or forbidden paths can raise weird
  676. # errors depending on the specific operating system
  677. return None
  678. def _remove_packed_ref(self, name) -> None:
  679. if self._packed_refs is None:
  680. return
  681. filename = os.path.join(self.path, b"packed-refs")
  682. # reread cached refs from disk, while holding the lock
  683. f = GitFile(filename, "wb")
  684. try:
  685. self._packed_refs = None
  686. self.get_packed_refs()
  687. if name not in self._packed_refs:
  688. return
  689. del self._packed_refs[name]
  690. with suppress(KeyError):
  691. del self._peeled_refs[name]
  692. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  693. f.close()
  694. finally:
  695. f.abort()
  696. def set_symbolic_ref(
  697. self,
  698. name,
  699. other,
  700. committer=None,
  701. timestamp=None,
  702. timezone=None,
  703. message=None,
  704. ) -> None:
  705. """Make a ref point at another ref.
  706. Args:
  707. name: Name of the ref to set
  708. other: Name of the ref to point at
  709. message: Optional message to describe the change
  710. """
  711. self._check_refname(name)
  712. self._check_refname(other)
  713. filename = self.refpath(name)
  714. f = GitFile(filename, "wb")
  715. try:
  716. f.write(SYMREF + other + b"\n")
  717. sha = self.follow(name)[-1]
  718. self._log(
  719. name,
  720. sha,
  721. sha,
  722. committer=committer,
  723. timestamp=timestamp,
  724. timezone=timezone,
  725. message=message,
  726. )
  727. except BaseException:
  728. f.abort()
  729. raise
  730. else:
  731. f.close()
  732. def set_if_equals(
  733. self,
  734. name,
  735. old_ref,
  736. new_ref,
  737. committer=None,
  738. timestamp=None,
  739. timezone=None,
  740. message=None,
  741. ) -> bool:
  742. """Set a refname to new_ref only if it currently equals old_ref.
  743. This method follows all symbolic references, and can be used to perform
  744. an atomic compare-and-swap operation.
  745. Args:
  746. name: The refname to set.
  747. old_ref: The old sha the refname must refer to, or None to set
  748. unconditionally.
  749. new_ref: The new sha the refname will refer to.
  750. message: Set message for reflog
  751. Returns: True if the set was successful, False otherwise.
  752. """
  753. self._check_refname(name)
  754. try:
  755. realnames, _ = self.follow(name)
  756. realname = realnames[-1]
  757. except (KeyError, IndexError, SymrefLoop):
  758. realname = name
  759. filename = self.refpath(realname)
  760. # make sure none of the ancestor folders is in packed refs
  761. probe_ref = os.path.dirname(realname)
  762. packed_refs = self.get_packed_refs()
  763. while probe_ref:
  764. if packed_refs.get(probe_ref, None) is not None:
  765. raise NotADirectoryError(filename)
  766. probe_ref = os.path.dirname(probe_ref)
  767. ensure_dir_exists(os.path.dirname(filename))
  768. with GitFile(filename, "wb") as f:
  769. if old_ref is not None:
  770. try:
  771. # read again while holding the lock
  772. orig_ref = self.read_loose_ref(realname)
  773. if orig_ref is None:
  774. orig_ref = self.get_packed_refs().get(realname, ZERO_SHA)
  775. if orig_ref != old_ref:
  776. f.abort()
  777. return False
  778. except OSError:
  779. f.abort()
  780. raise
  781. try:
  782. f.write(new_ref + b"\n")
  783. except OSError:
  784. f.abort()
  785. raise
  786. self._log(
  787. realname,
  788. old_ref,
  789. new_ref,
  790. committer=committer,
  791. timestamp=timestamp,
  792. timezone=timezone,
  793. message=message,
  794. )
  795. return True
  796. def add_if_new(
  797. self,
  798. name: bytes,
  799. ref: bytes,
  800. committer=None,
  801. timestamp=None,
  802. timezone=None,
  803. message: Optional[bytes] = None,
  804. ) -> bool:
  805. """Add a new reference only if it does not already exist.
  806. This method follows symrefs, and only ensures that the last ref in the
  807. chain does not exist.
  808. Args:
  809. name: The refname to set.
  810. ref: The new sha the refname will refer to.
  811. message: Optional message for reflog
  812. Returns: True if the add was successful, False otherwise.
  813. """
  814. try:
  815. realnames, contents = self.follow(name)
  816. if contents is not None:
  817. return False
  818. realname = realnames[-1]
  819. except (KeyError, IndexError):
  820. realname = name
  821. self._check_refname(realname)
  822. filename = self.refpath(realname)
  823. ensure_dir_exists(os.path.dirname(filename))
  824. with GitFile(filename, "wb") as f:
  825. if os.path.exists(filename) or name in self.get_packed_refs():
  826. f.abort()
  827. return False
  828. try:
  829. f.write(ref + b"\n")
  830. except OSError:
  831. f.abort()
  832. raise
  833. else:
  834. self._log(
  835. name,
  836. None,
  837. ref,
  838. committer=committer,
  839. timestamp=timestamp,
  840. timezone=timezone,
  841. message=message,
  842. )
  843. return True
  844. def remove_if_equals(
  845. self,
  846. name,
  847. old_ref,
  848. committer=None,
  849. timestamp=None,
  850. timezone=None,
  851. message=None,
  852. ) -> bool:
  853. """Remove a refname only if it currently equals old_ref.
  854. This method does not follow symbolic references. It can be used to
  855. perform an atomic compare-and-delete operation.
  856. Args:
  857. name: The refname to delete.
  858. old_ref: The old sha the refname must refer to, or None to
  859. delete unconditionally.
  860. message: Optional message
  861. Returns: True if the delete was successful, False otherwise.
  862. """
  863. self._check_refname(name)
  864. filename = self.refpath(name)
  865. ensure_dir_exists(os.path.dirname(filename))
  866. f = GitFile(filename, "wb")
  867. try:
  868. if old_ref is not None:
  869. orig_ref = self.read_loose_ref(name)
  870. if orig_ref is None:
  871. orig_ref = self.get_packed_refs().get(name, ZERO_SHA)
  872. if orig_ref != old_ref:
  873. return False
  874. # remove the reference file itself
  875. try:
  876. found = os.path.lexists(filename)
  877. except OSError:
  878. # may only be packed, or otherwise unstorable
  879. found = False
  880. if found:
  881. os.remove(filename)
  882. self._remove_packed_ref(name)
  883. self._log(
  884. name,
  885. old_ref,
  886. None,
  887. committer=committer,
  888. timestamp=timestamp,
  889. timezone=timezone,
  890. message=message,
  891. )
  892. finally:
  893. # never write, we just wanted the lock
  894. f.abort()
  895. # outside of the lock, clean-up any parent directory that might now
  896. # be empty. this ensures that re-creating a reference of the same
  897. # name of what was previously a directory works as expected
  898. parent = name
  899. while True:
  900. try:
  901. parent, _ = parent.rsplit(b"/", 1)
  902. except ValueError:
  903. break
  904. if parent == b"refs":
  905. break
  906. parent_filename = self.refpath(parent)
  907. try:
  908. os.rmdir(parent_filename)
  909. except OSError:
  910. # this can be caused by the parent directory being
  911. # removed by another process, being not empty, etc.
  912. # in any case, this is non fatal because we already
  913. # removed the reference, just ignore it
  914. break
  915. return True
  916. def _split_ref_line(line):
  917. """Split a single ref line into a tuple of SHA1 and name."""
  918. fields = line.rstrip(b"\n\r").split(b" ")
  919. if len(fields) != 2:
  920. raise PackedRefsException(f"invalid ref line {line!r}")
  921. sha, name = fields
  922. if not valid_hexsha(sha):
  923. raise PackedRefsException(f"Invalid hex sha {sha!r}")
  924. if not check_ref_format(name):
  925. raise PackedRefsException(f"invalid ref name {name!r}")
  926. return (sha, name)
  927. def read_packed_refs(f):
  928. """Read a packed refs file.
  929. Args:
  930. f: file-like object to read from
  931. Returns: Iterator over tuples with SHA1s and ref names.
  932. """
  933. for line in f:
  934. if line.startswith(b"#"):
  935. # Comment
  936. continue
  937. if line.startswith(b"^"):
  938. raise PackedRefsException("found peeled ref in packed-refs without peeled")
  939. yield _split_ref_line(line)
  940. def read_packed_refs_with_peeled(f):
  941. """Read a packed refs file including peeled refs.
  942. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  943. with ref names, SHA1s, and peeled SHA1s (or None).
  944. Args:
  945. f: file-like object to read from, seek'ed to the second line
  946. """
  947. last = None
  948. for line in f:
  949. if line[0] == b"#":
  950. continue
  951. line = line.rstrip(b"\r\n")
  952. if line.startswith(b"^"):
  953. if not last:
  954. raise PackedRefsException("unexpected peeled ref line")
  955. if not valid_hexsha(line[1:]):
  956. raise PackedRefsException(f"Invalid hex sha {line[1:]!r}")
  957. sha, name = _split_ref_line(last)
  958. last = None
  959. yield (sha, name, line[1:])
  960. else:
  961. if last:
  962. sha, name = _split_ref_line(last)
  963. yield (sha, name, None)
  964. last = line
  965. if last:
  966. sha, name = _split_ref_line(last)
  967. yield (sha, name, None)
  968. def write_packed_refs(f, packed_refs, peeled_refs=None) -> None:
  969. """Write a packed refs file.
  970. Args:
  971. f: empty file-like object to write to
  972. packed_refs: dict of refname to sha of packed refs to write
  973. peeled_refs: dict of refname to peeled value of sha
  974. """
  975. if peeled_refs is None:
  976. peeled_refs = {}
  977. else:
  978. f.write(b"# pack-refs with: peeled\n")
  979. for refname in sorted(packed_refs.keys()):
  980. f.write(git_line(packed_refs[refname], refname))
  981. if refname in peeled_refs:
  982. f.write(b"^" + peeled_refs[refname] + b"\n")
  983. def read_info_refs(f):
  984. ret = {}
  985. for line in f.readlines():
  986. (sha, name) = line.rstrip(b"\r\n").split(b"\t", 1)
  987. ret[name] = sha
  988. return ret
  989. def write_info_refs(refs, store: ObjectContainer):
  990. """Generate info refs."""
  991. # TODO: Avoid recursive import :(
  992. from .object_store import peel_sha
  993. for name, sha in sorted(refs.items()):
  994. # get_refs() includes HEAD as a special case, but we don't want to
  995. # advertise it
  996. if name == HEADREF:
  997. continue
  998. try:
  999. o = store[sha]
  1000. except KeyError:
  1001. continue
  1002. unpeeled, peeled = peel_sha(store, sha)
  1003. yield o.id + b"\t" + name + b"\n"
  1004. if o.id != peeled.id:
  1005. yield peeled.id + b"\t" + name + PEELED_TAG_SUFFIX + b"\n"
  1006. def is_local_branch(x):
  1007. return x.startswith(LOCAL_BRANCH_PREFIX)
  1008. def strip_peeled_refs(refs):
  1009. """Remove all peeled refs."""
  1010. return {
  1011. ref: sha for (ref, sha) in refs.items() if not ref.endswith(PEELED_TAG_SUFFIX)
  1012. }
  1013. def split_peeled_refs(refs):
  1014. """Split peeled refs from regular refs."""
  1015. peeled = {}
  1016. regular = {}
  1017. for ref, sha in refs.items():
  1018. if ref.endswith(PEELED_TAG_SUFFIX):
  1019. peeled[ref[: -len(PEELED_TAG_SUFFIX)]] = sha
  1020. else:
  1021. regular[ref] = sha
  1022. return regular, peeled
  1023. def _set_origin_head(refs, origin, origin_head) -> None:
  1024. # set refs/remotes/origin/HEAD
  1025. origin_base = b"refs/remotes/" + origin + b"/"
  1026. if origin_head and origin_head.startswith(LOCAL_BRANCH_PREFIX):
  1027. origin_ref = origin_base + HEADREF
  1028. target_ref = origin_base + origin_head[len(LOCAL_BRANCH_PREFIX) :]
  1029. if target_ref in refs:
  1030. refs.set_symbolic_ref(origin_ref, target_ref)
  1031. def _set_default_branch(
  1032. refs: RefsContainer,
  1033. origin: bytes,
  1034. origin_head: Optional[bytes],
  1035. branch: bytes,
  1036. ref_message: Optional[bytes],
  1037. ) -> bytes:
  1038. """Set the default branch."""
  1039. origin_base = b"refs/remotes/" + origin + b"/"
  1040. if branch:
  1041. origin_ref = origin_base + branch
  1042. if origin_ref in refs:
  1043. local_ref = LOCAL_BRANCH_PREFIX + branch
  1044. refs.add_if_new(local_ref, refs[origin_ref], ref_message)
  1045. head_ref = local_ref
  1046. elif LOCAL_TAG_PREFIX + branch in refs:
  1047. head_ref = LOCAL_TAG_PREFIX + branch
  1048. else:
  1049. raise ValueError(f"{os.fsencode(branch)!r} is not a valid branch or tag")
  1050. elif origin_head:
  1051. head_ref = origin_head
  1052. if origin_head.startswith(LOCAL_BRANCH_PREFIX):
  1053. origin_ref = origin_base + origin_head[len(LOCAL_BRANCH_PREFIX) :]
  1054. else:
  1055. origin_ref = origin_head
  1056. try:
  1057. refs.add_if_new(head_ref, refs[origin_ref], ref_message)
  1058. except KeyError:
  1059. pass
  1060. else:
  1061. raise ValueError("neither origin_head nor branch are provided")
  1062. return head_ref
  1063. def _set_head(refs, head_ref, ref_message):
  1064. if head_ref.startswith(LOCAL_TAG_PREFIX):
  1065. # detach HEAD at specified tag
  1066. head = refs[head_ref]
  1067. if isinstance(head, Tag):
  1068. _cls, obj = head.object
  1069. head = obj.get_object(obj).id
  1070. del refs[HEADREF]
  1071. refs.set_if_equals(HEADREF, None, head, message=ref_message)
  1072. else:
  1073. # set HEAD to specific branch
  1074. try:
  1075. head = refs[head_ref]
  1076. refs.set_symbolic_ref(HEADREF, head_ref)
  1077. refs.set_if_equals(HEADREF, None, head, message=ref_message)
  1078. except KeyError:
  1079. head = None
  1080. return head
  1081. def _import_remote_refs(
  1082. refs_container: RefsContainer,
  1083. remote_name: str,
  1084. refs: dict[str, str],
  1085. message: Optional[bytes] = None,
  1086. prune: bool = False,
  1087. prune_tags: bool = False,
  1088. ) -> None:
  1089. stripped_refs = strip_peeled_refs(refs)
  1090. branches = {
  1091. n[len(LOCAL_BRANCH_PREFIX) :]: v
  1092. for (n, v) in stripped_refs.items()
  1093. if n.startswith(LOCAL_BRANCH_PREFIX)
  1094. }
  1095. refs_container.import_refs(
  1096. b"refs/remotes/" + remote_name.encode(),
  1097. branches,
  1098. message=message,
  1099. prune=prune,
  1100. )
  1101. tags = {
  1102. n[len(LOCAL_TAG_PREFIX) :]: v
  1103. for (n, v) in stripped_refs.items()
  1104. if n.startswith(LOCAL_TAG_PREFIX) and not n.endswith(PEELED_TAG_SUFFIX)
  1105. }
  1106. refs_container.import_refs(
  1107. LOCAL_TAG_PREFIX, tags, message=message, prune=prune_tags
  1108. )
  1109. def serialize_refs(store, refs):
  1110. # TODO: Avoid recursive import :(
  1111. from .object_store import peel_sha
  1112. ret = {}
  1113. for ref, sha in refs.items():
  1114. try:
  1115. unpeeled, peeled = peel_sha(store, sha)
  1116. except KeyError:
  1117. warnings.warn(
  1118. "ref {} points at non-present sha {}".format(
  1119. ref.decode("utf-8", "replace"), sha.decode("ascii")
  1120. ),
  1121. UserWarning,
  1122. )
  1123. continue
  1124. else:
  1125. if isinstance(unpeeled, Tag):
  1126. ret[ref + PEELED_TAG_SUFFIX] = peeled.id
  1127. ret[ref] = unpeeled.id
  1128. return ret