refs.py 37 KB

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