refs.py 40 KB

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