repo.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. # repo.py -- For dealing with git repositories.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; version 2
  8. # of the License or (at your option) any later version of
  9. # the License.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. # MA 02110-1301, USA.
  20. """Repository access."""
  21. from cStringIO import StringIO
  22. import errno
  23. import os
  24. from dulwich.errors import (
  25. MissingCommitError,
  26. NoIndexPresent,
  27. NotBlobError,
  28. NotCommitError,
  29. NotGitRepository,
  30. NotTreeError,
  31. NotTagError,
  32. PackedRefsException,
  33. CommitError,
  34. )
  35. from dulwich.file import (
  36. ensure_dir_exists,
  37. GitFile,
  38. )
  39. from dulwich.object_store import (
  40. DiskObjectStore,
  41. MemoryObjectStore,
  42. )
  43. from dulwich.objects import (
  44. Blob,
  45. Commit,
  46. ShaFile,
  47. Tag,
  48. Tree,
  49. hex_to_sha,
  50. )
  51. import warnings
  52. OBJECTDIR = 'objects'
  53. SYMREF = 'ref: '
  54. REFSDIR = 'refs'
  55. REFSDIR_TAGS = 'tags'
  56. REFSDIR_HEADS = 'heads'
  57. INDEX_FILENAME = "index"
  58. BASE_DIRECTORIES = [
  59. ["branches"],
  60. [REFSDIR],
  61. [REFSDIR, REFSDIR_TAGS],
  62. [REFSDIR, REFSDIR_HEADS],
  63. ["hooks"],
  64. ["info"]
  65. ]
  66. def read_info_refs(f):
  67. ret = {}
  68. for l in f.readlines():
  69. (sha, name) = l.rstrip("\r\n").split("\t", 1)
  70. ret[name] = sha
  71. return ret
  72. def check_ref_format(refname):
  73. """Check if a refname is correctly formatted.
  74. Implements all the same rules as git-check-ref-format[1].
  75. [1] http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  76. :param refname: The refname to check
  77. :return: True if refname is valid, False otherwise
  78. """
  79. # These could be combined into one big expression, but are listed separately
  80. # to parallel [1].
  81. if '/.' in refname or refname.startswith('.'):
  82. return False
  83. if '/' not in refname:
  84. return False
  85. if '..' in refname:
  86. return False
  87. for c in refname:
  88. if ord(c) < 040 or c in '\177 ~^:?*[':
  89. return False
  90. if refname[-1] in '/.':
  91. return False
  92. if refname.endswith('.lock'):
  93. return False
  94. if '@{' in refname:
  95. return False
  96. if '\\' in refname:
  97. return False
  98. return True
  99. class RefsContainer(object):
  100. """A container for refs."""
  101. def set_ref(self, name, other):
  102. warnings.warn("RefsContainer.set_ref() is deprecated."
  103. "Use set_symblic_ref instead.",
  104. category=DeprecationWarning, stacklevel=2)
  105. return self.set_symbolic_ref(name, other)
  106. def set_symbolic_ref(self, name, other):
  107. """Make a ref point at another ref.
  108. :param name: Name of the ref to set
  109. :param other: Name of the ref to point at
  110. """
  111. raise NotImplementedError(self.set_symbolic_ref)
  112. def get_packed_refs(self):
  113. """Get contents of the packed-refs file.
  114. :return: Dictionary mapping ref names to SHA1s
  115. :note: Will return an empty dictionary when no packed-refs file is
  116. present.
  117. """
  118. raise NotImplementedError(self.get_packed_refs)
  119. def get_peeled(self, name):
  120. """Return the cached peeled value of a ref, if available.
  121. :param name: Name of the ref to peel
  122. :return: The peeled value of the ref. If the ref is known not point to a
  123. tag, this will be the SHA the ref refers to. If the ref may point to
  124. a tag, but no cached information is available, None is returned.
  125. """
  126. return None
  127. def import_refs(self, base, other):
  128. for name, value in other.iteritems():
  129. self["%s/%s" % (base, name)] = value
  130. def allkeys(self):
  131. """All refs present in this container."""
  132. raise NotImplementedError(self.allkeys)
  133. def keys(self, base=None):
  134. """Refs present in this container.
  135. :param base: An optional base to return refs under.
  136. :return: An unsorted set of valid refs in this container, including
  137. packed refs.
  138. """
  139. if base is not None:
  140. return self.subkeys(base)
  141. else:
  142. return self.allkeys()
  143. def subkeys(self, base):
  144. """Refs present in this container under a base.
  145. :param base: The base to return refs under.
  146. :return: A set of valid refs in this container under the base; the base
  147. prefix is stripped from the ref names returned.
  148. """
  149. keys = set()
  150. base_len = len(base) + 1
  151. for refname in self.allkeys():
  152. if refname.startswith(base):
  153. keys.add(refname[base_len:])
  154. return keys
  155. def as_dict(self, base=None):
  156. """Return the contents of this container as a dictionary.
  157. """
  158. ret = {}
  159. keys = self.keys(base)
  160. if base is None:
  161. base = ""
  162. for key in keys:
  163. try:
  164. ret[key] = self[("%s/%s" % (base, key)).strip("/")]
  165. except KeyError:
  166. continue # Unable to resolve
  167. return ret
  168. def _check_refname(self, name):
  169. """Ensure a refname is valid and lives in refs or is HEAD.
  170. HEAD is not a valid refname according to git-check-ref-format, but this
  171. class needs to be able to touch HEAD. Also, check_ref_format expects
  172. refnames without the leading 'refs/', but this class requires that
  173. so it cannot touch anything outside the refs dir (or HEAD).
  174. :param name: The name of the reference.
  175. :raises KeyError: if a refname is not HEAD or is otherwise not valid.
  176. """
  177. if name == 'HEAD':
  178. return
  179. if not name.startswith('refs/') or not check_ref_format(name[5:]):
  180. raise KeyError(name)
  181. def read_ref(self, refname):
  182. """Read a reference without following any references.
  183. :param refname: The name of the reference
  184. :return: The contents of the ref file, or None if it does
  185. not exist.
  186. """
  187. contents = self.read_loose_ref(refname)
  188. if not contents:
  189. contents = self.get_packed_refs().get(refname, None)
  190. return contents
  191. def read_loose_ref(self, name):
  192. """Read a loose reference and return its contents.
  193. :param name: the refname to read
  194. :return: The contents of the ref file, or None if it does
  195. not exist.
  196. """
  197. raise NotImplementedError(self.read_loose_ref)
  198. def _follow(self, name):
  199. """Follow a reference name.
  200. :return: a tuple of (refname, sha), where refname is the name of the
  201. last reference in the symbolic reference chain
  202. """
  203. self._check_refname(name)
  204. contents = SYMREF + name
  205. depth = 0
  206. while contents.startswith(SYMREF):
  207. refname = contents[len(SYMREF):]
  208. contents = self.read_ref(refname)
  209. if not contents:
  210. break
  211. depth += 1
  212. if depth > 5:
  213. raise KeyError(name)
  214. return refname, contents
  215. def __contains__(self, refname):
  216. if self.read_ref(refname):
  217. return True
  218. return False
  219. def __getitem__(self, name):
  220. """Get the SHA1 for a reference name.
  221. This method follows all symbolic references.
  222. """
  223. _, sha = self._follow(name)
  224. if sha is None:
  225. raise KeyError(name)
  226. return sha
  227. def set_if_equals(self, name, old_ref, new_ref):
  228. """Set a refname to new_ref only if it currently equals old_ref.
  229. This method follows all symbolic references if applicable for the
  230. subclass, and can be used to perform an atomic compare-and-swap
  231. operation.
  232. :param name: The refname to set.
  233. :param old_ref: The old sha the refname must refer to, or None to set
  234. unconditionally.
  235. :param new_ref: The new sha the refname will refer to.
  236. :return: True if the set was successful, False otherwise.
  237. """
  238. raise NotImplementedError(self.set_if_equals)
  239. def add_if_new(self, name, ref):
  240. """Add a new reference only if it does not already exist."""
  241. raise NotImplementedError(self.add_if_new)
  242. def __setitem__(self, name, ref):
  243. """Set a reference name to point to the given SHA1.
  244. This method follows all symbolic references if applicable for the
  245. subclass.
  246. :note: This method unconditionally overwrites the contents of a
  247. reference. To update atomically only if the reference has not
  248. changed, use set_if_equals().
  249. :param name: The refname to set.
  250. :param ref: The new sha the refname will refer to.
  251. """
  252. self.set_if_equals(name, None, ref)
  253. def remove_if_equals(self, name, old_ref):
  254. """Remove a refname only if it currently equals old_ref.
  255. This method does not follow symbolic references, even if applicable for
  256. the subclass. It can be used to perform an atomic compare-and-delete
  257. operation.
  258. :param name: The refname to delete.
  259. :param old_ref: The old sha the refname must refer to, or None to delete
  260. unconditionally.
  261. :return: True if the delete was successful, False otherwise.
  262. """
  263. raise NotImplementedError(self.remove_if_equals)
  264. def __delitem__(self, name):
  265. """Remove a refname.
  266. This method does not follow symbolic references, even if applicable for
  267. the subclass.
  268. :note: This method unconditionally deletes the contents of a reference.
  269. To delete atomically only if the reference has not changed, use
  270. remove_if_equals().
  271. :param name: The refname to delete.
  272. """
  273. self.remove_if_equals(name, None)
  274. class DictRefsContainer(RefsContainer):
  275. """RefsContainer backed by a simple dict.
  276. This container does not support symbolic or packed references and is not
  277. threadsafe.
  278. """
  279. def __init__(self, refs):
  280. self._refs = refs
  281. self._peeled = {}
  282. def allkeys(self):
  283. return self._refs.keys()
  284. def read_loose_ref(self, name):
  285. return self._refs.get(name, None)
  286. def get_packed_refs(self):
  287. return {}
  288. def set_symbolic_ref(self, name, other):
  289. self._refs[name] = SYMREF + other
  290. def set_if_equals(self, name, old_ref, new_ref):
  291. if old_ref is not None and self._refs.get(name, None) != old_ref:
  292. return False
  293. realname, _ = self._follow(name)
  294. self._refs[realname] = new_ref
  295. return True
  296. def add_if_new(self, name, ref):
  297. if name in self._refs:
  298. return False
  299. self._refs[name] = ref
  300. return True
  301. def remove_if_equals(self, name, old_ref):
  302. if old_ref is not None and self._refs.get(name, None) != old_ref:
  303. return False
  304. del self._refs[name]
  305. return True
  306. def get_peeled(self, name):
  307. return self._peeled.get(name)
  308. def _update(self, refs):
  309. """Update multiple refs; intended only for testing."""
  310. # TODO(dborowitz): replace this with a public function that uses
  311. # set_if_equal.
  312. self._refs.update(refs)
  313. def _update_peeled(self, peeled):
  314. """Update cached peeled refs; intended only for testing."""
  315. self._peeled.update(peeled)
  316. class DiskRefsContainer(RefsContainer):
  317. """Refs container that reads refs from disk."""
  318. def __init__(self, path):
  319. self.path = path
  320. self._packed_refs = None
  321. self._peeled_refs = None
  322. def __repr__(self):
  323. return "%s(%r)" % (self.__class__.__name__, self.path)
  324. def subkeys(self, base):
  325. keys = set()
  326. path = self.refpath(base)
  327. for root, dirs, files in os.walk(path):
  328. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  329. for filename in files:
  330. refname = ("%s/%s" % (dir, filename)).strip("/")
  331. # check_ref_format requires at least one /, so we prepend the
  332. # base before calling it.
  333. if check_ref_format("%s/%s" % (base, refname)):
  334. keys.add(refname)
  335. for key in self.get_packed_refs():
  336. if key.startswith(base):
  337. keys.add(key[len(base):].strip("/"))
  338. return keys
  339. def allkeys(self):
  340. keys = set()
  341. if os.path.exists(self.refpath("HEAD")):
  342. keys.add("HEAD")
  343. path = self.refpath("")
  344. for root, dirs, files in os.walk(self.refpath("refs")):
  345. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  346. for filename in files:
  347. refname = ("%s/%s" % (dir, filename)).strip("/")
  348. if check_ref_format(refname):
  349. keys.add(refname)
  350. keys.update(self.get_packed_refs())
  351. return keys
  352. def refpath(self, name):
  353. """Return the disk path of a ref.
  354. """
  355. if os.path.sep != "/":
  356. name = name.replace("/", os.path.sep)
  357. return os.path.join(self.path, name)
  358. def get_packed_refs(self):
  359. """Get contents of the packed-refs file.
  360. :return: Dictionary mapping ref names to SHA1s
  361. :note: Will return an empty dictionary when no packed-refs file is
  362. present.
  363. """
  364. # TODO: invalidate the cache on repacking
  365. if self._packed_refs is None:
  366. # set both to empty because we want _peeled_refs to be
  367. # None if and only if _packed_refs is also None.
  368. self._packed_refs = {}
  369. self._peeled_refs = {}
  370. path = os.path.join(self.path, 'packed-refs')
  371. try:
  372. f = GitFile(path, 'rb')
  373. except IOError, e:
  374. if e.errno == errno.ENOENT:
  375. return {}
  376. raise
  377. try:
  378. first_line = iter(f).next().rstrip()
  379. if (first_line.startswith("# pack-refs") and " peeled" in
  380. first_line):
  381. for sha, name, peeled in read_packed_refs_with_peeled(f):
  382. self._packed_refs[name] = sha
  383. if peeled:
  384. self._peeled_refs[name] = peeled
  385. else:
  386. f.seek(0)
  387. for sha, name in read_packed_refs(f):
  388. self._packed_refs[name] = sha
  389. finally:
  390. f.close()
  391. return self._packed_refs
  392. def get_peeled(self, name):
  393. """Return the cached peeled value of a ref, if available.
  394. :param name: Name of the ref to peel
  395. :return: The peeled value of the ref. If the ref is known not point to a
  396. tag, this will be the SHA the ref refers to. If the ref may point to
  397. a tag, but no cached information is available, None is returned.
  398. """
  399. self.get_packed_refs()
  400. if self._peeled_refs is None or name not in self._packed_refs:
  401. # No cache: no peeled refs were read, or this ref is loose
  402. return None
  403. if name in self._peeled_refs:
  404. return self._peeled_refs[name]
  405. else:
  406. # Known not peelable
  407. return self[name]
  408. def read_loose_ref(self, name):
  409. """Read a reference file and return its contents.
  410. If the reference file a symbolic reference, only read the first line of
  411. the file. Otherwise, only read the first 40 bytes.
  412. :param name: the refname to read, relative to refpath
  413. :return: The contents of the ref file, or None if the file does not
  414. exist.
  415. :raises IOError: if any other error occurs
  416. """
  417. filename = self.refpath(name)
  418. try:
  419. f = GitFile(filename, 'rb')
  420. try:
  421. header = f.read(len(SYMREF))
  422. if header == SYMREF:
  423. # Read only the first line
  424. return header + iter(f).next().rstrip("\r\n")
  425. else:
  426. # Read only the first 40 bytes
  427. return header + f.read(40-len(SYMREF))
  428. finally:
  429. f.close()
  430. except IOError, e:
  431. if e.errno == errno.ENOENT:
  432. return None
  433. raise
  434. def _remove_packed_ref(self, name):
  435. if self._packed_refs is None:
  436. return
  437. filename = os.path.join(self.path, 'packed-refs')
  438. # reread cached refs from disk, while holding the lock
  439. f = GitFile(filename, 'wb')
  440. try:
  441. self._packed_refs = None
  442. self.get_packed_refs()
  443. if name not in self._packed_refs:
  444. return
  445. del self._packed_refs[name]
  446. if name in self._peeled_refs:
  447. del self._peeled_refs[name]
  448. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  449. f.close()
  450. finally:
  451. f.abort()
  452. def set_symbolic_ref(self, name, other):
  453. """Make a ref point at another ref.
  454. :param name: Name of the ref to set
  455. :param other: Name of the ref to point at
  456. """
  457. self._check_refname(name)
  458. self._check_refname(other)
  459. filename = self.refpath(name)
  460. try:
  461. f = GitFile(filename, 'wb')
  462. try:
  463. f.write(SYMREF + other + '\n')
  464. except (IOError, OSError):
  465. f.abort()
  466. raise
  467. finally:
  468. f.close()
  469. def set_if_equals(self, name, old_ref, new_ref):
  470. """Set a refname to new_ref only if it currently equals old_ref.
  471. This method follows all symbolic references, and can be used to perform
  472. an atomic compare-and-swap operation.
  473. :param name: The refname to set.
  474. :param old_ref: The old sha the refname must refer to, or None to set
  475. unconditionally.
  476. :param new_ref: The new sha the refname will refer to.
  477. :return: True if the set was successful, False otherwise.
  478. """
  479. try:
  480. realname, _ = self._follow(name)
  481. except KeyError:
  482. realname = name
  483. filename = self.refpath(realname)
  484. ensure_dir_exists(os.path.dirname(filename))
  485. f = GitFile(filename, 'wb')
  486. try:
  487. if old_ref is not None:
  488. try:
  489. # read again while holding the lock
  490. orig_ref = self.read_loose_ref(realname)
  491. if orig_ref is None:
  492. orig_ref = self.get_packed_refs().get(realname, None)
  493. if orig_ref != old_ref:
  494. f.abort()
  495. return False
  496. except (OSError, IOError):
  497. f.abort()
  498. raise
  499. try:
  500. f.write(new_ref+"\n")
  501. except (OSError, IOError):
  502. f.abort()
  503. raise
  504. finally:
  505. f.close()
  506. return True
  507. def add_if_new(self, name, ref):
  508. """Add a new reference only if it does not already exist.
  509. This method follows symrefs, and only ensures that the last ref in the
  510. chain does not exist.
  511. :param name: The refname to set.
  512. :param ref: The new sha the refname will refer to.
  513. :return: True if the add was successful, False otherwise.
  514. """
  515. try:
  516. realname, contents = self._follow(name)
  517. if contents is not None:
  518. return False
  519. except KeyError:
  520. realname = name
  521. self._check_refname(realname)
  522. filename = self.refpath(realname)
  523. ensure_dir_exists(os.path.dirname(filename))
  524. f = GitFile(filename, 'wb')
  525. try:
  526. if os.path.exists(filename) or name in self.get_packed_refs():
  527. f.abort()
  528. return False
  529. try:
  530. f.write(ref+"\n")
  531. except (OSError, IOError):
  532. f.abort()
  533. raise
  534. finally:
  535. f.close()
  536. return True
  537. def remove_if_equals(self, name, old_ref):
  538. """Remove a refname only if it currently equals old_ref.
  539. This method does not follow symbolic references. It can be used to
  540. perform an atomic compare-and-delete operation.
  541. :param name: The refname to delete.
  542. :param old_ref: The old sha the refname must refer to, or None to delete
  543. unconditionally.
  544. :return: True if the delete was successful, False otherwise.
  545. """
  546. self._check_refname(name)
  547. filename = self.refpath(name)
  548. ensure_dir_exists(os.path.dirname(filename))
  549. f = GitFile(filename, 'wb')
  550. try:
  551. if old_ref is not None:
  552. orig_ref = self.read_loose_ref(name)
  553. if orig_ref is None:
  554. orig_ref = self.get_packed_refs().get(name, None)
  555. if orig_ref != old_ref:
  556. return False
  557. # may only be packed
  558. try:
  559. os.remove(filename)
  560. except OSError, e:
  561. if e.errno != errno.ENOENT:
  562. raise
  563. self._remove_packed_ref(name)
  564. finally:
  565. # never write, we just wanted the lock
  566. f.abort()
  567. return True
  568. def _split_ref_line(line):
  569. """Split a single ref line into a tuple of SHA1 and name."""
  570. fields = line.rstrip("\n").split(" ")
  571. if len(fields) != 2:
  572. raise PackedRefsException("invalid ref line '%s'" % line)
  573. sha, name = fields
  574. try:
  575. hex_to_sha(sha)
  576. except (AssertionError, TypeError), e:
  577. raise PackedRefsException(e)
  578. if not check_ref_format(name):
  579. raise PackedRefsException("invalid ref name '%s'" % name)
  580. return (sha, name)
  581. def read_packed_refs(f):
  582. """Read a packed refs file.
  583. :param f: file-like object to read from
  584. :return: Iterator over tuples with SHA1s and ref names.
  585. """
  586. for l in f:
  587. if l[0] == "#":
  588. # Comment
  589. continue
  590. if l[0] == "^":
  591. raise PackedRefsException(
  592. "found peeled ref in packed-refs without peeled")
  593. yield _split_ref_line(l)
  594. def read_packed_refs_with_peeled(f):
  595. """Read a packed refs file including peeled refs.
  596. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  597. with ref names, SHA1s, and peeled SHA1s (or None).
  598. :param f: file-like object to read from, seek'ed to the second line
  599. """
  600. last = None
  601. for l in f:
  602. if l[0] == "#":
  603. continue
  604. l = l.rstrip("\r\n")
  605. if l[0] == "^":
  606. if not last:
  607. raise PackedRefsException("unexpected peeled ref line")
  608. try:
  609. hex_to_sha(l[1:])
  610. except (AssertionError, TypeError), e:
  611. raise PackedRefsException(e)
  612. sha, name = _split_ref_line(last)
  613. last = None
  614. yield (sha, name, l[1:])
  615. else:
  616. if last:
  617. sha, name = _split_ref_line(last)
  618. yield (sha, name, None)
  619. last = l
  620. if last:
  621. sha, name = _split_ref_line(last)
  622. yield (sha, name, None)
  623. def write_packed_refs(f, packed_refs, peeled_refs=None):
  624. """Write a packed refs file.
  625. :param f: empty file-like object to write to
  626. :param packed_refs: dict of refname to sha of packed refs to write
  627. :param peeled_refs: dict of refname to peeled value of sha
  628. """
  629. if peeled_refs is None:
  630. peeled_refs = {}
  631. else:
  632. f.write('# pack-refs with: peeled\n')
  633. for refname in sorted(packed_refs.iterkeys()):
  634. f.write('%s %s\n' % (packed_refs[refname], refname))
  635. if refname in peeled_refs:
  636. f.write('^%s\n' % peeled_refs[refname])
  637. class BaseRepo(object):
  638. """Base class for a git repository.
  639. :ivar object_store: Dictionary-like object for accessing
  640. the objects
  641. :ivar refs: Dictionary-like object with the refs in this repository
  642. """
  643. def __init__(self, object_store, refs):
  644. self.object_store = object_store
  645. self.refs = refs
  646. def _init_files(self):
  647. """Initialize a default set of named files."""
  648. self._put_named_file('description', "Unnamed repository")
  649. self._put_named_file('config', ('[core]\n'
  650. 'repositoryformatversion = 0\n'
  651. 'filemode = true\n'
  652. 'bare = ' + str(self.bare).lower() + '\n'
  653. 'logallrefupdates = true\n'))
  654. self._put_named_file(os.path.join('info', 'exclude'), '')
  655. def get_named_file(self, path):
  656. """Get a file from the control dir with a specific name.
  657. Although the filename should be interpreted as a filename relative to
  658. the control dir in a disk-baked Repo, the object returned need not be
  659. pointing to a file in that location.
  660. :param path: The path to the file, relative to the control dir.
  661. :return: An open file object, or None if the file does not exist.
  662. """
  663. raise NotImplementedError(self.get_named_file)
  664. def _put_named_file(self, path, contents):
  665. """Write a file to the control dir with the given name and contents.
  666. :param path: The path to the file, relative to the control dir.
  667. :param contents: A string to write to the file.
  668. """
  669. raise NotImplementedError(self._put_named_file)
  670. def open_index(self):
  671. """Open the index for this repository.
  672. :raises NoIndexPresent: If no index is present
  673. :return: Index instance
  674. """
  675. raise NotImplementedError(self.open_index)
  676. def fetch(self, target, determine_wants=None, progress=None):
  677. """Fetch objects into another repository.
  678. :param target: The target repository
  679. :param determine_wants: Optional function to determine what refs to
  680. fetch.
  681. :param progress: Optional progress function
  682. """
  683. if determine_wants is None:
  684. determine_wants = lambda heads: heads.values()
  685. target.object_store.add_objects(
  686. self.fetch_objects(determine_wants, target.get_graph_walker(),
  687. progress))
  688. return self.get_refs()
  689. def fetch_objects(self, determine_wants, graph_walker, progress,
  690. get_tagged=None):
  691. """Fetch the missing objects required for a set of revisions.
  692. :param determine_wants: Function that takes a dictionary with heads
  693. and returns the list of heads to fetch.
  694. :param graph_walker: Object that can iterate over the list of revisions
  695. to fetch and has an "ack" method that will be called to acknowledge
  696. that a revision is present.
  697. :param progress: Simple progress function that will be called with
  698. updated progress strings.
  699. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  700. sha for including tags.
  701. :return: iterator over objects, with __len__ implemented
  702. """
  703. wants = determine_wants(self.get_refs())
  704. if wants is None:
  705. # TODO(dborowitz): find a way to short-circuit that doesn't change
  706. # this interface.
  707. return None
  708. haves = self.object_store.find_common_revisions(graph_walker)
  709. return self.object_store.iter_shas(
  710. self.object_store.find_missing_objects(haves, wants, progress,
  711. get_tagged))
  712. def get_graph_walker(self, heads=None):
  713. if heads is None:
  714. heads = self.refs.as_dict('refs/heads').values()
  715. return self.object_store.get_graph_walker(heads)
  716. def ref(self, name):
  717. """Return the SHA1 a ref is pointing to."""
  718. return self.refs[name]
  719. def get_refs(self):
  720. """Get dictionary with all refs."""
  721. return self.refs.as_dict()
  722. def head(self):
  723. """Return the SHA1 pointed at by HEAD."""
  724. return self.refs['HEAD']
  725. def _get_object(self, sha, cls):
  726. assert len(sha) in (20, 40)
  727. ret = self.get_object(sha)
  728. if not isinstance(ret, cls):
  729. if cls is Commit:
  730. raise NotCommitError(ret)
  731. elif cls is Blob:
  732. raise NotBlobError(ret)
  733. elif cls is Tree:
  734. raise NotTreeError(ret)
  735. elif cls is Tag:
  736. raise NotTagError(ret)
  737. else:
  738. raise Exception("Type invalid: %r != %r" % (
  739. ret.type_name, cls.type_name))
  740. return ret
  741. def get_object(self, sha):
  742. return self.object_store[sha]
  743. def get_parents(self, sha):
  744. return self.commit(sha).parents
  745. def get_config(self):
  746. import ConfigParser
  747. p = ConfigParser.RawConfigParser()
  748. p.read(os.path.join(self._controldir, 'config'))
  749. return dict((section, dict(p.items(section)))
  750. for section in p.sections())
  751. def commit(self, sha):
  752. """Retrieve the commit with a particular SHA.
  753. :param sha: SHA of the commit to retrieve
  754. :raise NotCommitError: If the SHA provided doesn't point at a Commit
  755. :raise KeyError: If the SHA provided didn't exist
  756. :return: A `Commit` object
  757. """
  758. warnings.warn("Repo.commit(sha) is deprecated. Use Repo[sha] instead.",
  759. category=DeprecationWarning, stacklevel=2)
  760. return self._get_object(sha, Commit)
  761. def tree(self, sha):
  762. """Retrieve the tree with a particular SHA.
  763. :param sha: SHA of the tree to retrieve
  764. :raise NotTreeError: If the SHA provided doesn't point at a Tree
  765. :raise KeyError: If the SHA provided didn't exist
  766. :return: A `Tree` object
  767. """
  768. warnings.warn("Repo.tree(sha) is deprecated. Use Repo[sha] instead.",
  769. category=DeprecationWarning, stacklevel=2)
  770. return self._get_object(sha, Tree)
  771. def tag(self, sha):
  772. """Retrieve the tag with a particular SHA.
  773. :param sha: SHA of the tag to retrieve
  774. :raise NotTagError: If the SHA provided doesn't point at a Tag
  775. :raise KeyError: If the SHA provided didn't exist
  776. :return: A `Tag` object
  777. """
  778. warnings.warn("Repo.tag(sha) is deprecated. Use Repo[sha] instead.",
  779. category=DeprecationWarning, stacklevel=2)
  780. return self._get_object(sha, Tag)
  781. def get_blob(self, sha):
  782. """Retrieve the blob with a particular SHA.
  783. :param sha: SHA of the blob to retrieve
  784. :raise NotBlobError: If the SHA provided doesn't point at a Blob
  785. :raise KeyError: If the SHA provided didn't exist
  786. :return: A `Blob` object
  787. """
  788. warnings.warn("Repo.get_blob(sha) is deprecated. Use Repo[sha] "
  789. "instead.", category=DeprecationWarning, stacklevel=2)
  790. return self._get_object(sha, Blob)
  791. def get_peeled(self, ref):
  792. """Get the peeled value of a ref.
  793. :param ref: The refname to peel.
  794. :return: The fully-peeled SHA1 of a tag object, after peeling all
  795. intermediate tags; if the original ref does not point to a tag, this
  796. will equal the original SHA1.
  797. """
  798. cached = self.refs.get_peeled(ref)
  799. if cached is not None:
  800. return cached
  801. return self.object_store.peel_sha(self.refs[ref]).id
  802. def revision_history(self, head):
  803. """Returns a list of the commits reachable from head.
  804. Returns a list of commit objects. the first of which will be the commit
  805. of head, then following theat will be the parents.
  806. Raises NotCommitError if any no commits are referenced, including if the
  807. head parameter isn't the sha of a commit.
  808. XXX: work out how to handle merges.
  809. """
  810. # We build the list backwards, as parents are more likely to be older
  811. # than children
  812. pending_commits = [head]
  813. history = []
  814. while pending_commits != []:
  815. head = pending_commits.pop(0)
  816. try:
  817. commit = self[head]
  818. except KeyError:
  819. raise MissingCommitError(head)
  820. if type(commit) != Commit:
  821. raise NotCommitError(commit)
  822. if commit in history:
  823. continue
  824. i = 0
  825. for known_commit in history:
  826. if known_commit.commit_time > commit.commit_time:
  827. break
  828. i += 1
  829. history.insert(i, commit)
  830. pending_commits += commit.parents
  831. history.reverse()
  832. return history
  833. def __getitem__(self, name):
  834. if len(name) in (20, 40):
  835. try:
  836. return self.object_store[name]
  837. except KeyError:
  838. pass
  839. return self.object_store[self.refs[name]]
  840. def __contains__(self, name):
  841. if len(name) in (20, 40):
  842. return name in self.object_store or name in self.refs
  843. else:
  844. return name in self.refs
  845. def __setitem__(self, name, value):
  846. if name.startswith("refs/") or name == "HEAD":
  847. if isinstance(value, ShaFile):
  848. self.refs[name] = value.id
  849. elif isinstance(value, str):
  850. self.refs[name] = value
  851. else:
  852. raise TypeError(value)
  853. else:
  854. raise ValueError(name)
  855. def __delitem__(self, name):
  856. if name.startswith("refs") or name == "HEAD":
  857. del self.refs[name]
  858. raise ValueError(name)
  859. def do_commit(self, message, committer=None,
  860. author=None, commit_timestamp=None,
  861. commit_timezone=None, author_timestamp=None,
  862. author_timezone=None, tree=None):
  863. """Create a new commit.
  864. :param message: Commit message
  865. :param committer: Committer fullname
  866. :param author: Author fullname (defaults to committer)
  867. :param commit_timestamp: Commit timestamp (defaults to now)
  868. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  869. :param author_timestamp: Author timestamp (defaults to commit timestamp)
  870. :param author_timezone: Author timestamp timezone
  871. (defaults to commit timestamp timezone)
  872. :param tree: SHA1 of the tree root to use (if not specified the current index will be committed).
  873. :return: New commit SHA1
  874. """
  875. import time
  876. c = Commit()
  877. if tree is None:
  878. index = self.open_index()
  879. c.tree = index.commit(self.object_store)
  880. else:
  881. c.tree = tree
  882. # TODO: Allow username to be missing, and get it from .git/config
  883. if committer is None:
  884. raise ValueError("committer not set")
  885. c.committer = committer
  886. if commit_timestamp is None:
  887. commit_timestamp = time.time()
  888. c.commit_time = int(commit_timestamp)
  889. if commit_timezone is None:
  890. # FIXME: Use current user timezone rather than UTC
  891. commit_timezone = 0
  892. c.commit_timezone = commit_timezone
  893. if author is None:
  894. author = committer
  895. c.author = author
  896. if author_timestamp is None:
  897. author_timestamp = commit_timestamp
  898. c.author_time = int(author_timestamp)
  899. if author_timezone is None:
  900. author_timezone = commit_timezone
  901. c.author_timezone = author_timezone
  902. c.message = message
  903. try:
  904. old_head = self.refs["HEAD"]
  905. c.parents = [old_head]
  906. self.object_store.add_object(c)
  907. ok = self.refs.set_if_equals("HEAD", old_head, c.id)
  908. except KeyError:
  909. c.parents = []
  910. self.object_store.add_object(c)
  911. ok = self.refs.add_if_new("HEAD", c.id)
  912. if not ok:
  913. # Fail if the atomic compare-and-swap failed, leaving the commit and
  914. # all its objects as garbage.
  915. raise CommitError("HEAD changed during commit")
  916. return c.id
  917. class Repo(BaseRepo):
  918. """A git repository backed by local disk."""
  919. def __init__(self, root):
  920. if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
  921. self.bare = False
  922. self._controldir = os.path.join(root, ".git")
  923. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  924. os.path.isdir(os.path.join(root, REFSDIR))):
  925. self.bare = True
  926. self._controldir = root
  927. else:
  928. raise NotGitRepository(root)
  929. self.path = root
  930. object_store = DiskObjectStore(os.path.join(self.controldir(),
  931. OBJECTDIR))
  932. refs = DiskRefsContainer(self.controldir())
  933. BaseRepo.__init__(self, object_store, refs)
  934. def controldir(self):
  935. """Return the path of the control directory."""
  936. return self._controldir
  937. def _put_named_file(self, path, contents):
  938. """Write a file to the control dir with the given name and contents.
  939. :param path: The path to the file, relative to the control dir.
  940. :param contents: A string to write to the file.
  941. """
  942. path = path.lstrip(os.path.sep)
  943. f = GitFile(os.path.join(self.controldir(), path), 'wb')
  944. try:
  945. f.write(contents)
  946. finally:
  947. f.close()
  948. def get_named_file(self, path):
  949. """Get a file from the control dir with a specific name.
  950. Although the filename should be interpreted as a filename relative to
  951. the control dir in a disk-baked Repo, the object returned need not be
  952. pointing to a file in that location.
  953. :param path: The path to the file, relative to the control dir.
  954. :return: An open file object, or None if the file does not exist.
  955. """
  956. # TODO(dborowitz): sanitize filenames, since this is used directly by
  957. # the dumb web serving code.
  958. path = path.lstrip(os.path.sep)
  959. try:
  960. return open(os.path.join(self.controldir(), path), 'rb')
  961. except (IOError, OSError), e:
  962. if e.errno == errno.ENOENT:
  963. return None
  964. raise
  965. def index_path(self):
  966. """Return path to the index file."""
  967. return os.path.join(self.controldir(), INDEX_FILENAME)
  968. def open_index(self):
  969. """Open the index for this repository."""
  970. from dulwich.index import Index
  971. if not self.has_index():
  972. raise NoIndexPresent()
  973. return Index(self.index_path())
  974. def has_index(self):
  975. """Check if an index is present."""
  976. # Bare repos must never have index files; non-bare repos may have a
  977. # missing index file, which is treated as empty.
  978. return not self.bare
  979. def stage(self, paths):
  980. """Stage a set of paths.
  981. :param paths: List of paths, relative to the repository path
  982. """
  983. from dulwich.index import cleanup_mode
  984. index = self.open_index()
  985. for path in paths:
  986. full_path = os.path.join(self.path, path)
  987. blob = Blob()
  988. try:
  989. st = os.stat(full_path)
  990. except OSError:
  991. # File no longer exists
  992. try:
  993. del index[path]
  994. except KeyError:
  995. pass # Doesn't exist in the index either
  996. else:
  997. f = open(full_path, 'rb')
  998. try:
  999. blob.data = f.read()
  1000. finally:
  1001. f.close()
  1002. self.object_store.add_object(blob)
  1003. # XXX: Cleanup some of the other file properties as well?
  1004. index[path] = (st.st_ctime, st.st_mtime, st.st_dev, st.st_ino,
  1005. cleanup_mode(st.st_mode), st.st_uid, st.st_gid, st.st_size,
  1006. blob.id, 0)
  1007. index.write()
  1008. def __repr__(self):
  1009. return "<Repo at %r>" % self.path
  1010. @classmethod
  1011. def init(cls, path, mkdir=True):
  1012. controldir = os.path.join(path, ".git")
  1013. os.mkdir(controldir)
  1014. cls.init_bare(controldir)
  1015. return cls(path)
  1016. @classmethod
  1017. def init_bare(cls, path, mkdir=True):
  1018. for d in BASE_DIRECTORIES:
  1019. os.mkdir(os.path.join(path, *d))
  1020. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  1021. ret = cls(path)
  1022. ret.refs.set_symbolic_ref("HEAD", "refs/heads/master")
  1023. ret._init_files()
  1024. return ret
  1025. create = init_bare
  1026. class MemoryRepo(BaseRepo):
  1027. """Repo that stores refs, objects, and named files in memory.
  1028. MemoryRepos are always bare: they have no working tree and no index, since
  1029. those have a stronger dependency on the filesystem.
  1030. """
  1031. def __init__(self):
  1032. BaseRepo.__init__(self, MemoryObjectStore(), DictRefsContainer({}))
  1033. self._named_files = {}
  1034. self.bare = True
  1035. def _put_named_file(self, path, contents):
  1036. """Write a file to the control dir with the given name and contents.
  1037. :param path: The path to the file, relative to the control dir.
  1038. :param contents: A string to write to the file.
  1039. """
  1040. self._named_files[path] = contents
  1041. def get_named_file(self, path):
  1042. """Get a file from the control dir with a specific name.
  1043. Although the filename should be interpreted as a filename relative to
  1044. the control dir in a disk-baked Repo, the object returned need not be
  1045. pointing to a file in that location.
  1046. :param path: The path to the file, relative to the control dir.
  1047. :return: An open file object, or None if the file does not exist.
  1048. """
  1049. contents = self._named_files.get(path, None)
  1050. if contents is None:
  1051. return None
  1052. return StringIO(contents)
  1053. def open_index(self):
  1054. """Fail to open index for this repo, since it is bare."""
  1055. raise NoIndexPresent()
  1056. @classmethod
  1057. def init_bare(cls, objects, refs):
  1058. ret = cls()
  1059. for obj in objects:
  1060. ret.object_store.add_object(obj)
  1061. for refname, sha in refs.iteritems():
  1062. ret.refs[refname] = sha
  1063. ret._init_files()
  1064. return ret