refs.py 41 KB

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