repo.py 42 KB

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