refs.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. import sys
  24. from dulwich.errors import (
  25. PackedRefsException,
  26. RefFormatError,
  27. )
  28. from dulwich.objects import (
  29. git_line,
  30. valid_hexsha,
  31. )
  32. from dulwich.file import (
  33. GitFile,
  34. ensure_dir_exists,
  35. )
  36. SYMREF = b'ref: '
  37. LOCAL_BRANCH_PREFIX = b'refs/heads/'
  38. BAD_REF_CHARS = set(b'\177 ~^:?*[')
  39. def check_ref_format(refname):
  40. """Check if a refname is correctly formatted.
  41. Implements all the same rules as git-check-ref-format[1].
  42. [1] http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  43. :param refname: The refname to check
  44. :return: True if refname is valid, False otherwise
  45. """
  46. # These could be combined into one big expression, but are listed separately
  47. # to parallel [1].
  48. if b'/.' in refname or refname.startswith(b'.'):
  49. return False
  50. if b'/' not in refname:
  51. return False
  52. if b'..' in refname:
  53. return False
  54. for i, c in enumerate(refname):
  55. if ord(refname[i:i+1]) < 0o40 or c in BAD_REF_CHARS:
  56. return False
  57. if refname[-1] in b'/.':
  58. return False
  59. if refname.endswith(b'.lock'):
  60. return False
  61. if b'@{' in refname:
  62. return False
  63. if b'\\' in refname:
  64. return False
  65. return True
  66. class RefsContainer(object):
  67. """A container for refs."""
  68. def set_symbolic_ref(self, name, other):
  69. """Make a ref point at another ref.
  70. :param name: Name of the ref to set
  71. :param other: Name of the ref to point at
  72. """
  73. raise NotImplementedError(self.set_symbolic_ref)
  74. def get_packed_refs(self):
  75. """Get contents of the packed-refs file.
  76. :return: Dictionary mapping ref names to SHA1s
  77. :note: Will return an empty dictionary when no packed-refs file is
  78. present.
  79. """
  80. raise NotImplementedError(self.get_packed_refs)
  81. def get_peeled(self, name):
  82. """Return the cached peeled value of a ref, if available.
  83. :param name: Name of the ref to peel
  84. :return: The peeled value of the ref. If the ref is known not point to a
  85. tag, this will be the SHA the ref refers to. If the ref may point to
  86. a tag, but no cached information is available, None is returned.
  87. """
  88. return None
  89. def import_refs(self, base, other):
  90. for name, value in other.items():
  91. self[b'/'.join((base, name))] = value
  92. def allkeys(self):
  93. """All refs present in this container."""
  94. raise NotImplementedError(self.allkeys)
  95. def keys(self, base=None):
  96. """Refs present in this container.
  97. :param base: An optional base to return refs under.
  98. :return: An unsorted set of valid refs in this container, including
  99. packed refs.
  100. """
  101. if base is not None:
  102. return self.subkeys(base)
  103. else:
  104. return self.allkeys()
  105. def subkeys(self, base):
  106. """Refs present in this container under a base.
  107. :param base: The base to return refs under.
  108. :return: A set of valid refs in this container under the base; the base
  109. prefix is stripped from the ref names returned.
  110. """
  111. keys = set()
  112. base_len = len(base) + 1
  113. for refname in self.allkeys():
  114. if refname.startswith(base):
  115. keys.add(refname[base_len:])
  116. return keys
  117. def as_dict(self, base=None):
  118. """Return the contents of this container as a dictionary.
  119. """
  120. ret = {}
  121. keys = self.keys(base)
  122. if base is None:
  123. base = b''
  124. else:
  125. base = base.rstrip(b'/')
  126. for key in keys:
  127. try:
  128. ret[key] = self[(base + b'/' + key).strip(b'/')]
  129. except KeyError:
  130. continue # Unable to resolve
  131. return ret
  132. def _check_refname(self, name):
  133. """Ensure a refname is valid and lives in refs or is HEAD.
  134. HEAD is not a valid refname according to git-check-ref-format, but this
  135. class needs to be able to touch HEAD. Also, check_ref_format expects
  136. refnames without the leading 'refs/', but this class requires that
  137. so it cannot touch anything outside the refs dir (or HEAD).
  138. :param name: The name of the reference.
  139. :raises KeyError: if a refname is not HEAD or is otherwise not valid.
  140. """
  141. if name in (b'HEAD', b'refs/stash'):
  142. return
  143. if not name.startswith(b'refs/') or not check_ref_format(name[5:]):
  144. raise RefFormatError(name)
  145. def read_ref(self, refname):
  146. """Read a reference without following any references.
  147. :param refname: The name of the reference
  148. :return: The contents of the ref file, or None if it does
  149. not exist.
  150. """
  151. contents = self.read_loose_ref(refname)
  152. if not contents:
  153. contents = self.get_packed_refs().get(refname, None)
  154. return contents
  155. def read_loose_ref(self, name):
  156. """Read a loose reference and return its contents.
  157. :param name: the refname to read
  158. :return: The contents of the ref file, or None if it does
  159. not exist.
  160. """
  161. raise NotImplementedError(self.read_loose_ref)
  162. def _follow(self, name):
  163. """Follow a reference name.
  164. :return: a tuple of (refname, sha), where refname is the name of the
  165. last reference in the symbolic reference chain
  166. """
  167. contents = SYMREF + name
  168. depth = 0
  169. while contents.startswith(SYMREF):
  170. refname = contents[len(SYMREF):]
  171. contents = self.read_ref(refname)
  172. if not contents:
  173. break
  174. depth += 1
  175. if depth > 5:
  176. raise KeyError(name)
  177. return refname, contents
  178. def __contains__(self, refname):
  179. if self.read_ref(refname):
  180. return True
  181. return False
  182. def __getitem__(self, name):
  183. """Get the SHA1 for a reference name.
  184. This method follows all symbolic references.
  185. """
  186. _, sha = self._follow(name)
  187. if sha is None:
  188. raise KeyError(name)
  189. return sha
  190. def set_if_equals(self, name, old_ref, new_ref):
  191. """Set a refname to new_ref only if it currently equals old_ref.
  192. This method follows all symbolic references if applicable for the
  193. subclass, and can be used to perform an atomic compare-and-swap
  194. operation.
  195. :param name: The refname to set.
  196. :param old_ref: The old sha the refname must refer to, or None to set
  197. unconditionally.
  198. :param new_ref: The new sha the refname will refer to.
  199. :return: True if the set was successful, False otherwise.
  200. """
  201. raise NotImplementedError(self.set_if_equals)
  202. def add_if_new(self, name, ref):
  203. """Add a new reference only if it does not already exist."""
  204. raise NotImplementedError(self.add_if_new)
  205. def __setitem__(self, name, ref):
  206. """Set a reference name to point to the given SHA1.
  207. This method follows all symbolic references if applicable for the
  208. subclass.
  209. :note: This method unconditionally overwrites the contents of a
  210. reference. To update atomically only if the reference has not
  211. changed, use set_if_equals().
  212. :param name: The refname to set.
  213. :param ref: The new sha the refname will refer to.
  214. """
  215. self.set_if_equals(name, None, ref)
  216. def remove_if_equals(self, name, old_ref):
  217. """Remove a refname only if it currently equals old_ref.
  218. This method does not follow symbolic references, even if applicable for
  219. the subclass. It can be used to perform an atomic compare-and-delete
  220. operation.
  221. :param name: The refname to delete.
  222. :param old_ref: The old sha the refname must refer to, or None to delete
  223. unconditionally.
  224. :return: True if the delete was successful, False otherwise.
  225. """
  226. raise NotImplementedError(self.remove_if_equals)
  227. def __delitem__(self, name):
  228. """Remove a refname.
  229. This method does not follow symbolic references, even if applicable for
  230. the subclass.
  231. :note: This method unconditionally deletes the contents of a reference.
  232. To delete atomically only if the reference has not changed, use
  233. remove_if_equals().
  234. :param name: The refname to delete.
  235. """
  236. self.remove_if_equals(name, None)
  237. class DictRefsContainer(RefsContainer):
  238. """RefsContainer backed by a simple dict.
  239. This container does not support symbolic or packed references and is not
  240. threadsafe.
  241. """
  242. def __init__(self, refs):
  243. self._refs = refs
  244. self._peeled = {}
  245. def allkeys(self):
  246. return self._refs.keys()
  247. def read_loose_ref(self, name):
  248. return self._refs.get(name, None)
  249. def get_packed_refs(self):
  250. return {}
  251. def set_symbolic_ref(self, name, other):
  252. self._refs[name] = SYMREF + other
  253. def set_if_equals(self, name, old_ref, new_ref):
  254. if old_ref is not None and self._refs.get(name, None) != old_ref:
  255. return False
  256. realname, _ = self._follow(name)
  257. self._check_refname(realname)
  258. self._refs[realname] = new_ref
  259. return True
  260. def add_if_new(self, name, ref):
  261. if name in self._refs:
  262. return False
  263. self._refs[name] = ref
  264. return True
  265. def remove_if_equals(self, name, old_ref):
  266. if old_ref is not None and self._refs.get(name, None) != old_ref:
  267. return False
  268. del self._refs[name]
  269. return True
  270. def get_peeled(self, name):
  271. return self._peeled.get(name)
  272. def _update(self, refs):
  273. """Update multiple refs; intended only for testing."""
  274. # TODO(dborowitz): replace this with a public function that uses
  275. # set_if_equal.
  276. self._refs.update(refs)
  277. def _update_peeled(self, peeled):
  278. """Update cached peeled refs; intended only for testing."""
  279. self._peeled.update(peeled)
  280. class InfoRefsContainer(RefsContainer):
  281. """Refs container that reads refs from a info/refs file."""
  282. def __init__(self, f):
  283. self._refs = {}
  284. self._peeled = {}
  285. for l in f.readlines():
  286. sha, name = l.rstrip(b'\n').split(b'\t')
  287. if name.endswith(b'^{}'):
  288. name = name[:-3]
  289. if not check_ref_format(name):
  290. raise ValueError("invalid ref name %r" % name)
  291. self._peeled[name] = sha
  292. else:
  293. if not check_ref_format(name):
  294. raise ValueError("invalid ref name %r" % name)
  295. self._refs[name] = sha
  296. def allkeys(self):
  297. return self._refs.keys()
  298. def read_loose_ref(self, name):
  299. return self._refs.get(name, None)
  300. def get_packed_refs(self):
  301. return {}
  302. def get_peeled(self, name):
  303. try:
  304. return self._peeled[name]
  305. except KeyError:
  306. return self._refs[name]
  307. class DiskRefsContainer(RefsContainer):
  308. """Refs container that reads refs from disk."""
  309. def __init__(self, path):
  310. self.path = path
  311. self._packed_refs = None
  312. self._peeled_refs = None
  313. def __repr__(self):
  314. return "%s(%r)" % (self.__class__.__name__, self.path)
  315. def subkeys(self, base):
  316. subkeys = set()
  317. path = self.refpath(base)
  318. for root, dirs, files in os.walk(path):
  319. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  320. for filename in files:
  321. refname = (("%s/%s" % (dir, filename))
  322. .strip("/").encode(sys.getfilesystemencoding()))
  323. # check_ref_format requires at least one /, so we prepend the
  324. # base before calling it.
  325. if check_ref_format(base + b'/' + refname):
  326. subkeys.add(refname)
  327. for key in self.get_packed_refs():
  328. if key.startswith(base):
  329. subkeys.add(key[len(base):].strip(b'/'))
  330. return subkeys
  331. def allkeys(self):
  332. allkeys = set()
  333. if os.path.exists(self.refpath(b'HEAD')):
  334. allkeys.add(b'HEAD')
  335. path = self.refpath(b'')
  336. for root, dirs, files in os.walk(self.refpath(b'refs')):
  337. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  338. for filename in files:
  339. refname = ("%s/%s" % (dir, filename)).encode(sys.getfilesystemencoding())
  340. if check_ref_format(refname):
  341. allkeys.add(refname)
  342. allkeys.update(self.get_packed_refs())
  343. return allkeys
  344. def refpath(self, name):
  345. """Return the disk path of a ref.
  346. """
  347. if getattr(self.path, "encode", None) and getattr(name, "decode", None):
  348. name = name.decode(sys.getfilesystemencoding())
  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. if not valid_hexsha(sha):
  559. raise PackedRefsException("Invalid hex sha %r" % sha)
  560. if not check_ref_format(name):
  561. raise PackedRefsException("invalid ref name %r" % name)
  562. return (sha, name)
  563. def read_packed_refs(f):
  564. """Read a packed refs file.
  565. :param f: file-like object to read from
  566. :return: Iterator over tuples with SHA1s and ref names.
  567. """
  568. for l in f:
  569. if l.startswith(b'#'):
  570. # Comment
  571. continue
  572. if l.startswith(b'^'):
  573. raise PackedRefsException(
  574. "found peeled ref in packed-refs without peeled")
  575. yield _split_ref_line(l)
  576. def read_packed_refs_with_peeled(f):
  577. """Read a packed refs file including peeled refs.
  578. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  579. with ref names, SHA1s, and peeled SHA1s (or None).
  580. :param f: file-like object to read from, seek'ed to the second line
  581. """
  582. last = None
  583. for l in f:
  584. if l[0] == b'#':
  585. continue
  586. l = l.rstrip(b'\r\n')
  587. if l.startswith(b'^'):
  588. if not last:
  589. raise PackedRefsException("unexpected peeled ref line")
  590. if not valid_hexsha(l[1:]):
  591. raise PackedRefsException("Invalid hex sha %r" % l[1:])
  592. sha, name = _split_ref_line(last)
  593. last = None
  594. yield (sha, name, l[1:])
  595. else:
  596. if last:
  597. sha, name = _split_ref_line(last)
  598. yield (sha, name, None)
  599. last = l
  600. if last:
  601. sha, name = _split_ref_line(last)
  602. yield (sha, name, None)
  603. def write_packed_refs(f, packed_refs, peeled_refs=None):
  604. """Write a packed refs file.
  605. :param f: empty file-like object to write to
  606. :param packed_refs: dict of refname to sha of packed refs to write
  607. :param peeled_refs: dict of refname to peeled value of sha
  608. """
  609. if peeled_refs is None:
  610. peeled_refs = {}
  611. else:
  612. f.write(b'# pack-refs with: peeled\n')
  613. for refname in sorted(packed_refs.keys()):
  614. f.write(git_line(packed_refs[refname], refname))
  615. if refname in peeled_refs:
  616. f.write(b'^' + peeled_refs[refname] + b'\n')
  617. def read_info_refs(f):
  618. ret = {}
  619. for l in f.readlines():
  620. (sha, name) = l.rstrip("\r\n").split("\t", 1)
  621. ret[name] = sha
  622. return ret
  623. def write_info_refs(refs, store):
  624. """Generate info refs."""
  625. for name, sha in sorted(refs.items()):
  626. # get_refs() includes HEAD as a special case, but we don't want to
  627. # advertise it
  628. if name == b'HEAD':
  629. continue
  630. try:
  631. o = store[sha]
  632. except KeyError:
  633. continue
  634. peeled = store.peel_sha(sha)
  635. yield o.id + b'\t' + name + b'\n'
  636. if o.id != peeled.id:
  637. yield peeled.id + b'\t' + name + b'^{}\n'
  638. is_local_branch = lambda x: x.startswith(b'refs/heads/')