refs.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. # refs.py -- For dealing with git refs
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) any later version of
  8. # the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Ref handling.
  20. """
  21. import errno
  22. import os
  23. from dulwich.errors import (
  24. PackedRefsException,
  25. RefFormatError,
  26. )
  27. from dulwich.objects import (
  28. hex_to_sha,
  29. git_line,
  30. )
  31. from dulwich.file import (
  32. GitFile,
  33. ensure_dir_exists,
  34. )
  35. from dulwich._py3_compat import (
  36. iterbytes,
  37. items,
  38. )
  39. SYMREF = b'ref: '
  40. LOCAL_BRANCH_PREFIX = b'refs/heads/'
  41. BAD_REF_CHARS = set(iterbytes(b'\177 ~^:?*['))
  42. def check_ref_format(refname):
  43. """Check if a refname is correctly formatted.
  44. Implements all the same rules as git-check-ref-format[1].
  45. [1] http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  46. :param refname: The refname to check
  47. :return: True if refname is valid, False otherwise
  48. """
  49. # These could be combined into one big expression, but are listed separately
  50. # to parallel [1].
  51. if b'/.' in refname or refname.startswith(b'.'):
  52. return False
  53. if b'/' not in refname:
  54. return False
  55. if b'..' in refname:
  56. return False
  57. for c in iterbytes(refname):
  58. if c < 0o40 or c in BAD_REF_CHARS:
  59. return False
  60. if refname[-1] in b'/.':
  61. return False
  62. if refname.endswith(b'.lock'):
  63. return False
  64. if b'@{' in refname:
  65. return False
  66. if b'\\' in refname:
  67. return False
  68. return True
  69. class RefsContainer(object):
  70. """A container for refs."""
  71. def set_symbolic_ref(self, name, other):
  72. """Make a ref point at another ref.
  73. :param name: Name of the ref to set
  74. :param other: Name of the ref to point at
  75. """
  76. raise NotImplementedError(self.set_symbolic_ref)
  77. def get_packed_refs(self):
  78. """Get contents of the packed-refs file.
  79. :return: Dictionary mapping ref names to SHA1s
  80. :note: Will return an empty dictionary when no packed-refs file is
  81. present.
  82. """
  83. raise NotImplementedError(self.get_packed_refs)
  84. def get_peeled(self, name):
  85. """Return the cached peeled value of a ref, if available.
  86. :param name: Name of the ref to peel
  87. :return: The peeled value of the ref. If the ref is known not point to a
  88. tag, this will be the SHA the ref refers to. If the ref may point to
  89. a tag, but no cached information is available, None is returned.
  90. """
  91. return None
  92. def import_refs(self, base, other):
  93. for name, value in items(other):
  94. self[b'/'.join((base, name))] = value
  95. def allkeys(self):
  96. """All refs present in this container."""
  97. raise NotImplementedError(self.allkeys)
  98. def keys(self, base=None):
  99. """Refs present in this container.
  100. :param base: An optional base to return refs under.
  101. :return: An unsorted set of valid refs in this container, including
  102. packed refs.
  103. """
  104. if base is not None:
  105. return self.subkeys(base)
  106. else:
  107. return self.allkeys()
  108. def subkeys(self, base):
  109. """Refs present in this container under a base.
  110. :param base: The base to return refs under.
  111. :return: A set of valid refs in this container under the base; the base
  112. prefix is stripped from the ref names returned.
  113. """
  114. keys = set()
  115. base_len = len(base) + 1
  116. for refname in self.allkeys():
  117. if refname.startswith(base):
  118. keys.add(refname[base_len:])
  119. return keys
  120. def as_dict(self, base=None):
  121. """Return the contents of this container as a dictionary.
  122. """
  123. ret = {}
  124. keys = self.keys(base)
  125. if base is None:
  126. base = b''
  127. for key in keys:
  128. try:
  129. ret[key] = self[(base + b'/' + key).strip(b'/')]
  130. except KeyError:
  131. continue # Unable to resolve
  132. return ret
  133. def _check_refname(self, name):
  134. """Ensure a refname is valid and lives in refs or is HEAD.
  135. HEAD is not a valid refname according to git-check-ref-format, but this
  136. class needs to be able to touch HEAD. Also, check_ref_format expects
  137. refnames without the leading 'refs/', but this class requires that
  138. so it cannot touch anything outside the refs dir (or HEAD).
  139. :param name: The name of the reference.
  140. :raises KeyError: if a refname is not HEAD or is otherwise not valid.
  141. """
  142. if name in (b'HEAD', b'refs/stash'):
  143. return
  144. if not name.startswith(b'refs/') or not check_ref_format(name[5:]):
  145. raise RefFormatError(name)
  146. def read_ref(self, refname):
  147. """Read a reference without following any references.
  148. :param refname: The name of the reference
  149. :return: The contents of the ref file, or None if it does
  150. not exist.
  151. """
  152. contents = self.read_loose_ref(refname)
  153. if not contents:
  154. contents = self.get_packed_refs().get(refname, None)
  155. return contents
  156. def read_loose_ref(self, name):
  157. """Read a loose reference and return its contents.
  158. :param name: the refname to read
  159. :return: The contents of the ref file, or None if it does
  160. not exist.
  161. """
  162. raise NotImplementedError(self.read_loose_ref)
  163. def _follow(self, name):
  164. """Follow a reference name.
  165. :return: a tuple of (refname, sha), where refname is the name of the
  166. last reference in the symbolic reference chain
  167. """
  168. contents = SYMREF + name
  169. depth = 0
  170. while contents.startswith(SYMREF):
  171. refname = contents[len(SYMREF):]
  172. contents = self.read_ref(refname)
  173. if not contents:
  174. break
  175. depth += 1
  176. if depth > 5:
  177. raise KeyError(name)
  178. return refname, contents
  179. def __contains__(self, refname):
  180. if self.read_ref(refname):
  181. return True
  182. return False
  183. def __getitem__(self, name):
  184. """Get the SHA1 for a reference name.
  185. This method follows all symbolic references.
  186. """
  187. _, sha = self._follow(name)
  188. if sha is None:
  189. raise KeyError(name)
  190. return sha
  191. def set_if_equals(self, name, old_ref, new_ref):
  192. """Set a refname to new_ref only if it currently equals old_ref.
  193. This method follows all symbolic references if applicable for the
  194. subclass, and can be used to perform an atomic compare-and-swap
  195. operation.
  196. :param name: The refname to set.
  197. :param old_ref: The old sha the refname must refer to, or None to set
  198. unconditionally.
  199. :param new_ref: The new sha the refname will refer to.
  200. :return: True if the set was successful, False otherwise.
  201. """
  202. raise NotImplementedError(self.set_if_equals)
  203. def add_if_new(self, name, ref):
  204. """Add a new reference only if it does not already exist."""
  205. raise NotImplementedError(self.add_if_new)
  206. def __setitem__(self, name, ref):
  207. """Set a reference name to point to the given SHA1.
  208. This method follows all symbolic references if applicable for the
  209. subclass.
  210. :note: This method unconditionally overwrites the contents of a
  211. reference. To update atomically only if the reference has not
  212. changed, use set_if_equals().
  213. :param name: The refname to set.
  214. :param ref: The new sha the refname will refer to.
  215. """
  216. self.set_if_equals(name, None, ref)
  217. def remove_if_equals(self, name, old_ref):
  218. """Remove a refname only if it currently equals old_ref.
  219. This method does not follow symbolic references, even if applicable for
  220. the subclass. It can be used to perform an atomic compare-and-delete
  221. operation.
  222. :param name: The refname to delete.
  223. :param old_ref: The old sha the refname must refer to, or None to delete
  224. unconditionally.
  225. :return: True if the delete was successful, False otherwise.
  226. """
  227. raise NotImplementedError(self.remove_if_equals)
  228. def __delitem__(self, name):
  229. """Remove a refname.
  230. This method does not follow symbolic references, even if applicable for
  231. the subclass.
  232. :note: This method unconditionally deletes the contents of a reference.
  233. To delete atomically only if the reference has not changed, use
  234. remove_if_equals().
  235. :param name: The refname to delete.
  236. """
  237. self.remove_if_equals(name, None)
  238. class DictRefsContainer(RefsContainer):
  239. """RefsContainer backed by a simple dict.
  240. This container does not support symbolic or packed references and is not
  241. threadsafe.
  242. """
  243. def __init__(self, refs):
  244. self._refs = refs
  245. self._peeled = {}
  246. def allkeys(self):
  247. return self._refs.keys()
  248. def read_loose_ref(self, name):
  249. return self._refs.get(name, None)
  250. def get_packed_refs(self):
  251. return {}
  252. def set_symbolic_ref(self, name, other):
  253. self._refs[name] = SYMREF + other
  254. def set_if_equals(self, name, old_ref, new_ref):
  255. if old_ref is not None and self._refs.get(name, None) != old_ref:
  256. return False
  257. realname, _ = self._follow(name)
  258. self._check_refname(realname)
  259. self._refs[realname] = new_ref
  260. return True
  261. def add_if_new(self, name, ref):
  262. if name in self._refs:
  263. return False
  264. self._refs[name] = ref
  265. return True
  266. def remove_if_equals(self, name, old_ref):
  267. if old_ref is not None and self._refs.get(name, None) != old_ref:
  268. return False
  269. del self._refs[name]
  270. return True
  271. def get_peeled(self, name):
  272. return self._peeled.get(name)
  273. def _update(self, refs):
  274. """Update multiple refs; intended only for testing."""
  275. # TODO(dborowitz): replace this with a public function that uses
  276. # set_if_equal.
  277. self._refs.update(refs)
  278. def _update_peeled(self, peeled):
  279. """Update cached peeled refs; intended only for testing."""
  280. self._peeled.update(peeled)
  281. class InfoRefsContainer(RefsContainer):
  282. """Refs container that reads refs from a info/refs file."""
  283. def __init__(self, f):
  284. self._refs = {}
  285. self._peeled = {}
  286. for l in f.readlines():
  287. sha, name = l.rstrip(b'\n').split(b'\t')
  288. if name.endswith(b'^{}'):
  289. name = name[:-3]
  290. if not check_ref_format(name):
  291. raise ValueError("invalid ref name %r" % name)
  292. self._peeled[name] = sha
  293. else:
  294. if not check_ref_format(name):
  295. raise ValueError("invalid ref name %r" % name)
  296. self._refs[name] = sha
  297. def allkeys(self):
  298. return self._refs.keys()
  299. def read_loose_ref(self, name):
  300. return self._refs.get(name, None)
  301. def get_packed_refs(self):
  302. return {}
  303. def get_peeled(self, name):
  304. try:
  305. return self._peeled[name]
  306. except KeyError:
  307. return self._refs[name]
  308. class DiskRefsContainer(RefsContainer):
  309. """Refs container that reads refs from disk."""
  310. def __init__(self, path):
  311. self.path = path
  312. self._packed_refs = None
  313. self._peeled_refs = None
  314. def __repr__(self):
  315. return "%s(%r)" % (self.__class__.__name__, self.path)
  316. def subkeys(self, base):
  317. subkeys = set()
  318. path = self.refpath(base)
  319. for root, dirs, files in os.walk(path):
  320. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  321. for filename in files:
  322. refname = (("%s/%s" % (dir, filename))
  323. .strip("/").encode('ascii'))
  324. # check_ref_format requires at least one /, so we prepend the
  325. # base before calling it.
  326. if check_ref_format(base + b'/' + refname):
  327. subkeys.add(refname)
  328. for key in self.get_packed_refs():
  329. if key.startswith(base):
  330. subkeys.add(key[len(base):].strip(b'/'))
  331. return subkeys
  332. def allkeys(self):
  333. allkeys = set()
  334. if os.path.exists(self.refpath(b'HEAD')):
  335. allkeys.add(b'HEAD')
  336. path = self.refpath(b'')
  337. for root, dirs, files in os.walk(self.refpath(b'refs')):
  338. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  339. for filename in files:
  340. refname = ("%s/%s" % (dir, filename)).strip("/").encode('ascii')
  341. if check_ref_format(refname):
  342. allkeys.add(refname)
  343. allkeys.update(self.get_packed_refs())
  344. return allkeys
  345. def refpath(self, name):
  346. """Return the disk path of a ref.
  347. """
  348. name = name.decode('ascii')
  349. if os.path.sep != "/":
  350. name = name.replace("/", os.path.sep)
  351. return os.path.join(self.path, name)
  352. def get_packed_refs(self):
  353. """Get contents of the packed-refs file.
  354. :return: Dictionary mapping ref names to SHA1s
  355. :note: Will return an empty dictionary when no packed-refs file is
  356. present.
  357. """
  358. # TODO: invalidate the cache on repacking
  359. if self._packed_refs is None:
  360. # set both to empty because we want _peeled_refs to be
  361. # None if and only if _packed_refs is also None.
  362. self._packed_refs = {}
  363. self._peeled_refs = {}
  364. path = os.path.join(self.path, 'packed-refs')
  365. try:
  366. f = GitFile(path, 'rb')
  367. except IOError as e:
  368. if e.errno == errno.ENOENT:
  369. return {}
  370. raise
  371. with f:
  372. first_line = next(iter(f)).rstrip()
  373. if (first_line.startswith(b'# pack-refs') and b' peeled' in
  374. first_line):
  375. for sha, name, peeled in read_packed_refs_with_peeled(f):
  376. self._packed_refs[name] = sha
  377. if peeled:
  378. self._peeled_refs[name] = peeled
  379. else:
  380. f.seek(0)
  381. for sha, name in read_packed_refs(f):
  382. self._packed_refs[name] = sha
  383. return self._packed_refs
  384. def get_peeled(self, name):
  385. """Return the cached peeled value of a ref, if available.
  386. :param name: Name of the ref to peel
  387. :return: The peeled value of the ref. If the ref is known not point to a
  388. tag, this will be the SHA the ref refers to. If the ref may point to
  389. a tag, but no cached information is available, None is returned.
  390. """
  391. self.get_packed_refs()
  392. if self._peeled_refs is None or name not in self._packed_refs:
  393. # No cache: no peeled refs were read, or this ref is loose
  394. return None
  395. if name in self._peeled_refs:
  396. return self._peeled_refs[name]
  397. else:
  398. # Known not peelable
  399. return self[name]
  400. def read_loose_ref(self, name):
  401. """Read a reference file and return its contents.
  402. If the reference file a symbolic reference, only read the first line of
  403. the file. Otherwise, only read the first 40 bytes.
  404. :param name: the refname to read, relative to refpath
  405. :return: The contents of the ref file, or None if the file does not
  406. exist.
  407. :raises IOError: if any other error occurs
  408. """
  409. filename = self.refpath(name)
  410. try:
  411. with GitFile(filename, 'rb') as f:
  412. header = f.read(len(SYMREF))
  413. if header == SYMREF:
  414. # Read only the first line
  415. return header + next(iter(f)).rstrip(b'\r\n')
  416. else:
  417. # Read only the first 40 bytes
  418. return header + f.read(40 - len(SYMREF))
  419. except IOError as e:
  420. if e.errno == errno.ENOENT:
  421. return None
  422. raise
  423. def _remove_packed_ref(self, name):
  424. if self._packed_refs is None:
  425. return
  426. filename = os.path.join(self.path, 'packed-refs')
  427. # reread cached refs from disk, while holding the lock
  428. f = GitFile(filename, 'wb')
  429. try:
  430. self._packed_refs = None
  431. self.get_packed_refs()
  432. if name not in self._packed_refs:
  433. return
  434. del self._packed_refs[name]
  435. if name in self._peeled_refs:
  436. del self._peeled_refs[name]
  437. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  438. f.close()
  439. finally:
  440. f.abort()
  441. def set_symbolic_ref(self, name, other):
  442. """Make a ref point at another ref.
  443. :param name: Name of the ref to set
  444. :param other: Name of the ref to point at
  445. """
  446. self._check_refname(name)
  447. self._check_refname(other)
  448. filename = self.refpath(name)
  449. try:
  450. f = GitFile(filename, 'wb')
  451. try:
  452. f.write(SYMREF + other + b'\n')
  453. except (IOError, OSError):
  454. f.abort()
  455. raise
  456. finally:
  457. f.close()
  458. def set_if_equals(self, name, old_ref, new_ref):
  459. """Set a refname to new_ref only if it currently equals old_ref.
  460. This method follows all symbolic references, and can be used to perform
  461. an atomic compare-and-swap operation.
  462. :param name: The refname to set.
  463. :param old_ref: The old sha the refname must refer to, or None to set
  464. unconditionally.
  465. :param new_ref: The new sha the refname will refer to.
  466. :return: True if the set was successful, False otherwise.
  467. """
  468. self._check_refname(name)
  469. try:
  470. realname, _ = self._follow(name)
  471. except KeyError:
  472. realname = name
  473. filename = self.refpath(realname)
  474. ensure_dir_exists(os.path.dirname(filename))
  475. with GitFile(filename, 'wb') as f:
  476. if old_ref is not None:
  477. try:
  478. # read again while holding the lock
  479. orig_ref = self.read_loose_ref(realname)
  480. if orig_ref is None:
  481. orig_ref = self.get_packed_refs().get(realname, None)
  482. if orig_ref != old_ref:
  483. f.abort()
  484. return False
  485. except (OSError, IOError):
  486. f.abort()
  487. raise
  488. try:
  489. f.write(new_ref + b'\n')
  490. except (OSError, IOError):
  491. f.abort()
  492. raise
  493. return True
  494. def add_if_new(self, name, ref):
  495. """Add a new reference only if it does not already exist.
  496. This method follows symrefs, and only ensures that the last ref in the
  497. chain does not exist.
  498. :param name: The refname to set.
  499. :param ref: The new sha the refname will refer to.
  500. :return: True if the add was successful, False otherwise.
  501. """
  502. try:
  503. realname, contents = self._follow(name)
  504. if contents is not None:
  505. return False
  506. except KeyError:
  507. realname = name
  508. self._check_refname(realname)
  509. filename = self.refpath(realname)
  510. ensure_dir_exists(os.path.dirname(filename))
  511. with GitFile(filename, 'wb') as f:
  512. if os.path.exists(filename) or name in self.get_packed_refs():
  513. f.abort()
  514. return False
  515. try:
  516. f.write(ref + b'\n')
  517. except (OSError, IOError):
  518. f.abort()
  519. raise
  520. return True
  521. def remove_if_equals(self, name, old_ref):
  522. """Remove a refname only if it currently equals old_ref.
  523. This method does not follow symbolic references. It can be used to
  524. perform an atomic compare-and-delete operation.
  525. :param name: The refname to delete.
  526. :param old_ref: The old sha the refname must refer to, or None to delete
  527. unconditionally.
  528. :return: True if the delete was successful, False otherwise.
  529. """
  530. self._check_refname(name)
  531. filename = self.refpath(name)
  532. ensure_dir_exists(os.path.dirname(filename))
  533. f = GitFile(filename, 'wb')
  534. try:
  535. if old_ref is not None:
  536. orig_ref = self.read_loose_ref(name)
  537. if orig_ref is None:
  538. orig_ref = self.get_packed_refs().get(name, None)
  539. if orig_ref != old_ref:
  540. return False
  541. # may only be packed
  542. try:
  543. os.remove(filename)
  544. except OSError as e:
  545. if e.errno != errno.ENOENT:
  546. raise
  547. self._remove_packed_ref(name)
  548. finally:
  549. # never write, we just wanted the lock
  550. f.abort()
  551. return True
  552. def _split_ref_line(line):
  553. """Split a single ref line into a tuple of SHA1 and name."""
  554. fields = line.rstrip(b'\n').split(b' ')
  555. if len(fields) != 2:
  556. raise PackedRefsException("invalid ref line %r" % line)
  557. sha, name = fields
  558. try:
  559. hex_to_sha(sha)
  560. except (AssertionError, TypeError) as e:
  561. raise PackedRefsException(e)
  562. if not check_ref_format(name):
  563. raise PackedRefsException("invalid ref name %r" % name)
  564. return (sha, name)
  565. def read_packed_refs(f):
  566. """Read a packed refs file.
  567. :param f: file-like object to read from
  568. :return: Iterator over tuples with SHA1s and ref names.
  569. """
  570. for l in f:
  571. if l.startswith(b'#'):
  572. # Comment
  573. continue
  574. if l.startswith(b'^'):
  575. raise PackedRefsException(
  576. "found peeled ref in packed-refs without peeled")
  577. yield _split_ref_line(l)
  578. def read_packed_refs_with_peeled(f):
  579. """Read a packed refs file including peeled refs.
  580. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  581. with ref names, SHA1s, and peeled SHA1s (or None).
  582. :param f: file-like object to read from, seek'ed to the second line
  583. """
  584. last = None
  585. for l in f:
  586. if l[0] == b'#':
  587. continue
  588. l = l.rstrip(b'\r\n')
  589. if l.startswith(b'^'):
  590. if not last:
  591. raise PackedRefsException("unexpected peeled ref line")
  592. try:
  593. hex_to_sha(l[1:])
  594. except (AssertionError, TypeError) as e:
  595. raise PackedRefsException(e)
  596. sha, name = _split_ref_line(last)
  597. last = None
  598. yield (sha, name, l[1:])
  599. else:
  600. if last:
  601. sha, name = _split_ref_line(last)
  602. yield (sha, name, None)
  603. last = l
  604. if last:
  605. sha, name = _split_ref_line(last)
  606. yield (sha, name, None)
  607. def write_packed_refs(f, packed_refs, peeled_refs=None):
  608. """Write a packed refs file.
  609. :param f: empty file-like object to write to
  610. :param packed_refs: dict of refname to sha of packed refs to write
  611. :param peeled_refs: dict of refname to peeled value of sha
  612. """
  613. if peeled_refs is None:
  614. peeled_refs = {}
  615. else:
  616. f.write(b'# pack-refs with: peeled\n')
  617. for refname in sorted(packed_refs.keys()):
  618. f.write(git_line(packed_refs[refname], refname))
  619. if refname in peeled_refs:
  620. f.write(b'^' + peeled_refs[refname] + b'\n')
  621. def read_info_refs(f):
  622. ret = {}
  623. for l in f.readlines():
  624. (sha, name) = l.rstrip("\r\n").split("\t", 1)
  625. ret[name] = sha
  626. return ret
  627. def write_info_refs(refs, store):
  628. """Generate info refs."""
  629. for name, sha in sorted(refs.items()):
  630. # get_refs() includes HEAD as a special case, but we don't want to
  631. # advertise it
  632. if name == b'HEAD':
  633. continue
  634. try:
  635. o = store[sha]
  636. except KeyError:
  637. continue
  638. peeled = store.peel_sha(sha)
  639. yield o.id + b'\t' + name + b'\n'
  640. if o.id != peeled.id:
  641. yield peeled.id + b'\t' + name + b'^{}\n'
  642. is_local_branch = lambda x: x.startswith(b'refs/heads/')