refs.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066
  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 published 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 types
  24. import warnings
  25. from collections.abc import Iterable, Iterator, Mapping
  26. from contextlib import suppress
  27. from typing import (
  28. IO,
  29. TYPE_CHECKING,
  30. Any,
  31. BinaryIO,
  32. Callable,
  33. Optional,
  34. TypeVar,
  35. Union,
  36. )
  37. if TYPE_CHECKING:
  38. from .file import _GitFile
  39. from .errors import PackedRefsException, RefFormatError
  40. from .file import GitFile, ensure_dir_exists
  41. from .objects import ZERO_SHA, ObjectID, Tag, git_line, valid_hexsha
  42. from .pack import ObjectContainer
  43. Ref = bytes
  44. HEADREF = b"HEAD"
  45. SYMREF = b"ref: "
  46. LOCAL_BRANCH_PREFIX = b"refs/heads/"
  47. LOCAL_TAG_PREFIX = b"refs/tags/"
  48. LOCAL_REMOTE_PREFIX = b"refs/remotes/"
  49. LOCAL_NOTES_PREFIX = b"refs/notes/"
  50. BAD_REF_CHARS = set(b"\177 ~^:?*[")
  51. PEELED_TAG_SUFFIX = b"^{}"
  52. # For backwards compatibility
  53. ANNOTATED_TAG_SUFFIX = PEELED_TAG_SUFFIX
  54. class SymrefLoop(Exception):
  55. """There is a loop between one or more symrefs."""
  56. def __init__(self, ref: bytes, depth: int) -> None:
  57. """Initialize SymrefLoop exception."""
  58. self.ref = ref
  59. self.depth = depth
  60. def parse_symref_value(contents: bytes) -> bytes:
  61. """Parse a symref value.
  62. Args:
  63. contents: Contents to parse
  64. Returns: Destination
  65. """
  66. if contents.startswith(SYMREF):
  67. return contents[len(SYMREF) :].rstrip(b"\r\n")
  68. raise ValueError(contents)
  69. def check_ref_format(refname: Ref) -> bool:
  70. """Check if a refname is correctly formatted.
  71. Implements all the same rules as git-check-ref-format[1].
  72. [1]
  73. http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  74. Args:
  75. refname: The refname to check
  76. Returns: True if refname is valid, False otherwise
  77. """
  78. # These could be combined into one big expression, but are listed
  79. # separately to parallel [1].
  80. if b"/." in refname or refname.startswith(b"."):
  81. return False
  82. if b"/" not in refname:
  83. return False
  84. if b".." in refname:
  85. return False
  86. for i, c in enumerate(refname):
  87. if ord(refname[i : i + 1]) < 0o40 or c in BAD_REF_CHARS:
  88. return False
  89. if refname[-1] in b"/.":
  90. return False
  91. if refname.endswith(b".lock"):
  92. return False
  93. if b"@{" in refname:
  94. return False
  95. if b"\\" in refname:
  96. return False
  97. return True
  98. def parse_remote_ref(ref: bytes) -> tuple[bytes, bytes]:
  99. """Parse a remote ref into remote name and branch name.
  100. Args:
  101. ref: Remote ref like b"refs/remotes/origin/main"
  102. Returns:
  103. Tuple of (remote_name, branch_name)
  104. Raises:
  105. ValueError: If ref is not a valid remote ref
  106. """
  107. if not ref.startswith(LOCAL_REMOTE_PREFIX):
  108. raise ValueError(f"Not a remote ref: {ref!r}")
  109. # Remove the prefix
  110. remainder = ref[len(LOCAL_REMOTE_PREFIX) :]
  111. # Split into remote name and branch name
  112. parts = remainder.split(b"/", 1)
  113. if len(parts) != 2:
  114. raise ValueError(f"Invalid remote ref format: {ref!r}")
  115. remote_name, branch_name = parts
  116. return (remote_name, branch_name)
  117. class RefsContainer:
  118. """A container for refs."""
  119. def __init__(
  120. self,
  121. logger: Optional[
  122. Callable[
  123. [
  124. bytes,
  125. bytes,
  126. bytes,
  127. Optional[bytes],
  128. Optional[int],
  129. Optional[int],
  130. bytes,
  131. ],
  132. None,
  133. ]
  134. ] = None,
  135. ) -> None:
  136. """Initialize RefsContainer with optional logger function."""
  137. self._logger = logger
  138. def _log(
  139. self,
  140. ref: bytes,
  141. old_sha: Optional[bytes],
  142. new_sha: Optional[bytes],
  143. committer: Optional[bytes] = None,
  144. timestamp: Optional[int] = None,
  145. timezone: Optional[int] = None,
  146. message: Optional[bytes] = None,
  147. ) -> None:
  148. if self._logger is None:
  149. return
  150. if message is None:
  151. return
  152. # Use ZERO_SHA for None values, matching git behavior
  153. if old_sha is None:
  154. old_sha = ZERO_SHA
  155. if new_sha is None:
  156. new_sha = ZERO_SHA
  157. self._logger(ref, old_sha, new_sha, committer, timestamp, timezone, message)
  158. def set_symbolic_ref(
  159. self,
  160. name: bytes,
  161. other: bytes,
  162. committer: Optional[bytes] = None,
  163. timestamp: Optional[int] = None,
  164. timezone: Optional[int] = None,
  165. message: Optional[bytes] = None,
  166. ) -> None:
  167. """Make a ref point at another ref.
  168. Args:
  169. name: Name of the ref to set
  170. other: Name of the ref to point at
  171. committer: Optional committer name/email
  172. timestamp: Optional timestamp
  173. timezone: Optional timezone
  174. message: Optional message
  175. """
  176. raise NotImplementedError(self.set_symbolic_ref)
  177. def get_packed_refs(self) -> dict[Ref, ObjectID]:
  178. """Get contents of the packed-refs file.
  179. Returns: Dictionary mapping ref names to SHA1s
  180. Note: Will return an empty dictionary when no packed-refs file is
  181. present.
  182. """
  183. raise NotImplementedError(self.get_packed_refs)
  184. def add_packed_refs(self, new_refs: Mapping[Ref, Optional[ObjectID]]) -> None:
  185. """Add the given refs as packed refs.
  186. Args:
  187. new_refs: A mapping of ref names to targets; if a target is None that
  188. means remove the ref
  189. """
  190. raise NotImplementedError(self.add_packed_refs)
  191. def get_peeled(self, name: bytes) -> Optional[ObjectID]:
  192. """Return the cached peeled value of a ref, if available.
  193. Args:
  194. name: Name of the ref to peel
  195. Returns: The peeled value of the ref. If the ref is known not point to
  196. a tag, this will be the SHA the ref refers to. If the ref may point
  197. to a tag, but no cached information is available, None is returned.
  198. """
  199. return None
  200. def import_refs(
  201. self,
  202. base: Ref,
  203. other: Mapping[Ref, ObjectID],
  204. committer: Optional[bytes] = None,
  205. timestamp: Optional[bytes] = None,
  206. timezone: Optional[bytes] = None,
  207. message: Optional[bytes] = None,
  208. prune: bool = False,
  209. ) -> None:
  210. """Import refs from another repository.
  211. Args:
  212. base: Base ref to import into (e.g., b'refs/remotes/origin')
  213. other: Dictionary of refs to import
  214. committer: Optional committer for reflog
  215. timestamp: Optional timestamp for reflog
  216. timezone: Optional timezone for reflog
  217. message: Optional message for reflog
  218. prune: If True, remove refs not in other
  219. """
  220. if prune:
  221. to_delete = set(self.subkeys(base))
  222. else:
  223. to_delete = set()
  224. for name, value in other.items():
  225. if value is None:
  226. to_delete.add(name)
  227. else:
  228. self.set_if_equals(
  229. b"/".join((base, name)), None, value, message=message
  230. )
  231. if to_delete:
  232. try:
  233. to_delete.remove(name)
  234. except KeyError:
  235. pass
  236. for ref in to_delete:
  237. self.remove_if_equals(b"/".join((base, ref)), None, message=message)
  238. def allkeys(self) -> set[Ref]:
  239. """All refs present in this container."""
  240. raise NotImplementedError(self.allkeys)
  241. def __iter__(self) -> Iterator[Ref]:
  242. """Iterate over all reference keys."""
  243. return iter(self.allkeys())
  244. def keys(self, base: Optional[bytes] = None) -> set[bytes]:
  245. """Refs present in this container.
  246. Args:
  247. base: An optional base to return refs under.
  248. Returns: An unsorted set of valid refs in this container, including
  249. packed refs.
  250. """
  251. if base is not None:
  252. return self.subkeys(base)
  253. else:
  254. return self.allkeys()
  255. def subkeys(self, base: bytes) -> set[bytes]:
  256. """Refs present in this container under a base.
  257. Args:
  258. base: The base to return refs under.
  259. Returns: A set of valid refs in this container under the base; the base
  260. prefix is stripped from the ref names returned.
  261. """
  262. keys = set()
  263. base_len = len(base) + 1
  264. for refname in self.allkeys():
  265. if refname.startswith(base):
  266. keys.add(refname[base_len:])
  267. return keys
  268. def as_dict(self, base: Optional[bytes] = None) -> dict[Ref, ObjectID]:
  269. """Return the contents of this container as a dictionary."""
  270. ret = {}
  271. keys = self.keys(base)
  272. if base is None:
  273. base = b""
  274. else:
  275. base = base.rstrip(b"/")
  276. for key in keys:
  277. try:
  278. ret[key] = self[(base + b"/" + key).strip(b"/")]
  279. except (SymrefLoop, KeyError):
  280. continue # Unable to resolve
  281. return ret
  282. def _check_refname(self, name: bytes) -> None:
  283. """Ensure a refname is valid and lives in refs or is HEAD.
  284. HEAD is not a valid refname according to git-check-ref-format, but this
  285. class needs to be able to touch HEAD. Also, check_ref_format expects
  286. refnames without the leading 'refs/', but this class requires that
  287. so it cannot touch anything outside the refs dir (or HEAD).
  288. Args:
  289. name: The name of the reference.
  290. Raises:
  291. KeyError: if a refname is not HEAD or is otherwise not valid.
  292. """
  293. if name in (HEADREF, b"refs/stash"):
  294. return
  295. if not name.startswith(b"refs/") or not check_ref_format(name[5:]):
  296. raise RefFormatError(name)
  297. def read_ref(self, refname: bytes) -> Optional[bytes]:
  298. """Read a reference without following any references.
  299. Args:
  300. refname: The name of the reference
  301. Returns: The contents of the ref file, or None if it does
  302. not exist.
  303. """
  304. contents = self.read_loose_ref(refname)
  305. if not contents:
  306. contents = self.get_packed_refs().get(refname, None)
  307. return contents
  308. def read_loose_ref(self, name: bytes) -> Optional[bytes]:
  309. """Read a loose reference and return its contents.
  310. Args:
  311. name: the refname to read
  312. Returns: The contents of the ref file, or None if it does
  313. not exist.
  314. """
  315. raise NotImplementedError(self.read_loose_ref)
  316. def follow(self, name: bytes) -> tuple[list[bytes], Optional[bytes]]:
  317. """Follow a reference name.
  318. Returns: a tuple of (refnames, sha), wheres refnames are the names of
  319. references in the chain
  320. """
  321. contents: Optional[bytes] = SYMREF + name
  322. depth = 0
  323. refnames = []
  324. while contents and contents.startswith(SYMREF):
  325. refname = contents[len(SYMREF) :]
  326. refnames.append(refname)
  327. contents = self.read_ref(refname)
  328. if not contents:
  329. break
  330. depth += 1
  331. if depth > 5:
  332. raise SymrefLoop(name, depth)
  333. return refnames, contents
  334. def __contains__(self, refname: bytes) -> bool:
  335. """Check if a reference exists."""
  336. if self.read_ref(refname):
  337. return True
  338. return False
  339. def __getitem__(self, name: bytes) -> ObjectID:
  340. """Get the SHA1 for a reference name.
  341. This method follows all symbolic references.
  342. """
  343. _, sha = self.follow(name)
  344. if sha is None:
  345. raise KeyError(name)
  346. return sha
  347. def set_if_equals(
  348. self,
  349. name: bytes,
  350. old_ref: Optional[bytes],
  351. new_ref: bytes,
  352. committer: Optional[bytes] = None,
  353. timestamp: Optional[int] = None,
  354. timezone: Optional[int] = None,
  355. message: Optional[bytes] = None,
  356. ) -> bool:
  357. """Set a refname to new_ref only if it currently equals old_ref.
  358. This method follows all symbolic references if applicable for the
  359. subclass, and can be used to perform an atomic compare-and-swap
  360. operation.
  361. Args:
  362. name: The refname to set.
  363. old_ref: The old sha the refname must refer to, or None to set
  364. unconditionally.
  365. new_ref: The new sha the refname will refer to.
  366. committer: Optional committer name/email
  367. timestamp: Optional timestamp
  368. timezone: Optional timezone
  369. message: Message for reflog
  370. Returns: True if the set was successful, False otherwise.
  371. """
  372. raise NotImplementedError(self.set_if_equals)
  373. def add_if_new(
  374. self,
  375. name: bytes,
  376. ref: bytes,
  377. committer: Optional[bytes] = None,
  378. timestamp: Optional[int] = None,
  379. timezone: Optional[int] = None,
  380. message: Optional[bytes] = None,
  381. ) -> bool:
  382. """Add a new reference only if it does not already exist.
  383. Args:
  384. name: Ref name
  385. ref: Ref value
  386. committer: Optional committer name/email
  387. timestamp: Optional timestamp
  388. timezone: Optional timezone
  389. message: Optional message for reflog
  390. """
  391. raise NotImplementedError(self.add_if_new)
  392. def __setitem__(self, name: bytes, ref: bytes) -> None:
  393. """Set a reference name to point to the given SHA1.
  394. This method follows all symbolic references if applicable for the
  395. subclass.
  396. Note: This method unconditionally overwrites the contents of a
  397. reference. To update atomically only if the reference has not
  398. changed, use set_if_equals().
  399. Args:
  400. name: The refname to set.
  401. ref: The new sha the refname will refer to.
  402. """
  403. if not (valid_hexsha(ref) or ref.startswith(SYMREF)):
  404. raise ValueError(f"{ref!r} must be a valid sha (40 chars) or a symref")
  405. self.set_if_equals(name, None, ref)
  406. def remove_if_equals(
  407. self,
  408. name: bytes,
  409. old_ref: Optional[bytes],
  410. committer: Optional[bytes] = None,
  411. timestamp: Optional[int] = None,
  412. timezone: Optional[int] = None,
  413. message: Optional[bytes] = None,
  414. ) -> bool:
  415. """Remove a refname only if it currently equals old_ref.
  416. This method does not follow symbolic references, even if applicable for
  417. the subclass. It can be used to perform an atomic compare-and-delete
  418. operation.
  419. Args:
  420. name: The refname to delete.
  421. old_ref: The old sha the refname must refer to, or None to
  422. delete unconditionally.
  423. committer: Optional committer name/email
  424. timestamp: Optional timestamp
  425. timezone: Optional timezone
  426. message: Message for reflog
  427. Returns: True if the delete was successful, False otherwise.
  428. """
  429. raise NotImplementedError(self.remove_if_equals)
  430. def __delitem__(self, name: bytes) -> None:
  431. """Remove a refname.
  432. This method does not follow symbolic references, even if applicable for
  433. the subclass.
  434. Note: This method unconditionally deletes the contents of a reference.
  435. To delete atomically only if the reference has not changed, use
  436. remove_if_equals().
  437. Args:
  438. name: The refname to delete.
  439. """
  440. self.remove_if_equals(name, None)
  441. def get_symrefs(self) -> dict[bytes, bytes]:
  442. """Get a dict with all symrefs in this container.
  443. Returns: Dictionary mapping source ref to target ref
  444. """
  445. ret = {}
  446. for src in self.allkeys():
  447. try:
  448. ref_value = self.read_ref(src)
  449. assert ref_value is not None
  450. dst = parse_symref_value(ref_value)
  451. except ValueError:
  452. pass
  453. else:
  454. ret[src] = dst
  455. return ret
  456. def pack_refs(self, all: bool = False) -> None:
  457. """Pack loose refs into packed-refs file.
  458. Args:
  459. all: If True, pack all refs. If False, only pack tags.
  460. """
  461. raise NotImplementedError(self.pack_refs)
  462. class DictRefsContainer(RefsContainer):
  463. """RefsContainer backed by a simple dict.
  464. This container does not support symbolic or packed references and is not
  465. threadsafe.
  466. """
  467. def __init__(
  468. self,
  469. refs: dict[bytes, bytes],
  470. logger: Optional[
  471. Callable[
  472. [
  473. bytes,
  474. Optional[bytes],
  475. Optional[bytes],
  476. Optional[bytes],
  477. Optional[int],
  478. Optional[int],
  479. Optional[bytes],
  480. ],
  481. None,
  482. ]
  483. ] = None,
  484. ) -> None:
  485. """Initialize DictRefsContainer with refs dictionary and optional logger."""
  486. super().__init__(logger=logger)
  487. self._refs = refs
  488. self._peeled: dict[bytes, ObjectID] = {}
  489. self._watchers: set[Any] = set()
  490. def allkeys(self) -> set[bytes]:
  491. """Return all reference keys."""
  492. return set(self._refs.keys())
  493. def read_loose_ref(self, name: bytes) -> Optional[bytes]:
  494. """Read a loose reference."""
  495. return self._refs.get(name, None)
  496. def get_packed_refs(self) -> dict[bytes, bytes]:
  497. """Get packed references."""
  498. return {}
  499. def _notify(self, ref: bytes, newsha: Optional[bytes]) -> None:
  500. for watcher in self._watchers:
  501. watcher._notify((ref, newsha))
  502. def set_symbolic_ref(
  503. self,
  504. name: Ref,
  505. other: Ref,
  506. committer: Optional[bytes] = None,
  507. timestamp: Optional[int] = None,
  508. timezone: Optional[int] = None,
  509. message: Optional[bytes] = None,
  510. ) -> None:
  511. """Make a ref point at another ref.
  512. Args:
  513. name: Name of the ref to set
  514. other: Name of the ref to point at
  515. committer: Optional committer name for reflog
  516. timestamp: Optional timestamp for reflog
  517. timezone: Optional timezone for reflog
  518. message: Optional message for reflog
  519. """
  520. old = self.follow(name)[-1]
  521. new = SYMREF + other
  522. self._refs[name] = new
  523. self._notify(name, new)
  524. self._log(
  525. name,
  526. old,
  527. new,
  528. committer=committer,
  529. timestamp=timestamp,
  530. timezone=timezone,
  531. message=message,
  532. )
  533. def set_if_equals(
  534. self,
  535. name: bytes,
  536. old_ref: Optional[bytes],
  537. new_ref: bytes,
  538. committer: Optional[bytes] = None,
  539. timestamp: Optional[int] = None,
  540. timezone: Optional[int] = None,
  541. message: Optional[bytes] = None,
  542. ) -> bool:
  543. """Set a refname to new_ref only if it currently equals old_ref.
  544. This method follows all symbolic references, and can be used to perform
  545. an atomic compare-and-swap operation.
  546. Args:
  547. name: The refname to set.
  548. old_ref: The old sha the refname must refer to, or None to set
  549. unconditionally.
  550. new_ref: The new sha the refname will refer to.
  551. committer: Optional committer name for reflog
  552. timestamp: Optional timestamp for reflog
  553. timezone: Optional timezone for reflog
  554. message: Optional message for reflog
  555. Returns:
  556. True if the set was successful, False otherwise.
  557. """
  558. if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref:
  559. return False
  560. # Only update the specific ref requested, not the whole chain
  561. self._check_refname(name)
  562. old = self._refs.get(name)
  563. self._refs[name] = new_ref
  564. self._notify(name, new_ref)
  565. self._log(
  566. name,
  567. old,
  568. new_ref,
  569. committer=committer,
  570. timestamp=timestamp,
  571. timezone=timezone,
  572. message=message,
  573. )
  574. return True
  575. def add_if_new(
  576. self,
  577. name: Ref,
  578. ref: ObjectID,
  579. committer: Optional[bytes] = None,
  580. timestamp: Optional[int] = None,
  581. timezone: Optional[int] = None,
  582. message: Optional[bytes] = None,
  583. ) -> bool:
  584. """Add a new reference only if it does not already exist.
  585. Args:
  586. name: Ref name
  587. ref: Ref value
  588. committer: Optional committer name for reflog
  589. timestamp: Optional timestamp for reflog
  590. timezone: Optional timezone for reflog
  591. message: Optional message for reflog
  592. Returns:
  593. True if the add was successful, False otherwise.
  594. """
  595. if name in self._refs:
  596. return False
  597. self._refs[name] = ref
  598. self._notify(name, ref)
  599. self._log(
  600. name,
  601. None,
  602. ref,
  603. committer=committer,
  604. timestamp=timestamp,
  605. timezone=timezone,
  606. message=message,
  607. )
  608. return True
  609. def remove_if_equals(
  610. self,
  611. name: bytes,
  612. old_ref: Optional[bytes],
  613. committer: Optional[bytes] = None,
  614. timestamp: Optional[int] = None,
  615. timezone: Optional[int] = None,
  616. message: Optional[bytes] = None,
  617. ) -> bool:
  618. """Remove a refname only if it currently equals old_ref.
  619. This method does not follow symbolic references. It can be used to
  620. perform an atomic compare-and-delete operation.
  621. Args:
  622. name: The refname to delete.
  623. old_ref: The old sha the refname must refer to, or None to
  624. delete unconditionally.
  625. committer: Optional committer name for reflog
  626. timestamp: Optional timestamp for reflog
  627. timezone: Optional timezone for reflog
  628. message: Optional message for reflog
  629. Returns:
  630. True if the delete was successful, False otherwise.
  631. """
  632. if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref:
  633. return False
  634. try:
  635. old = self._refs.pop(name)
  636. except KeyError:
  637. pass
  638. else:
  639. self._notify(name, None)
  640. self._log(
  641. name,
  642. old,
  643. None,
  644. committer=committer,
  645. timestamp=timestamp,
  646. timezone=timezone,
  647. message=message,
  648. )
  649. return True
  650. def get_peeled(self, name: bytes) -> Optional[bytes]:
  651. """Get peeled version of a reference."""
  652. return self._peeled.get(name)
  653. def _update(self, refs: Mapping[bytes, bytes]) -> None:
  654. """Update multiple refs; intended only for testing."""
  655. # TODO(dborowitz): replace this with a public function that uses
  656. # set_if_equal.
  657. for ref, sha in refs.items():
  658. self.set_if_equals(ref, None, sha)
  659. def _update_peeled(self, peeled: Mapping[bytes, bytes]) -> None:
  660. """Update cached peeled refs; intended only for testing."""
  661. self._peeled.update(peeled)
  662. class InfoRefsContainer(RefsContainer):
  663. """Refs container that reads refs from a info/refs file."""
  664. def __init__(self, f: BinaryIO) -> None:
  665. """Initialize InfoRefsContainer from info/refs file."""
  666. self._refs: dict[bytes, bytes] = {}
  667. self._peeled: dict[bytes, bytes] = {}
  668. refs = read_info_refs(f)
  669. (self._refs, self._peeled) = split_peeled_refs(refs)
  670. def allkeys(self) -> set[bytes]:
  671. """Return all reference keys."""
  672. return set(self._refs.keys())
  673. def read_loose_ref(self, name: bytes) -> Optional[bytes]:
  674. """Read a loose reference."""
  675. return self._refs.get(name, None)
  676. def get_packed_refs(self) -> dict[bytes, bytes]:
  677. """Get packed references."""
  678. return {}
  679. def get_peeled(self, name: bytes) -> Optional[bytes]:
  680. """Get peeled version of a reference."""
  681. try:
  682. return self._peeled[name]
  683. except KeyError:
  684. return self._refs[name]
  685. class DiskRefsContainer(RefsContainer):
  686. """Refs container that reads refs from disk."""
  687. def __init__(
  688. self,
  689. path: Union[str, bytes, os.PathLike[str]],
  690. worktree_path: Optional[Union[str, bytes, os.PathLike[str]]] = None,
  691. logger: Optional[
  692. Callable[
  693. [
  694. bytes,
  695. bytes,
  696. bytes,
  697. Optional[bytes],
  698. Optional[int],
  699. Optional[int],
  700. bytes,
  701. ],
  702. None,
  703. ]
  704. ] = None,
  705. ) -> None:
  706. """Initialize DiskRefsContainer."""
  707. super().__init__(logger=logger)
  708. # Convert path-like objects to strings, then to bytes for Git compatibility
  709. self.path = os.fsencode(os.fspath(path))
  710. if worktree_path is None:
  711. self.worktree_path = self.path
  712. else:
  713. self.worktree_path = os.fsencode(os.fspath(worktree_path))
  714. self._packed_refs: Optional[dict[bytes, bytes]] = None
  715. self._peeled_refs: Optional[dict[bytes, bytes]] = None
  716. def __repr__(self) -> str:
  717. """Return string representation of DiskRefsContainer."""
  718. return f"{self.__class__.__name__}({self.path!r})"
  719. def _iter_dir(
  720. self,
  721. path: bytes,
  722. base: bytes,
  723. dir_filter: Optional[Callable[[bytes], bool]] = None,
  724. ) -> Iterator[bytes]:
  725. refspath = os.path.join(path, base.rstrip(b"/"))
  726. prefix_len = len(os.path.join(path, b""))
  727. for root, dirs, files in os.walk(refspath):
  728. directory = root[prefix_len:]
  729. if os.path.sep != "/":
  730. directory = directory.replace(os.fsencode(os.path.sep), b"/")
  731. if dir_filter is not None:
  732. dirs[:] = [
  733. d for d in dirs if dir_filter(b"/".join([directory, d, b""]))
  734. ]
  735. for filename in files:
  736. refname = b"/".join([directory, filename])
  737. if check_ref_format(refname):
  738. yield refname
  739. def _iter_loose_refs(self, base: bytes = b"refs/") -> Iterator[bytes]:
  740. base = base.rstrip(b"/") + b"/"
  741. search_paths: list[tuple[bytes, Optional[Callable[[bytes], bool]]]] = []
  742. if base != b"refs/":
  743. path = self.worktree_path if is_per_worktree_ref(base) else self.path
  744. search_paths.append((path, None))
  745. elif self.worktree_path == self.path:
  746. # Iterate through all the refs from the main worktree
  747. search_paths.append((self.path, None))
  748. else:
  749. # Iterate through all the shared refs from the commondir, excluding per-worktree refs
  750. search_paths.append((self.path, lambda r: not is_per_worktree_ref(r)))
  751. # Iterate through all the per-worktree refs from the worktree's gitdir
  752. search_paths.append((self.worktree_path, is_per_worktree_ref))
  753. for path, dir_filter in search_paths:
  754. yield from self._iter_dir(path, base, dir_filter=dir_filter)
  755. def subkeys(self, base: bytes) -> set[bytes]:
  756. """Return subkeys under a given base reference path."""
  757. subkeys = set()
  758. for key in self._iter_loose_refs(base):
  759. if key.startswith(base):
  760. subkeys.add(key[len(base) :].strip(b"/"))
  761. for key in self.get_packed_refs():
  762. if key.startswith(base):
  763. subkeys.add(key[len(base) :].strip(b"/"))
  764. return subkeys
  765. def allkeys(self) -> set[bytes]:
  766. """Return all reference keys."""
  767. allkeys = set()
  768. if os.path.exists(self.refpath(HEADREF)):
  769. allkeys.add(HEADREF)
  770. allkeys.update(self._iter_loose_refs())
  771. allkeys.update(self.get_packed_refs())
  772. return allkeys
  773. def refpath(self, name: bytes) -> bytes:
  774. """Return the disk path of a ref."""
  775. path = name
  776. if os.path.sep != "/":
  777. path = path.replace(b"/", os.fsencode(os.path.sep))
  778. root_dir = self.worktree_path if is_per_worktree_ref(name) else self.path
  779. return os.path.join(root_dir, path)
  780. def get_packed_refs(self) -> dict[bytes, bytes]:
  781. """Get contents of the packed-refs file.
  782. Returns: Dictionary mapping ref names to SHA1s
  783. Note: Will return an empty dictionary when no packed-refs file is
  784. present.
  785. """
  786. # TODO: invalidate the cache on repacking
  787. if self._packed_refs is None:
  788. # set both to empty because we want _peeled_refs to be
  789. # None if and only if _packed_refs is also None.
  790. self._packed_refs = {}
  791. self._peeled_refs = {}
  792. path = os.path.join(self.path, b"packed-refs")
  793. try:
  794. f = GitFile(path, "rb")
  795. except FileNotFoundError:
  796. return {}
  797. with f:
  798. first_line = next(iter(f)).rstrip()
  799. if first_line.startswith(b"# pack-refs") and b" peeled" in first_line:
  800. for sha, name, peeled in read_packed_refs_with_peeled(f):
  801. self._packed_refs[name] = sha
  802. if peeled:
  803. self._peeled_refs[name] = peeled
  804. else:
  805. f.seek(0)
  806. for sha, name in read_packed_refs(f):
  807. self._packed_refs[name] = sha
  808. return self._packed_refs
  809. def add_packed_refs(self, new_refs: Mapping[Ref, Optional[ObjectID]]) -> None:
  810. """Add the given refs as packed refs.
  811. Args:
  812. new_refs: A mapping of ref names to targets; if a target is None that
  813. means remove the ref
  814. """
  815. if not new_refs:
  816. return
  817. path = os.path.join(self.path, b"packed-refs")
  818. with GitFile(path, "wb") as f:
  819. # reread cached refs from disk, while holding the lock
  820. packed_refs = self.get_packed_refs().copy()
  821. for ref, target in new_refs.items():
  822. # sanity check
  823. if ref == HEADREF:
  824. raise ValueError("cannot pack HEAD")
  825. # remove any loose refs pointing to this one -- please
  826. # note that this bypasses remove_if_equals as we don't
  827. # want to affect packed refs in here
  828. with suppress(OSError):
  829. os.remove(self.refpath(ref))
  830. if target is not None:
  831. packed_refs[ref] = target
  832. else:
  833. packed_refs.pop(ref, None)
  834. write_packed_refs(f, packed_refs, self._peeled_refs)
  835. self._packed_refs = packed_refs
  836. def get_peeled(self, name: bytes) -> Optional[bytes]:
  837. """Return the cached peeled value of a ref, if available.
  838. Args:
  839. name: Name of the ref to peel
  840. Returns: The peeled value of the ref. If the ref is known not point to
  841. a tag, this will be the SHA the ref refers to. If the ref may point
  842. to a tag, but no cached information is available, None is returned.
  843. """
  844. self.get_packed_refs()
  845. if (
  846. self._peeled_refs is None
  847. or self._packed_refs is None
  848. or name not in self._packed_refs
  849. ):
  850. # No cache: no peeled refs were read, or this ref is loose
  851. return None
  852. if name in self._peeled_refs:
  853. return self._peeled_refs[name]
  854. else:
  855. # Known not peelable
  856. return self[name]
  857. def read_loose_ref(self, name: bytes) -> Optional[bytes]:
  858. """Read a reference file and return its contents.
  859. If the reference file a symbolic reference, only read the first line of
  860. the file. Otherwise, only read the first 40 bytes.
  861. Args:
  862. name: the refname to read, relative to refpath
  863. Returns: The contents of the ref file, or None if the file does not
  864. exist.
  865. Raises:
  866. IOError: if any other error occurs
  867. """
  868. filename = self.refpath(name)
  869. try:
  870. with GitFile(filename, "rb") as f:
  871. header = f.read(len(SYMREF))
  872. if header == SYMREF:
  873. # Read only the first line
  874. return header + next(iter(f)).rstrip(b"\r\n")
  875. else:
  876. # Read only the first 40 bytes
  877. return header + f.read(40 - len(SYMREF))
  878. except (OSError, UnicodeError):
  879. # don't assume anything specific about the error; in
  880. # particular, invalid or forbidden paths can raise weird
  881. # errors depending on the specific operating system
  882. return None
  883. def _remove_packed_ref(self, name: bytes) -> None:
  884. if self._packed_refs is None:
  885. return
  886. filename = os.path.join(self.path, b"packed-refs")
  887. # reread cached refs from disk, while holding the lock
  888. f = GitFile(filename, "wb")
  889. try:
  890. self._packed_refs = None
  891. self.get_packed_refs()
  892. if self._packed_refs is None or name not in self._packed_refs:
  893. f.abort()
  894. return
  895. del self._packed_refs[name]
  896. if self._peeled_refs is not None:
  897. with suppress(KeyError):
  898. del self._peeled_refs[name]
  899. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  900. f.close()
  901. except BaseException:
  902. f.abort()
  903. raise
  904. def set_symbolic_ref(
  905. self,
  906. name: bytes,
  907. other: bytes,
  908. committer: Optional[bytes] = None,
  909. timestamp: Optional[int] = None,
  910. timezone: Optional[int] = None,
  911. message: Optional[bytes] = None,
  912. ) -> None:
  913. """Make a ref point at another ref.
  914. Args:
  915. name: Name of the ref to set
  916. other: Name of the ref to point at
  917. committer: Optional committer name
  918. timestamp: Optional timestamp
  919. timezone: Optional timezone
  920. message: Optional message to describe the change
  921. """
  922. self._check_refname(name)
  923. self._check_refname(other)
  924. filename = self.refpath(name)
  925. f = GitFile(filename, "wb")
  926. try:
  927. f.write(SYMREF + other + b"\n")
  928. sha = self.follow(name)[-1]
  929. self._log(
  930. name,
  931. sha,
  932. sha,
  933. committer=committer,
  934. timestamp=timestamp,
  935. timezone=timezone,
  936. message=message,
  937. )
  938. except BaseException:
  939. f.abort()
  940. raise
  941. else:
  942. f.close()
  943. def set_if_equals(
  944. self,
  945. name: bytes,
  946. old_ref: Optional[bytes],
  947. new_ref: bytes,
  948. committer: Optional[bytes] = None,
  949. timestamp: Optional[int] = None,
  950. timezone: Optional[int] = None,
  951. message: Optional[bytes] = None,
  952. ) -> bool:
  953. """Set a refname to new_ref only if it currently equals old_ref.
  954. This method follows all symbolic references, and can be used to perform
  955. an atomic compare-and-swap operation.
  956. Args:
  957. name: The refname to set.
  958. old_ref: The old sha the refname must refer to, or None to set
  959. unconditionally.
  960. new_ref: The new sha the refname will refer to.
  961. committer: Optional committer name
  962. timestamp: Optional timestamp
  963. timezone: Optional timezone
  964. message: Set message for reflog
  965. Returns: True if the set was successful, False otherwise.
  966. """
  967. self._check_refname(name)
  968. try:
  969. realnames, _ = self.follow(name)
  970. realname = realnames[-1]
  971. except (KeyError, IndexError, SymrefLoop):
  972. realname = name
  973. filename = self.refpath(realname)
  974. # make sure none of the ancestor folders is in packed refs
  975. probe_ref = os.path.dirname(realname)
  976. packed_refs = self.get_packed_refs()
  977. while probe_ref:
  978. if packed_refs.get(probe_ref, None) is not None:
  979. raise NotADirectoryError(filename)
  980. probe_ref = os.path.dirname(probe_ref)
  981. ensure_dir_exists(os.path.dirname(filename))
  982. with GitFile(filename, "wb") as f:
  983. if old_ref is not None:
  984. try:
  985. # read again while holding the lock to handle race conditions
  986. orig_ref = self.read_loose_ref(realname)
  987. if orig_ref is None:
  988. orig_ref = self.get_packed_refs().get(realname, ZERO_SHA)
  989. if orig_ref != old_ref:
  990. f.abort()
  991. return False
  992. except OSError:
  993. f.abort()
  994. raise
  995. # Check if ref already has the desired value while holding the lock
  996. # This avoids fsync when ref is unchanged but still detects lock conflicts
  997. current_ref = self.read_loose_ref(realname)
  998. if current_ref is None:
  999. current_ref = packed_refs.get(realname, None)
  1000. if current_ref is not None and current_ref == new_ref:
  1001. # Ref already has desired value, abort write to avoid fsync
  1002. f.abort()
  1003. return True
  1004. try:
  1005. f.write(new_ref + b"\n")
  1006. except OSError:
  1007. f.abort()
  1008. raise
  1009. self._log(
  1010. realname,
  1011. old_ref,
  1012. new_ref,
  1013. committer=committer,
  1014. timestamp=timestamp,
  1015. timezone=timezone,
  1016. message=message,
  1017. )
  1018. return True
  1019. def add_if_new(
  1020. self,
  1021. name: bytes,
  1022. ref: bytes,
  1023. committer: Optional[bytes] = None,
  1024. timestamp: Optional[int] = None,
  1025. timezone: Optional[int] = None,
  1026. message: Optional[bytes] = None,
  1027. ) -> bool:
  1028. """Add a new reference only if it does not already exist.
  1029. This method follows symrefs, and only ensures that the last ref in the
  1030. chain does not exist.
  1031. Args:
  1032. name: The refname to set.
  1033. ref: The new sha the refname will refer to.
  1034. committer: Optional committer name
  1035. timestamp: Optional timestamp
  1036. timezone: Optional timezone
  1037. message: Optional message for reflog
  1038. Returns: True if the add was successful, False otherwise.
  1039. """
  1040. try:
  1041. realnames, contents = self.follow(name)
  1042. if contents is not None:
  1043. return False
  1044. realname = realnames[-1]
  1045. except (KeyError, IndexError):
  1046. realname = name
  1047. self._check_refname(realname)
  1048. filename = self.refpath(realname)
  1049. ensure_dir_exists(os.path.dirname(filename))
  1050. with GitFile(filename, "wb") as f:
  1051. if os.path.exists(filename) or name in self.get_packed_refs():
  1052. f.abort()
  1053. return False
  1054. try:
  1055. f.write(ref + b"\n")
  1056. except OSError:
  1057. f.abort()
  1058. raise
  1059. else:
  1060. self._log(
  1061. name,
  1062. None,
  1063. ref,
  1064. committer=committer,
  1065. timestamp=timestamp,
  1066. timezone=timezone,
  1067. message=message,
  1068. )
  1069. return True
  1070. def remove_if_equals(
  1071. self,
  1072. name: bytes,
  1073. old_ref: Optional[bytes],
  1074. committer: Optional[bytes] = None,
  1075. timestamp: Optional[int] = None,
  1076. timezone: Optional[int] = None,
  1077. message: Optional[bytes] = None,
  1078. ) -> bool:
  1079. """Remove a refname only if it currently equals old_ref.
  1080. This method does not follow symbolic references. It can be used to
  1081. perform an atomic compare-and-delete operation.
  1082. Args:
  1083. name: The refname to delete.
  1084. old_ref: The old sha the refname must refer to, or None to
  1085. delete unconditionally.
  1086. committer: Optional committer name
  1087. timestamp: Optional timestamp
  1088. timezone: Optional timezone
  1089. message: Optional message
  1090. Returns: True if the delete was successful, False otherwise.
  1091. """
  1092. self._check_refname(name)
  1093. filename = self.refpath(name)
  1094. ensure_dir_exists(os.path.dirname(filename))
  1095. f = GitFile(filename, "wb")
  1096. try:
  1097. if old_ref is not None:
  1098. orig_ref = self.read_loose_ref(name)
  1099. if orig_ref is None:
  1100. orig_ref = self.get_packed_refs().get(name, ZERO_SHA)
  1101. if orig_ref != old_ref:
  1102. return False
  1103. # remove the reference file itself
  1104. try:
  1105. found = os.path.lexists(filename)
  1106. except OSError:
  1107. # may only be packed, or otherwise unstorable
  1108. found = False
  1109. if found:
  1110. os.remove(filename)
  1111. self._remove_packed_ref(name)
  1112. self._log(
  1113. name,
  1114. old_ref,
  1115. None,
  1116. committer=committer,
  1117. timestamp=timestamp,
  1118. timezone=timezone,
  1119. message=message,
  1120. )
  1121. finally:
  1122. # never write, we just wanted the lock
  1123. f.abort()
  1124. # outside of the lock, clean-up any parent directory that might now
  1125. # be empty. this ensures that re-creating a reference of the same
  1126. # name of what was previously a directory works as expected
  1127. parent = name
  1128. while True:
  1129. try:
  1130. parent, _ = parent.rsplit(b"/", 1)
  1131. except ValueError:
  1132. break
  1133. if parent == b"refs":
  1134. break
  1135. parent_filename = self.refpath(parent)
  1136. try:
  1137. os.rmdir(parent_filename)
  1138. except OSError:
  1139. # this can be caused by the parent directory being
  1140. # removed by another process, being not empty, etc.
  1141. # in any case, this is non fatal because we already
  1142. # removed the reference, just ignore it
  1143. break
  1144. return True
  1145. def pack_refs(self, all: bool = False) -> None:
  1146. """Pack loose refs into packed-refs file.
  1147. Args:
  1148. all: If True, pack all refs. If False, only pack tags.
  1149. """
  1150. refs_to_pack: dict[Ref, Optional[ObjectID]] = {}
  1151. for ref in self.allkeys():
  1152. if ref == HEADREF:
  1153. # Never pack HEAD
  1154. continue
  1155. if all or ref.startswith(LOCAL_TAG_PREFIX):
  1156. try:
  1157. sha = self[ref]
  1158. if sha:
  1159. refs_to_pack[ref] = sha
  1160. except KeyError:
  1161. # Broken ref, skip it
  1162. pass
  1163. if refs_to_pack:
  1164. self.add_packed_refs(refs_to_pack)
  1165. def _split_ref_line(line: bytes) -> tuple[bytes, bytes]:
  1166. """Split a single ref line into a tuple of SHA1 and name."""
  1167. fields = line.rstrip(b"\n\r").split(b" ")
  1168. if len(fields) != 2:
  1169. raise PackedRefsException(f"invalid ref line {line!r}")
  1170. sha, name = fields
  1171. if not valid_hexsha(sha):
  1172. raise PackedRefsException(f"Invalid hex sha {sha!r}")
  1173. if not check_ref_format(name):
  1174. raise PackedRefsException(f"invalid ref name {name!r}")
  1175. return (sha, name)
  1176. def read_packed_refs(f: IO[bytes]) -> Iterator[tuple[bytes, bytes]]:
  1177. """Read a packed refs file.
  1178. Args:
  1179. f: file-like object to read from
  1180. Returns: Iterator over tuples with SHA1s and ref names.
  1181. """
  1182. for line in f:
  1183. if line.startswith(b"#"):
  1184. # Comment
  1185. continue
  1186. if line.startswith(b"^"):
  1187. raise PackedRefsException("found peeled ref in packed-refs without peeled")
  1188. yield _split_ref_line(line)
  1189. def read_packed_refs_with_peeled(
  1190. f: IO[bytes],
  1191. ) -> Iterator[tuple[bytes, bytes, Optional[bytes]]]:
  1192. """Read a packed refs file including peeled refs.
  1193. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  1194. with ref names, SHA1s, and peeled SHA1s (or None).
  1195. Args:
  1196. f: file-like object to read from, seek'ed to the second line
  1197. """
  1198. last = None
  1199. for line in f:
  1200. if line.startswith(b"#"):
  1201. continue
  1202. line = line.rstrip(b"\r\n")
  1203. if line.startswith(b"^"):
  1204. if not last:
  1205. raise PackedRefsException("unexpected peeled ref line")
  1206. if not valid_hexsha(line[1:]):
  1207. raise PackedRefsException(f"Invalid hex sha {line[1:]!r}")
  1208. sha, name = _split_ref_line(last)
  1209. last = None
  1210. yield (sha, name, line[1:])
  1211. else:
  1212. if last:
  1213. sha, name = _split_ref_line(last)
  1214. yield (sha, name, None)
  1215. last = line
  1216. if last:
  1217. sha, name = _split_ref_line(last)
  1218. yield (sha, name, None)
  1219. def write_packed_refs(
  1220. f: IO[bytes],
  1221. packed_refs: Mapping[bytes, bytes],
  1222. peeled_refs: Optional[Mapping[bytes, bytes]] = None,
  1223. ) -> None:
  1224. """Write a packed refs file.
  1225. Args:
  1226. f: empty file-like object to write to
  1227. packed_refs: dict of refname to sha of packed refs to write
  1228. peeled_refs: dict of refname to peeled value of sha
  1229. """
  1230. if peeled_refs is None:
  1231. peeled_refs = {}
  1232. else:
  1233. f.write(b"# pack-refs with: peeled\n")
  1234. for refname in sorted(packed_refs.keys()):
  1235. f.write(git_line(packed_refs[refname], refname))
  1236. if refname in peeled_refs:
  1237. f.write(b"^" + peeled_refs[refname] + b"\n")
  1238. def read_info_refs(f: BinaryIO) -> dict[bytes, bytes]:
  1239. """Read info/refs file.
  1240. Args:
  1241. f: File-like object to read from
  1242. Returns:
  1243. Dictionary mapping ref names to SHA1s
  1244. """
  1245. ret = {}
  1246. for line in f.readlines():
  1247. (sha, name) = line.rstrip(b"\r\n").split(b"\t", 1)
  1248. ret[name] = sha
  1249. return ret
  1250. def write_info_refs(
  1251. refs: Mapping[bytes, bytes], store: ObjectContainer
  1252. ) -> Iterator[bytes]:
  1253. """Generate info refs."""
  1254. # TODO: Avoid recursive import :(
  1255. from .object_store import peel_sha
  1256. for name, sha in sorted(refs.items()):
  1257. # get_refs() includes HEAD as a special case, but we don't want to
  1258. # advertise it
  1259. if name == HEADREF:
  1260. continue
  1261. try:
  1262. o = store[sha]
  1263. except KeyError:
  1264. continue
  1265. _unpeeled, peeled = peel_sha(store, sha)
  1266. yield o.id + b"\t" + name + b"\n"
  1267. if o.id != peeled.id:
  1268. yield peeled.id + b"\t" + name + PEELED_TAG_SUFFIX + b"\n"
  1269. def is_local_branch(x: bytes) -> bool:
  1270. """Check if a ref name is a local branch."""
  1271. return x.startswith(LOCAL_BRANCH_PREFIX)
  1272. def local_branch_name(name: bytes) -> bytes:
  1273. """Build a full branch ref from a short name.
  1274. Args:
  1275. name: Short branch name (e.g., b"master") or full ref
  1276. Returns:
  1277. Full branch ref name (e.g., b"refs/heads/master")
  1278. Examples:
  1279. >>> local_branch_name(b"master")
  1280. b'refs/heads/master'
  1281. >>> local_branch_name(b"refs/heads/master")
  1282. b'refs/heads/master'
  1283. """
  1284. if name.startswith(LOCAL_BRANCH_PREFIX):
  1285. return name
  1286. return LOCAL_BRANCH_PREFIX + name
  1287. def local_tag_name(name: bytes) -> bytes:
  1288. """Build a full tag ref from a short name.
  1289. Args:
  1290. name: Short tag name (e.g., b"v1.0") or full ref
  1291. Returns:
  1292. Full tag ref name (e.g., b"refs/tags/v1.0")
  1293. Examples:
  1294. >>> local_tag_name(b"v1.0")
  1295. b'refs/tags/v1.0'
  1296. >>> local_tag_name(b"refs/tags/v1.0")
  1297. b'refs/tags/v1.0'
  1298. """
  1299. if name.startswith(LOCAL_TAG_PREFIX):
  1300. return name
  1301. return LOCAL_TAG_PREFIX + name
  1302. def extract_branch_name(ref: bytes) -> bytes:
  1303. """Extract branch name from a full branch ref.
  1304. Args:
  1305. ref: Full branch ref (e.g., b"refs/heads/master")
  1306. Returns:
  1307. Short branch name (e.g., b"master")
  1308. Raises:
  1309. ValueError: If ref is not a local branch
  1310. Examples:
  1311. >>> extract_branch_name(b"refs/heads/master")
  1312. b'master'
  1313. >>> extract_branch_name(b"refs/heads/feature/foo")
  1314. b'feature/foo'
  1315. """
  1316. if not ref.startswith(LOCAL_BRANCH_PREFIX):
  1317. raise ValueError(f"Not a local branch ref: {ref!r}")
  1318. return ref[len(LOCAL_BRANCH_PREFIX) :]
  1319. def extract_tag_name(ref: bytes) -> bytes:
  1320. """Extract tag name from a full tag ref.
  1321. Args:
  1322. ref: Full tag ref (e.g., b"refs/tags/v1.0")
  1323. Returns:
  1324. Short tag name (e.g., b"v1.0")
  1325. Raises:
  1326. ValueError: If ref is not a local tag
  1327. Examples:
  1328. >>> extract_tag_name(b"refs/tags/v1.0")
  1329. b'v1.0'
  1330. """
  1331. if not ref.startswith(LOCAL_TAG_PREFIX):
  1332. raise ValueError(f"Not a local tag ref: {ref!r}")
  1333. return ref[len(LOCAL_TAG_PREFIX) :]
  1334. def shorten_ref_name(ref: bytes) -> bytes:
  1335. """Convert a full ref name to its short form.
  1336. Args:
  1337. ref: Full ref name (e.g., b"refs/heads/master")
  1338. Returns:
  1339. Short ref name (e.g., b"master")
  1340. Examples:
  1341. >>> shorten_ref_name(b"refs/heads/master")
  1342. b'master'
  1343. >>> shorten_ref_name(b"refs/remotes/origin/main")
  1344. b'origin/main'
  1345. >>> shorten_ref_name(b"refs/tags/v1.0")
  1346. b'v1.0'
  1347. >>> shorten_ref_name(b"HEAD")
  1348. b'HEAD'
  1349. """
  1350. if ref.startswith(LOCAL_BRANCH_PREFIX):
  1351. return ref[len(LOCAL_BRANCH_PREFIX) :]
  1352. elif ref.startswith(LOCAL_REMOTE_PREFIX):
  1353. return ref[len(LOCAL_REMOTE_PREFIX) :]
  1354. elif ref.startswith(LOCAL_TAG_PREFIX):
  1355. return ref[len(LOCAL_TAG_PREFIX) :]
  1356. return ref
  1357. T = TypeVar("T", dict[bytes, bytes], dict[bytes, Optional[bytes]])
  1358. def strip_peeled_refs(refs: T) -> T:
  1359. """Remove all peeled refs."""
  1360. return {
  1361. ref: sha for (ref, sha) in refs.items() if not ref.endswith(PEELED_TAG_SUFFIX)
  1362. }
  1363. def split_peeled_refs(refs: T) -> tuple[T, dict[bytes, bytes]]:
  1364. """Split peeled refs from regular refs."""
  1365. peeled: dict[bytes, bytes] = {}
  1366. regular = {k: v for k, v in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)}
  1367. for ref, sha in refs.items():
  1368. if ref.endswith(PEELED_TAG_SUFFIX):
  1369. # Only add to peeled dict if sha is not None
  1370. if sha is not None:
  1371. peeled[ref[: -len(PEELED_TAG_SUFFIX)]] = sha
  1372. return regular, peeled
  1373. def _set_origin_head(
  1374. refs: RefsContainer, origin: bytes, origin_head: Optional[bytes]
  1375. ) -> None:
  1376. # set refs/remotes/origin/HEAD
  1377. origin_base = b"refs/remotes/" + origin + b"/"
  1378. if origin_head and origin_head.startswith(LOCAL_BRANCH_PREFIX):
  1379. origin_ref = origin_base + HEADREF
  1380. target_ref = origin_base + extract_branch_name(origin_head)
  1381. if target_ref in refs:
  1382. refs.set_symbolic_ref(origin_ref, target_ref)
  1383. def _set_default_branch(
  1384. refs: RefsContainer,
  1385. origin: bytes,
  1386. origin_head: Optional[bytes],
  1387. branch: Optional[bytes],
  1388. ref_message: Optional[bytes],
  1389. ) -> bytes:
  1390. """Set the default branch."""
  1391. origin_base = b"refs/remotes/" + origin + b"/"
  1392. if branch:
  1393. origin_ref = origin_base + branch
  1394. if origin_ref in refs:
  1395. local_ref = local_branch_name(branch)
  1396. refs.add_if_new(local_ref, refs[origin_ref], ref_message)
  1397. head_ref = local_ref
  1398. elif local_tag_name(branch) in refs:
  1399. head_ref = local_tag_name(branch)
  1400. else:
  1401. raise ValueError(f"{os.fsencode(branch)!r} is not a valid branch or tag")
  1402. elif origin_head:
  1403. head_ref = origin_head
  1404. if origin_head.startswith(LOCAL_BRANCH_PREFIX):
  1405. origin_ref = origin_base + extract_branch_name(origin_head)
  1406. else:
  1407. origin_ref = origin_head
  1408. try:
  1409. refs.add_if_new(head_ref, refs[origin_ref], ref_message)
  1410. except KeyError:
  1411. pass
  1412. else:
  1413. raise ValueError("neither origin_head nor branch are provided")
  1414. return head_ref
  1415. def _set_head(
  1416. refs: RefsContainer, head_ref: bytes, ref_message: Optional[bytes]
  1417. ) -> Optional[bytes]:
  1418. if head_ref.startswith(LOCAL_TAG_PREFIX):
  1419. # detach HEAD at specified tag
  1420. head = refs[head_ref]
  1421. if isinstance(head, Tag):
  1422. _cls, obj = head.object
  1423. head = obj.get_object(obj).id
  1424. del refs[HEADREF]
  1425. refs.set_if_equals(HEADREF, None, head, message=ref_message)
  1426. else:
  1427. # set HEAD to specific branch
  1428. try:
  1429. head = refs[head_ref]
  1430. refs.set_symbolic_ref(HEADREF, head_ref)
  1431. refs.set_if_equals(HEADREF, None, head, message=ref_message)
  1432. except KeyError:
  1433. head = None
  1434. return head
  1435. def _import_remote_refs(
  1436. refs_container: RefsContainer,
  1437. remote_name: str,
  1438. refs: dict[bytes, Optional[bytes]],
  1439. message: Optional[bytes] = None,
  1440. prune: bool = False,
  1441. prune_tags: bool = False,
  1442. ) -> None:
  1443. stripped_refs = strip_peeled_refs(refs)
  1444. branches = {
  1445. extract_branch_name(n): v
  1446. for (n, v) in stripped_refs.items()
  1447. if n.startswith(LOCAL_BRANCH_PREFIX) and v is not None
  1448. }
  1449. refs_container.import_refs(
  1450. b"refs/remotes/" + remote_name.encode(),
  1451. branches,
  1452. message=message,
  1453. prune=prune,
  1454. )
  1455. tags = {
  1456. extract_tag_name(n): v
  1457. for (n, v) in stripped_refs.items()
  1458. if n.startswith(LOCAL_TAG_PREFIX)
  1459. and not n.endswith(PEELED_TAG_SUFFIX)
  1460. and v is not None
  1461. }
  1462. refs_container.import_refs(
  1463. LOCAL_TAG_PREFIX, tags, message=message, prune=prune_tags
  1464. )
  1465. def serialize_refs(
  1466. store: ObjectContainer, refs: Mapping[bytes, bytes]
  1467. ) -> dict[bytes, bytes]:
  1468. """Serialize refs with peeled refs.
  1469. Args:
  1470. store: Object store to peel refs from
  1471. refs: Dictionary of ref names to SHAs
  1472. Returns:
  1473. Dictionary with refs and peeled refs (marked with ^{})
  1474. """
  1475. # TODO: Avoid recursive import :(
  1476. from .object_store import peel_sha
  1477. ret = {}
  1478. for ref, sha in refs.items():
  1479. try:
  1480. unpeeled, peeled = peel_sha(store, sha)
  1481. except KeyError:
  1482. warnings.warn(
  1483. "ref {} points at non-present sha {}".format(
  1484. ref.decode("utf-8", "replace"), sha.decode("ascii")
  1485. ),
  1486. UserWarning,
  1487. )
  1488. continue
  1489. else:
  1490. if isinstance(unpeeled, Tag):
  1491. ret[ref + PEELED_TAG_SUFFIX] = peeled.id
  1492. ret[ref] = unpeeled.id
  1493. return ret
  1494. class locked_ref:
  1495. """Lock a ref while making modifications.
  1496. Works as a context manager.
  1497. """
  1498. def __init__(self, refs_container: DiskRefsContainer, refname: Ref) -> None:
  1499. """Initialize a locked ref.
  1500. Args:
  1501. refs_container: The DiskRefsContainer to lock the ref in
  1502. refname: The ref name to lock
  1503. """
  1504. self._refs_container = refs_container
  1505. self._refname = refname
  1506. self._file: Optional[_GitFile] = None
  1507. self._realname: Optional[Ref] = None
  1508. self._deleted = False
  1509. def __enter__(self) -> "locked_ref":
  1510. """Enter the context manager and acquire the lock.
  1511. Returns:
  1512. This locked_ref instance
  1513. Raises:
  1514. OSError: If the lock cannot be acquired
  1515. """
  1516. self._refs_container._check_refname(self._refname)
  1517. try:
  1518. realnames, _ = self._refs_container.follow(self._refname)
  1519. self._realname = realnames[-1]
  1520. except (KeyError, IndexError, SymrefLoop):
  1521. self._realname = self._refname
  1522. filename = self._refs_container.refpath(self._realname)
  1523. ensure_dir_exists(os.path.dirname(filename))
  1524. f = GitFile(filename, "wb")
  1525. self._file = f
  1526. return self
  1527. def __exit__(
  1528. self,
  1529. exc_type: Optional[type],
  1530. exc_value: Optional[BaseException],
  1531. traceback: Optional[types.TracebackType],
  1532. ) -> None:
  1533. """Exit the context manager and release the lock.
  1534. Args:
  1535. exc_type: Type of exception if one occurred
  1536. exc_value: Exception instance if one occurred
  1537. traceback: Traceback if an exception occurred
  1538. """
  1539. if self._file:
  1540. if exc_type is not None or self._deleted:
  1541. self._file.abort()
  1542. else:
  1543. self._file.close()
  1544. def get(self) -> Optional[bytes]:
  1545. """Get the current value of the ref."""
  1546. if not self._file:
  1547. raise RuntimeError("locked_ref not in context")
  1548. assert self._realname is not None
  1549. current_ref = self._refs_container.read_loose_ref(self._realname)
  1550. if current_ref is None:
  1551. current_ref = self._refs_container.get_packed_refs().get(
  1552. self._realname, None
  1553. )
  1554. return current_ref
  1555. def ensure_equals(self, expected_value: Optional[bytes]) -> bool:
  1556. """Ensure the ref currently equals the expected value.
  1557. Args:
  1558. expected_value: The expected current value of the ref
  1559. Returns:
  1560. True if the ref equals the expected value, False otherwise
  1561. """
  1562. current_value = self.get()
  1563. return current_value == expected_value
  1564. def set(self, new_ref: bytes) -> None:
  1565. """Set the ref to a new value.
  1566. Args:
  1567. new_ref: The new SHA1 or symbolic ref value
  1568. """
  1569. if not self._file:
  1570. raise RuntimeError("locked_ref not in context")
  1571. if not (valid_hexsha(new_ref) or new_ref.startswith(SYMREF)):
  1572. raise ValueError(f"{new_ref!r} must be a valid sha (40 chars) or a symref")
  1573. self._file.seek(0)
  1574. self._file.truncate()
  1575. self._file.write(new_ref + b"\n")
  1576. self._deleted = False
  1577. def set_symbolic_ref(self, target: Ref) -> None:
  1578. """Make this ref point at another ref.
  1579. Args:
  1580. target: Name of the ref to point at
  1581. """
  1582. if not self._file:
  1583. raise RuntimeError("locked_ref not in context")
  1584. self._refs_container._check_refname(target)
  1585. self._file.seek(0)
  1586. self._file.truncate()
  1587. self._file.write(SYMREF + target + b"\n")
  1588. self._deleted = False
  1589. def delete(self) -> None:
  1590. """Delete the ref file while holding the lock."""
  1591. if not self._file:
  1592. raise RuntimeError("locked_ref not in context")
  1593. # Delete the actual ref file while holding the lock
  1594. if self._realname:
  1595. filename = self._refs_container.refpath(self._realname)
  1596. try:
  1597. if os.path.lexists(filename):
  1598. os.remove(filename)
  1599. except FileNotFoundError:
  1600. pass
  1601. self._refs_container._remove_packed_ref(self._realname)
  1602. self._deleted = True
  1603. class NamespacedRefsContainer(RefsContainer):
  1604. """Wrapper that adds namespace prefix to all ref operations.
  1605. This implements Git's GIT_NAMESPACE feature, which stores refs under
  1606. refs/namespaces/<namespace>/ and filters operations to only show refs
  1607. within that namespace.
  1608. Example:
  1609. With namespace "foo", a ref "refs/heads/master" is stored as
  1610. "refs/namespaces/foo/refs/heads/master" in the underlying container.
  1611. """
  1612. def __init__(self, refs: RefsContainer, namespace: bytes) -> None:
  1613. """Initialize NamespacedRefsContainer.
  1614. Args:
  1615. refs: The underlying refs container to wrap
  1616. namespace: The namespace prefix (e.g., b"foo" or b"foo/bar")
  1617. """
  1618. super().__init__(logger=refs._logger)
  1619. self._refs = refs
  1620. # Build namespace prefix: refs/namespaces/<namespace>/
  1621. # Support nested namespaces: foo/bar -> refs/namespaces/foo/refs/namespaces/bar/
  1622. namespace_parts = namespace.split(b"/")
  1623. self._namespace_prefix = b""
  1624. for part in namespace_parts:
  1625. self._namespace_prefix += b"refs/namespaces/" + part + b"/"
  1626. def _apply_namespace(self, name: bytes) -> bytes:
  1627. """Apply namespace prefix to a ref name."""
  1628. # HEAD and other special refs are not namespaced
  1629. if name == HEADREF or not name.startswith(b"refs/"):
  1630. return name
  1631. return self._namespace_prefix + name
  1632. def _strip_namespace(self, name: bytes) -> Optional[bytes]:
  1633. """Remove namespace prefix from a ref name.
  1634. Returns None if the ref is not in our namespace.
  1635. """
  1636. # HEAD and other special refs are not namespaced
  1637. if name == HEADREF or not name.startswith(b"refs/"):
  1638. return name
  1639. if name.startswith(self._namespace_prefix):
  1640. return name[len(self._namespace_prefix) :]
  1641. return None
  1642. def allkeys(self) -> set[bytes]:
  1643. """Return all reference keys in this namespace."""
  1644. keys = set()
  1645. for key in self._refs.allkeys():
  1646. stripped = self._strip_namespace(key)
  1647. if stripped is not None:
  1648. keys.add(stripped)
  1649. return keys
  1650. def read_loose_ref(self, name: bytes) -> Optional[bytes]:
  1651. """Read a loose reference."""
  1652. return self._refs.read_loose_ref(self._apply_namespace(name))
  1653. def get_packed_refs(self) -> dict[Ref, ObjectID]:
  1654. """Get packed refs within this namespace."""
  1655. packed = {}
  1656. for name, value in self._refs.get_packed_refs().items():
  1657. stripped = self._strip_namespace(name)
  1658. if stripped is not None:
  1659. packed[stripped] = value
  1660. return packed
  1661. def add_packed_refs(self, new_refs: Mapping[Ref, Optional[ObjectID]]) -> None:
  1662. """Add packed refs with namespace prefix."""
  1663. namespaced_refs = {
  1664. self._apply_namespace(name): value for name, value in new_refs.items()
  1665. }
  1666. self._refs.add_packed_refs(namespaced_refs)
  1667. def get_peeled(self, name: bytes) -> Optional[ObjectID]:
  1668. """Return the cached peeled value of a ref."""
  1669. return self._refs.get_peeled(self._apply_namespace(name))
  1670. def set_symbolic_ref(
  1671. self,
  1672. name: bytes,
  1673. other: bytes,
  1674. committer: Optional[bytes] = None,
  1675. timestamp: Optional[int] = None,
  1676. timezone: Optional[int] = None,
  1677. message: Optional[bytes] = None,
  1678. ) -> None:
  1679. """Make a ref point at another ref."""
  1680. self._refs.set_symbolic_ref(
  1681. self._apply_namespace(name),
  1682. self._apply_namespace(other),
  1683. committer=committer,
  1684. timestamp=timestamp,
  1685. timezone=timezone,
  1686. message=message,
  1687. )
  1688. def set_if_equals(
  1689. self,
  1690. name: bytes,
  1691. old_ref: Optional[bytes],
  1692. new_ref: bytes,
  1693. committer: Optional[bytes] = None,
  1694. timestamp: Optional[int] = None,
  1695. timezone: Optional[int] = None,
  1696. message: Optional[bytes] = None,
  1697. ) -> bool:
  1698. """Set a refname to new_ref only if it currently equals old_ref."""
  1699. return self._refs.set_if_equals(
  1700. self._apply_namespace(name),
  1701. old_ref,
  1702. new_ref,
  1703. committer=committer,
  1704. timestamp=timestamp,
  1705. timezone=timezone,
  1706. message=message,
  1707. )
  1708. def add_if_new(
  1709. self,
  1710. name: bytes,
  1711. ref: bytes,
  1712. committer: Optional[bytes] = None,
  1713. timestamp: Optional[int] = None,
  1714. timezone: Optional[int] = None,
  1715. message: Optional[bytes] = None,
  1716. ) -> bool:
  1717. """Add a new reference only if it does not already exist."""
  1718. return self._refs.add_if_new(
  1719. self._apply_namespace(name),
  1720. ref,
  1721. committer=committer,
  1722. timestamp=timestamp,
  1723. timezone=timezone,
  1724. message=message,
  1725. )
  1726. def remove_if_equals(
  1727. self,
  1728. name: bytes,
  1729. old_ref: Optional[bytes],
  1730. committer: Optional[bytes] = None,
  1731. timestamp: Optional[int] = None,
  1732. timezone: Optional[int] = None,
  1733. message: Optional[bytes] = None,
  1734. ) -> bool:
  1735. """Remove a refname only if it currently equals old_ref."""
  1736. return self._refs.remove_if_equals(
  1737. self._apply_namespace(name),
  1738. old_ref,
  1739. committer=committer,
  1740. timestamp=timestamp,
  1741. timezone=timezone,
  1742. message=message,
  1743. )
  1744. def pack_refs(self, all: bool = False) -> None:
  1745. """Pack loose refs into packed-refs file.
  1746. Note: This packs all refs in the underlying container, not just
  1747. those in the namespace.
  1748. """
  1749. self._refs.pack_refs(all=all)
  1750. def filter_ref_prefix(refs: T, prefixes: Iterable[bytes]) -> T:
  1751. """Filter refs to only include those with a given prefix.
  1752. Args:
  1753. refs: A dictionary of refs.
  1754. prefixes: The prefixes to filter by.
  1755. """
  1756. filtered = {k: v for k, v in refs.items() if any(k.startswith(p) for p in prefixes)}
  1757. return filtered
  1758. def is_per_worktree_ref(ref: bytes) -> bool:
  1759. """Returns whether a reference is stored per worktree or not.
  1760. Per-worktree references are:
  1761. - all pseudorefs, e.g. HEAD
  1762. - all references stored inside "refs/bisect/", "refs/worktree/" and "refs/rewritten/"
  1763. All refs starting with "refs/" are shared, except for the ones listed above.
  1764. See https://git-scm.com/docs/git-worktree#_refs.
  1765. """
  1766. return not ref.startswith(b"refs/") or ref.startswith(
  1767. (b"refs/bisect/", b"refs/worktree/", b"refs/rewritten/")
  1768. )