refs.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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 errno
  23. import os
  24. import sys
  25. from dulwich.errors import (
  26. PackedRefsException,
  27. RefFormatError,
  28. )
  29. from dulwich.objects import (
  30. git_line,
  31. valid_hexsha,
  32. ZERO_SHA,
  33. )
  34. from dulwich.file import (
  35. GitFile,
  36. ensure_dir_exists,
  37. )
  38. SYMREF = b'ref: '
  39. LOCAL_BRANCH_PREFIX = b'refs/heads/'
  40. LOCAL_TAG_PREFIX = b'refs/tags/'
  41. BAD_REF_CHARS = set(b'\177 ~^:?*[')
  42. ANNOTATED_TAG_SUFFIX = b'^{}'
  43. def parse_symref_value(contents):
  44. """Parse a symref value.
  45. :param contents: Contents to parse
  46. :return: Destination
  47. """
  48. if contents.startswith(SYMREF):
  49. return contents[len(SYMREF):].rstrip(b'\r\n')
  50. raise ValueError(contents)
  51. def check_ref_format(refname):
  52. """Check if a refname is correctly formatted.
  53. Implements all the same rules as git-check-ref-format[1].
  54. [1]
  55. http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  56. :param refname: The refname to check
  57. :return: True if refname is valid, False otherwise
  58. """
  59. # These could be combined into one big expression, but are listed
  60. # separately to parallel [1].
  61. if b'/.' in refname or refname.startswith(b'.'):
  62. return False
  63. if b'/' not in refname:
  64. return False
  65. if b'..' in refname:
  66. return False
  67. for i, c in enumerate(refname):
  68. if ord(refname[i:i+1]) < 0o40 or c in BAD_REF_CHARS:
  69. return False
  70. if refname[-1] in b'/.':
  71. return False
  72. if refname.endswith(b'.lock'):
  73. return False
  74. if b'@{' in refname:
  75. return False
  76. if b'\\' in refname:
  77. return False
  78. return True
  79. class RefsContainer(object):
  80. """A container for refs."""
  81. def __init__(self, logger=None):
  82. self._logger = logger
  83. def _log(self, ref, old_sha, new_sha, committer=None, timestamp=None,
  84. timezone=None, message=None):
  85. if self._logger is None:
  86. return
  87. if message is None:
  88. return
  89. self._logger(ref, old_sha, new_sha, committer, timestamp,
  90. timezone, message)
  91. def set_symbolic_ref(self, name, other, committer=None, timestamp=None,
  92. timezone=None, message=None):
  93. """Make a ref point at another ref.
  94. :param name: Name of the ref to set
  95. :param other: Name of the ref to point at
  96. :param message: Optional message
  97. """
  98. raise NotImplementedError(self.set_symbolic_ref)
  99. def get_packed_refs(self):
  100. """Get contents of the packed-refs file.
  101. :return: Dictionary mapping ref names to SHA1s
  102. :note: Will return an empty dictionary when no packed-refs file is
  103. present.
  104. """
  105. raise NotImplementedError(self.get_packed_refs)
  106. def get_peeled(self, name):
  107. """Return the cached peeled value of a ref, if available.
  108. :param name: Name of the ref to peel
  109. :return: The peeled value of the ref. If the ref is known not point to
  110. a tag, this will be the SHA the ref refers to. If the ref may point
  111. to a tag, but no cached information is available, None is returned.
  112. """
  113. return None
  114. def import_refs(self, base, other, committer=None, timestamp=None,
  115. timezone=None, message=None):
  116. for name, value in other.items():
  117. self.set_if_equals(b'/'.join((base, name)), None, value,
  118. message=message)
  119. def allkeys(self):
  120. """All refs present in this container."""
  121. raise NotImplementedError(self.allkeys)
  122. def keys(self, base=None):
  123. """Refs present in this container.
  124. :param base: An optional base to return refs under.
  125. :return: An unsorted set of valid refs in this container, including
  126. packed refs.
  127. """
  128. if base is not None:
  129. return self.subkeys(base)
  130. else:
  131. return self.allkeys()
  132. def subkeys(self, base):
  133. """Refs present in this container under a base.
  134. :param base: The base to return refs under.
  135. :return: A set of valid refs in this container under the base; the base
  136. prefix is stripped from the ref names returned.
  137. """
  138. keys = set()
  139. base_len = len(base) + 1
  140. for refname in self.allkeys():
  141. if refname.startswith(base):
  142. keys.add(refname[base_len:])
  143. return keys
  144. def as_dict(self, base=None):
  145. """Return the contents of this container as a dictionary.
  146. """
  147. ret = {}
  148. keys = self.keys(base)
  149. if base is None:
  150. base = b''
  151. else:
  152. base = base.rstrip(b'/')
  153. for key in keys:
  154. try:
  155. ret[key] = self[(base + b'/' + key).strip(b'/')]
  156. except KeyError:
  157. continue # Unable to resolve
  158. return ret
  159. def _check_refname(self, name):
  160. """Ensure a refname is valid and lives in refs or is HEAD.
  161. HEAD is not a valid refname according to git-check-ref-format, but this
  162. class needs to be able to touch HEAD. Also, check_ref_format expects
  163. refnames without the leading 'refs/', but this class requires that
  164. so it cannot touch anything outside the refs dir (or HEAD).
  165. :param name: The name of the reference.
  166. :raises KeyError: if a refname is not HEAD or is otherwise not valid.
  167. """
  168. if name in (b'HEAD', b'refs/stash'):
  169. return
  170. if not name.startswith(b'refs/') or not check_ref_format(name[5:]):
  171. raise RefFormatError(name)
  172. def read_ref(self, refname):
  173. """Read a reference without following any references.
  174. :param refname: The name of the reference
  175. :return: The contents of the ref file, or None if it does
  176. not exist.
  177. """
  178. contents = self.read_loose_ref(refname)
  179. if not contents:
  180. contents = self.get_packed_refs().get(refname, None)
  181. return contents
  182. def read_loose_ref(self, name):
  183. """Read a loose reference and return its contents.
  184. :param name: the refname to read
  185. :return: The contents of the ref file, or None if it does
  186. not exist.
  187. """
  188. raise NotImplementedError(self.read_loose_ref)
  189. def follow(self, name):
  190. """Follow a reference name.
  191. :return: a tuple of (refnames, sha), wheres refnames are the names of
  192. references in the chain
  193. """
  194. contents = SYMREF + name
  195. depth = 0
  196. refnames = []
  197. while contents.startswith(SYMREF):
  198. refname = contents[len(SYMREF):]
  199. refnames.append(refname)
  200. contents = self.read_ref(refname)
  201. if not contents:
  202. break
  203. depth += 1
  204. if depth > 5:
  205. raise KeyError(name)
  206. return refnames, contents
  207. def _follow(self, name):
  208. import warnings
  209. warnings.warn(
  210. "RefsContainer._follow is deprecated. Use RefsContainer.follow "
  211. "instead.", DeprecationWarning)
  212. refnames, contents = self.follow(name)
  213. if not refnames:
  214. return (None, contents)
  215. return (refnames[-1], contents)
  216. def __contains__(self, refname):
  217. if self.read_ref(refname):
  218. return True
  219. return False
  220. def __getitem__(self, name):
  221. """Get the SHA1 for a reference name.
  222. This method follows all symbolic references.
  223. """
  224. _, sha = self.follow(name)
  225. if sha is None:
  226. raise KeyError(name)
  227. return sha
  228. def set_if_equals(self, name, old_ref, new_ref, committer=None,
  229. timestamp=None, timezone=None, message=None):
  230. """Set a refname to new_ref only if it currently equals old_ref.
  231. This method follows all symbolic references if applicable for the
  232. subclass, and can be used to perform an atomic compare-and-swap
  233. operation.
  234. :param name: The refname to set.
  235. :param old_ref: The old sha the refname must refer to, or None to set
  236. unconditionally.
  237. :param new_ref: The new sha the refname will refer to.
  238. :param message: Message for reflog
  239. :return: True if the set was successful, False otherwise.
  240. """
  241. raise NotImplementedError(self.set_if_equals)
  242. def add_if_new(self, name, ref):
  243. """Add a new reference only if it does not already exist.
  244. :param name: Ref name
  245. :param ref: Ref value
  246. :param message: Message for reflog
  247. """
  248. raise NotImplementedError(self.add_if_new)
  249. def __setitem__(self, name, ref):
  250. """Set a reference name to point to the given SHA1.
  251. This method follows all symbolic references if applicable for the
  252. subclass.
  253. :note: This method unconditionally overwrites the contents of a
  254. reference. To update atomically only if the reference has not
  255. changed, use set_if_equals().
  256. :param name: The refname to set.
  257. :param ref: The new sha the refname will refer to.
  258. """
  259. self.set_if_equals(name, None, ref)
  260. def remove_if_equals(self, name, old_ref, committer=None,
  261. timestamp=None, timezone=None, message=None):
  262. """Remove a refname only if it currently equals old_ref.
  263. This method does not follow symbolic references, even if applicable for
  264. the subclass. It can be used to perform an atomic compare-and-delete
  265. operation.
  266. :param name: The refname to delete.
  267. :param old_ref: The old sha the refname must refer to, or None to
  268. delete unconditionally.
  269. :param message: Message for reflog
  270. :return: True if the delete was successful, False otherwise.
  271. """
  272. raise NotImplementedError(self.remove_if_equals)
  273. def __delitem__(self, name):
  274. """Remove a refname.
  275. This method does not follow symbolic references, even if applicable for
  276. the subclass.
  277. :note: This method unconditionally deletes the contents of a reference.
  278. To delete atomically only if the reference has not changed, use
  279. remove_if_equals().
  280. :param name: The refname to delete.
  281. """
  282. self.remove_if_equals(name, None)
  283. def get_symrefs(self):
  284. """Get a dict with all symrefs in this container.
  285. :return: Dictionary mapping source ref to target ref
  286. """
  287. ret = {}
  288. for src in self.allkeys():
  289. try:
  290. dst = parse_symref_value(self.read_ref(src))
  291. except ValueError:
  292. pass
  293. else:
  294. ret[src] = dst
  295. return ret
  296. class DictRefsContainer(RefsContainer):
  297. """RefsContainer backed by a simple dict.
  298. This container does not support symbolic or packed references and is not
  299. threadsafe.
  300. """
  301. def __init__(self, refs, logger=None):
  302. super(DictRefsContainer, self).__init__(logger=logger)
  303. self._refs = refs
  304. self._peeled = {}
  305. def allkeys(self):
  306. return self._refs.keys()
  307. def read_loose_ref(self, name):
  308. return self._refs.get(name, None)
  309. def get_packed_refs(self):
  310. return {}
  311. def set_symbolic_ref(self, name, other, committer=None,
  312. timestamp=None, timezone=None, message=None):
  313. old = self.follow(name)[-1]
  314. self._refs[name] = SYMREF + other
  315. self._log(name, old, old, committer=committer, timestamp=timestamp,
  316. timezone=timezone, message=message)
  317. def set_if_equals(self, name, old_ref, new_ref, committer=None,
  318. timestamp=None, timezone=None, message=None):
  319. if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref:
  320. return False
  321. realnames, _ = self.follow(name)
  322. for realname in realnames:
  323. self._check_refname(realname)
  324. old = self._refs.get(realname)
  325. self._refs[realname] = new_ref
  326. self._log(realname, old, new_ref, committer=committer,
  327. timestamp=timestamp, timezone=timezone, message=message)
  328. return True
  329. def add_if_new(self, name, ref, committer=None, timestamp=None,
  330. timezone=None, message=None):
  331. if name in self._refs:
  332. return False
  333. self._refs[name] = ref
  334. self._log(name, None, ref, committer=committer, timestamp=timestamp,
  335. timezone=timezone, message=message)
  336. return True
  337. def remove_if_equals(self, name, old_ref, committer=None, timestamp=None,
  338. timezone=None, message=None):
  339. if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref:
  340. return False
  341. try:
  342. old = self._refs.pop(name)
  343. except KeyError:
  344. pass
  345. else:
  346. self._log(name, old, None, committer=committer,
  347. timestamp=timestamp, timezone=timezone, message=message)
  348. return True
  349. def get_peeled(self, name):
  350. return self._peeled.get(name)
  351. def _update(self, refs):
  352. """Update multiple refs; intended only for testing."""
  353. # TODO(dborowitz): replace this with a public function that uses
  354. # set_if_equal.
  355. self._refs.update(refs)
  356. def _update_peeled(self, peeled):
  357. """Update cached peeled refs; intended only for testing."""
  358. self._peeled.update(peeled)
  359. class InfoRefsContainer(RefsContainer):
  360. """Refs container that reads refs from a info/refs file."""
  361. def __init__(self, f):
  362. self._refs = {}
  363. self._peeled = {}
  364. for l in f.readlines():
  365. sha, name = l.rstrip(b'\n').split(b'\t')
  366. if name.endswith(ANNOTATED_TAG_SUFFIX):
  367. name = name[:-3]
  368. if not check_ref_format(name):
  369. raise ValueError("invalid ref name %r" % name)
  370. self._peeled[name] = sha
  371. else:
  372. if not check_ref_format(name):
  373. raise ValueError("invalid ref name %r" % name)
  374. self._refs[name] = sha
  375. def allkeys(self):
  376. return self._refs.keys()
  377. def read_loose_ref(self, name):
  378. return self._refs.get(name, None)
  379. def get_packed_refs(self):
  380. return {}
  381. def get_peeled(self, name):
  382. try:
  383. return self._peeled[name]
  384. except KeyError:
  385. return self._refs[name]
  386. class DiskRefsContainer(RefsContainer):
  387. """Refs container that reads refs from disk."""
  388. def __init__(self, path, worktree_path=None, logger=None):
  389. super(DiskRefsContainer, self).__init__(logger=logger)
  390. if getattr(path, 'encode', None) is not None:
  391. path = path.encode(sys.getfilesystemencoding())
  392. self.path = path
  393. if worktree_path is None:
  394. worktree_path = path
  395. if getattr(worktree_path, 'encode', None) is not None:
  396. worktree_path = worktree_path.encode(sys.getfilesystemencoding())
  397. self.worktree_path = worktree_path
  398. self._packed_refs = None
  399. self._peeled_refs = None
  400. def __repr__(self):
  401. return "%s(%r)" % (self.__class__.__name__, self.path)
  402. def subkeys(self, base):
  403. subkeys = set()
  404. path = self.refpath(base)
  405. for root, unused_dirs, files in os.walk(path):
  406. dir = root[len(path):]
  407. if os.path.sep != '/':
  408. dir = dir.replace(os.path.sep.encode(
  409. sys.getfilesystemencoding()), b"/")
  410. dir = dir.strip(b'/')
  411. for filename in files:
  412. refname = b"/".join(([dir] if dir else []) + [filename])
  413. # check_ref_format requires at least one /, so we prepend the
  414. # base before calling it.
  415. if check_ref_format(base + b'/' + refname):
  416. subkeys.add(refname)
  417. for key in self.get_packed_refs():
  418. if key.startswith(base):
  419. subkeys.add(key[len(base):].strip(b'/'))
  420. return subkeys
  421. def allkeys(self):
  422. allkeys = set()
  423. if os.path.exists(self.refpath(b'HEAD')):
  424. allkeys.add(b'HEAD')
  425. path = self.refpath(b'')
  426. refspath = self.refpath(b'refs')
  427. for root, unused_dirs, files in os.walk(refspath):
  428. dir = root[len(path):]
  429. if os.path.sep != '/':
  430. dir = dir.replace(
  431. os.path.sep.encode(sys.getfilesystemencoding()), b"/")
  432. for filename in files:
  433. refname = b"/".join([dir, filename])
  434. if check_ref_format(refname):
  435. allkeys.add(refname)
  436. allkeys.update(self.get_packed_refs())
  437. return allkeys
  438. def refpath(self, name):
  439. """Return the disk path of a ref.
  440. """
  441. if os.path.sep != "/":
  442. name = name.replace(
  443. b"/",
  444. os.path.sep.encode(sys.getfilesystemencoding()))
  445. # TODO: as the 'HEAD' reference is working tree specific, it
  446. # should actually not be a part of RefsContainer
  447. if name == b'HEAD':
  448. return os.path.join(self.worktree_path, name)
  449. else:
  450. return os.path.join(self.path, name)
  451. def get_packed_refs(self):
  452. """Get contents of the packed-refs file.
  453. :return: Dictionary mapping ref names to SHA1s
  454. :note: Will return an empty dictionary when no packed-refs file is
  455. present.
  456. """
  457. # TODO: invalidate the cache on repacking
  458. if self._packed_refs is None:
  459. # set both to empty because we want _peeled_refs to be
  460. # None if and only if _packed_refs is also None.
  461. self._packed_refs = {}
  462. self._peeled_refs = {}
  463. path = os.path.join(self.path, b'packed-refs')
  464. try:
  465. f = GitFile(path, 'rb')
  466. except IOError as e:
  467. if e.errno == errno.ENOENT:
  468. return {}
  469. raise
  470. with f:
  471. first_line = next(iter(f)).rstrip()
  472. if (first_line.startswith(b'# pack-refs') and b' peeled' in
  473. first_line):
  474. for sha, name, peeled in read_packed_refs_with_peeled(f):
  475. self._packed_refs[name] = sha
  476. if peeled:
  477. self._peeled_refs[name] = peeled
  478. else:
  479. f.seek(0)
  480. for sha, name in read_packed_refs(f):
  481. self._packed_refs[name] = sha
  482. return self._packed_refs
  483. def get_peeled(self, name):
  484. """Return the cached peeled value of a ref, if available.
  485. :param name: Name of the ref to peel
  486. :return: The peeled value of the ref. If the ref is known not point to
  487. a tag, this will be the SHA the ref refers to. If the ref may point
  488. to a tag, but no cached information is available, None is returned.
  489. """
  490. self.get_packed_refs()
  491. if self._peeled_refs is None or name not in self._packed_refs:
  492. # No cache: no peeled refs were read, or this ref is loose
  493. return None
  494. if name in self._peeled_refs:
  495. return self._peeled_refs[name]
  496. else:
  497. # Known not peelable
  498. return self[name]
  499. def read_loose_ref(self, name):
  500. """Read a reference file and return its contents.
  501. If the reference file a symbolic reference, only read the first line of
  502. the file. Otherwise, only read the first 40 bytes.
  503. :param name: the refname to read, relative to refpath
  504. :return: The contents of the ref file, or None if the file does not
  505. exist.
  506. :raises IOError: if any other error occurs
  507. """
  508. filename = self.refpath(name)
  509. try:
  510. with GitFile(filename, 'rb') as f:
  511. header = f.read(len(SYMREF))
  512. if header == SYMREF:
  513. # Read only the first line
  514. return header + next(iter(f)).rstrip(b'\r\n')
  515. else:
  516. # Read only the first 40 bytes
  517. return header + f.read(40 - len(SYMREF))
  518. except IOError as e:
  519. if e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
  520. return None
  521. raise
  522. def _remove_packed_ref(self, name):
  523. if self._packed_refs is None:
  524. return
  525. filename = os.path.join(self.path, b'packed-refs')
  526. # reread cached refs from disk, while holding the lock
  527. f = GitFile(filename, 'wb')
  528. try:
  529. self._packed_refs = None
  530. self.get_packed_refs()
  531. if name not in self._packed_refs:
  532. return
  533. del self._packed_refs[name]
  534. if name in self._peeled_refs:
  535. del self._peeled_refs[name]
  536. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  537. f.close()
  538. finally:
  539. f.abort()
  540. def set_symbolic_ref(self, name, other, committer=None, timestamp=None,
  541. timezone=None, message=None):
  542. """Make a ref point at another ref.
  543. :param name: Name of the ref to set
  544. :param other: Name of the ref to point at
  545. :param message: Optional message to describe the change
  546. """
  547. self._check_refname(name)
  548. self._check_refname(other)
  549. filename = self.refpath(name)
  550. f = GitFile(filename, 'wb')
  551. try:
  552. f.write(SYMREF + other + b'\n')
  553. sha = self.follow(name)[-1]
  554. self._log(name, sha, sha, committer=committer,
  555. timestamp=timestamp, timezone=timezone,
  556. message=message)
  557. except BaseException:
  558. f.abort()
  559. raise
  560. else:
  561. f.close()
  562. def set_if_equals(self, name, old_ref, new_ref, committer=None,
  563. timestamp=None, timezone=None, message=None):
  564. """Set a refname to new_ref only if it currently equals old_ref.
  565. This method follows all symbolic references, and can be used to perform
  566. an atomic compare-and-swap operation.
  567. :param name: The refname to set.
  568. :param old_ref: The old sha the refname must refer to, or None to set
  569. unconditionally.
  570. :param new_ref: The new sha the refname will refer to.
  571. :param message: Set message for reflog
  572. :return: True if the set was successful, False otherwise.
  573. """
  574. self._check_refname(name)
  575. try:
  576. realnames, _ = self.follow(name)
  577. realname = realnames[-1]
  578. except (KeyError, IndexError):
  579. realname = name
  580. filename = self.refpath(realname)
  581. ensure_dir_exists(os.path.dirname(filename))
  582. with GitFile(filename, 'wb') as f:
  583. if old_ref is not None:
  584. try:
  585. # read again while holding the lock
  586. orig_ref = self.read_loose_ref(realname)
  587. if orig_ref is None:
  588. orig_ref = self.get_packed_refs().get(
  589. realname, ZERO_SHA)
  590. if orig_ref != old_ref:
  591. f.abort()
  592. return False
  593. except (OSError, IOError):
  594. f.abort()
  595. raise
  596. try:
  597. f.write(new_ref + b'\n')
  598. except (OSError, IOError):
  599. f.abort()
  600. raise
  601. self._log(realname, old_ref, new_ref, committer=committer,
  602. timestamp=timestamp, timezone=timezone, message=message)
  603. return True
  604. def add_if_new(self, name, ref, committer=None, timestamp=None,
  605. timezone=None, message=None):
  606. """Add a new reference only if it does not already exist.
  607. This method follows symrefs, and only ensures that the last ref in the
  608. chain does not exist.
  609. :param name: The refname to set.
  610. :param ref: The new sha the refname will refer to.
  611. :param message: Optional message for reflog
  612. :return: True if the add was successful, False otherwise.
  613. """
  614. try:
  615. realnames, contents = self.follow(name)
  616. if contents is not None:
  617. return False
  618. realname = realnames[-1]
  619. except (KeyError, IndexError):
  620. realname = name
  621. self._check_refname(realname)
  622. filename = self.refpath(realname)
  623. ensure_dir_exists(os.path.dirname(filename))
  624. with GitFile(filename, 'wb') as f:
  625. if os.path.exists(filename) or name in self.get_packed_refs():
  626. f.abort()
  627. return False
  628. try:
  629. f.write(ref + b'\n')
  630. except (OSError, IOError):
  631. f.abort()
  632. raise
  633. else:
  634. self._log(name, None, ref, committer=committer,
  635. timestamp=timestamp, timezone=timezone,
  636. message=message)
  637. return True
  638. def remove_if_equals(self, name, old_ref, committer=None, timestamp=None,
  639. timezone=None, message=None):
  640. """Remove a refname only if it currently equals old_ref.
  641. This method does not follow symbolic references. It can be used to
  642. perform an atomic compare-and-delete operation.
  643. :param name: The refname to delete.
  644. :param old_ref: The old sha the refname must refer to, or None to
  645. delete unconditionally.
  646. :param message: Optional message
  647. :return: True if the delete was successful, False otherwise.
  648. """
  649. self._check_refname(name)
  650. filename = self.refpath(name)
  651. ensure_dir_exists(os.path.dirname(filename))
  652. f = GitFile(filename, 'wb')
  653. try:
  654. if old_ref is not None:
  655. orig_ref = self.read_loose_ref(name)
  656. if orig_ref is None:
  657. orig_ref = self.get_packed_refs().get(name, ZERO_SHA)
  658. if orig_ref != old_ref:
  659. return False
  660. # remove the reference file itself
  661. try:
  662. os.remove(filename)
  663. except OSError as e:
  664. if e.errno != errno.ENOENT: # may only be packed
  665. raise
  666. self._remove_packed_ref(name)
  667. self._log(name, old_ref, None, committer=committer,
  668. timestamp=timestamp, timezone=timezone, message=message)
  669. finally:
  670. # never write, we just wanted the lock
  671. f.abort()
  672. # outside of the lock, clean-up any parent directory that might now
  673. # be empty. this ensures that re-creating a reference of the same
  674. # name of what was previously a directory works as expected
  675. parent = name
  676. while True:
  677. try:
  678. parent, _ = parent.rsplit(b'/', 1)
  679. except ValueError:
  680. break
  681. parent_filename = self.refpath(parent)
  682. try:
  683. os.rmdir(parent_filename)
  684. except OSError:
  685. # this can be caused by the parent directory being
  686. # removed by another process, being not empty, etc.
  687. # in any case, this is non fatal because we already
  688. # removed the reference, just ignore it
  689. break
  690. return True
  691. def _split_ref_line(line):
  692. """Split a single ref line into a tuple of SHA1 and name."""
  693. fields = line.rstrip(b'\n\r').split(b' ')
  694. if len(fields) != 2:
  695. raise PackedRefsException("invalid ref line %r" % line)
  696. sha, name = fields
  697. if not valid_hexsha(sha):
  698. raise PackedRefsException("Invalid hex sha %r" % sha)
  699. if not check_ref_format(name):
  700. raise PackedRefsException("invalid ref name %r" % name)
  701. return (sha, name)
  702. def read_packed_refs(f):
  703. """Read a packed refs file.
  704. :param f: file-like object to read from
  705. :return: Iterator over tuples with SHA1s and ref names.
  706. """
  707. for l in f:
  708. if l.startswith(b'#'):
  709. # Comment
  710. continue
  711. if l.startswith(b'^'):
  712. raise PackedRefsException(
  713. "found peeled ref in packed-refs without peeled")
  714. yield _split_ref_line(l)
  715. def read_packed_refs_with_peeled(f):
  716. """Read a packed refs file including peeled refs.
  717. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  718. with ref names, SHA1s, and peeled SHA1s (or None).
  719. :param f: file-like object to read from, seek'ed to the second line
  720. """
  721. last = None
  722. for line in f:
  723. if line[0] == b'#':
  724. continue
  725. line = line.rstrip(b'\r\n')
  726. if line.startswith(b'^'):
  727. if not last:
  728. raise PackedRefsException("unexpected peeled ref line")
  729. if not valid_hexsha(line[1:]):
  730. raise PackedRefsException("Invalid hex sha %r" % line[1:])
  731. sha, name = _split_ref_line(last)
  732. last = None
  733. yield (sha, name, line[1:])
  734. else:
  735. if last:
  736. sha, name = _split_ref_line(last)
  737. yield (sha, name, None)
  738. last = line
  739. if last:
  740. sha, name = _split_ref_line(last)
  741. yield (sha, name, None)
  742. def write_packed_refs(f, packed_refs, peeled_refs=None):
  743. """Write a packed refs file.
  744. :param f: empty file-like object to write to
  745. :param packed_refs: dict of refname to sha of packed refs to write
  746. :param peeled_refs: dict of refname to peeled value of sha
  747. """
  748. if peeled_refs is None:
  749. peeled_refs = {}
  750. else:
  751. f.write(b'# pack-refs with: peeled\n')
  752. for refname in sorted(packed_refs.keys()):
  753. f.write(git_line(packed_refs[refname], refname))
  754. if refname in peeled_refs:
  755. f.write(b'^' + peeled_refs[refname] + b'\n')
  756. def read_info_refs(f):
  757. ret = {}
  758. for l in f.readlines():
  759. (sha, name) = l.rstrip(b"\r\n").split(b"\t", 1)
  760. ret[name] = sha
  761. return ret
  762. def write_info_refs(refs, store):
  763. """Generate info refs."""
  764. for name, sha in sorted(refs.items()):
  765. # get_refs() includes HEAD as a special case, but we don't want to
  766. # advertise it
  767. if name == b'HEAD':
  768. continue
  769. try:
  770. o = store[sha]
  771. except KeyError:
  772. continue
  773. peeled = store.peel_sha(sha)
  774. yield o.id + b'\t' + name + b'\n'
  775. if o.id != peeled.id:
  776. yield peeled.id + b'\t' + name + ANNOTATED_TAG_SUFFIX + b'\n'
  777. def is_local_branch(x):
  778. return x.startswith(LOCAL_BRANCH_PREFIX)
  779. def strip_peeled_refs(refs):
  780. """Remove all peeled refs"""
  781. return {ref: sha for (ref, sha) in refs.items()
  782. if not ref.endswith(ANNOTATED_TAG_SUFFIX)}