repo.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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. This module contains the base class for git repositories
  22. (BaseRepo) and an implementation which uses a repository on
  23. local disk (Repo).
  24. """
  25. from cStringIO import StringIO
  26. import errno
  27. import os
  28. from dulwich.errors import (
  29. NoIndexPresent,
  30. NotBlobError,
  31. NotCommitError,
  32. NotGitRepository,
  33. NotTreeError,
  34. NotTagError,
  35. PackedRefsException,
  36. CommitError,
  37. RefFormatError,
  38. )
  39. from dulwich.file import (
  40. ensure_dir_exists,
  41. GitFile,
  42. )
  43. from dulwich.object_store import (
  44. DiskObjectStore,
  45. MemoryObjectStore,
  46. )
  47. from dulwich.objects import (
  48. Blob,
  49. Commit,
  50. ShaFile,
  51. Tag,
  52. Tree,
  53. hex_to_sha,
  54. )
  55. import warnings
  56. OBJECTDIR = 'objects'
  57. SYMREF = 'ref: '
  58. REFSDIR = 'refs'
  59. REFSDIR_TAGS = 'tags'
  60. REFSDIR_HEADS = 'heads'
  61. INDEX_FILENAME = "index"
  62. BASE_DIRECTORIES = [
  63. ["branches"],
  64. [REFSDIR],
  65. [REFSDIR, REFSDIR_TAGS],
  66. [REFSDIR, REFSDIR_HEADS],
  67. ["hooks"],
  68. ["info"]
  69. ]
  70. def read_info_refs(f):
  71. ret = {}
  72. for l in f.readlines():
  73. (sha, name) = l.rstrip("\r\n").split("\t", 1)
  74. ret[name] = sha
  75. return ret
  76. def check_ref_format(refname):
  77. """Check if a refname is correctly formatted.
  78. Implements all the same rules as git-check-ref-format[1].
  79. [1] http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  80. :param refname: The refname to check
  81. :return: True if refname is valid, False otherwise
  82. """
  83. # These could be combined into one big expression, but are listed separately
  84. # to parallel [1].
  85. if '/.' in refname or refname.startswith('.'):
  86. return False
  87. if '/' not in refname:
  88. return False
  89. if '..' in refname:
  90. return False
  91. for c in refname:
  92. if ord(c) < 040 or c in '\177 ~^:?*[':
  93. return False
  94. if refname[-1] in '/.':
  95. return False
  96. if refname.endswith('.lock'):
  97. return False
  98. if '@{' in refname:
  99. return False
  100. if '\\' in refname:
  101. return False
  102. return True
  103. class RefsContainer(object):
  104. """A container for refs."""
  105. def set_ref(self, name, other):
  106. warnings.warn("RefsContainer.set_ref() is deprecated."
  107. "Use set_symblic_ref instead.",
  108. category=DeprecationWarning, stacklevel=2)
  109. return self.set_symbolic_ref(name, other)
  110. def set_symbolic_ref(self, name, other):
  111. """Make a ref point at another ref.
  112. :param name: Name of the ref to set
  113. :param other: Name of the ref to point at
  114. """
  115. raise NotImplementedError(self.set_symbolic_ref)
  116. def get_packed_refs(self):
  117. """Get contents of the packed-refs file.
  118. :return: Dictionary mapping ref names to SHA1s
  119. :note: Will return an empty dictionary when no packed-refs file is
  120. present.
  121. """
  122. raise NotImplementedError(self.get_packed_refs)
  123. def get_peeled(self, name):
  124. """Return the cached peeled value of a ref, if available.
  125. :param name: Name of the ref to peel
  126. :return: The peeled value of the ref. If the ref is known not point to a
  127. tag, this will be the SHA the ref refers to. If the ref may point to
  128. a tag, but no cached information is available, None is returned.
  129. """
  130. return None
  131. def import_refs(self, base, other):
  132. for name, value in other.iteritems():
  133. self["%s/%s" % (base, name)] = value
  134. def allkeys(self):
  135. """All refs present in this container."""
  136. raise NotImplementedError(self.allkeys)
  137. def keys(self, base=None):
  138. """Refs present in this container.
  139. :param base: An optional base to return refs under.
  140. :return: An unsorted set of valid refs in this container, including
  141. packed refs.
  142. """
  143. if base is not None:
  144. return self.subkeys(base)
  145. else:
  146. return self.allkeys()
  147. def subkeys(self, base):
  148. """Refs present in this container under a base.
  149. :param base: The base to return refs under.
  150. :return: A set of valid refs in this container under the base; the base
  151. prefix is stripped from the ref names returned.
  152. """
  153. keys = set()
  154. base_len = len(base) + 1
  155. for refname in self.allkeys():
  156. if refname.startswith(base):
  157. keys.add(refname[base_len:])
  158. return keys
  159. def as_dict(self, base=None):
  160. """Return the contents of this container as a dictionary.
  161. """
  162. ret = {}
  163. keys = self.keys(base)
  164. if base is None:
  165. base = ""
  166. for key in keys:
  167. try:
  168. ret[key] = self[("%s/%s" % (base, key)).strip("/")]
  169. except KeyError:
  170. continue # Unable to resolve
  171. return ret
  172. def _check_refname(self, name):
  173. """Ensure a refname is valid and lives in refs or is HEAD.
  174. HEAD is not a valid refname according to git-check-ref-format, but this
  175. class needs to be able to touch HEAD. Also, check_ref_format expects
  176. refnames without the leading 'refs/', but this class requires that
  177. so it cannot touch anything outside the refs dir (or HEAD).
  178. :param name: The name of the reference.
  179. :raises KeyError: if a refname is not HEAD or is otherwise not valid.
  180. """
  181. if name in ('HEAD', 'refs/stash'):
  182. return
  183. if not name.startswith('refs/') or not check_ref_format(name[5:]):
  184. raise RefFormatError(name)
  185. def read_ref(self, refname):
  186. """Read a reference without following any references.
  187. :param refname: The name of the reference
  188. :return: The contents of the ref file, or None if it does
  189. not exist.
  190. """
  191. contents = self.read_loose_ref(refname)
  192. if not contents:
  193. contents = self.get_packed_refs().get(refname, None)
  194. return contents
  195. def read_loose_ref(self, name):
  196. """Read a loose reference and return its contents.
  197. :param name: the refname to read
  198. :return: The contents of the ref file, or None if it does
  199. not exist.
  200. """
  201. raise NotImplementedError(self.read_loose_ref)
  202. def _follow(self, name):
  203. """Follow a reference name.
  204. :return: a tuple of (refname, sha), where refname is the name of the
  205. last reference in the symbolic reference chain
  206. """
  207. contents = SYMREF + name
  208. depth = 0
  209. while contents.startswith(SYMREF):
  210. refname = contents[len(SYMREF):]
  211. contents = self.read_ref(refname)
  212. if not contents:
  213. break
  214. depth += 1
  215. if depth > 5:
  216. raise KeyError(name)
  217. return refname, contents
  218. def __contains__(self, refname):
  219. if self.read_ref(refname):
  220. return True
  221. return False
  222. def __getitem__(self, name):
  223. """Get the SHA1 for a reference name.
  224. This method follows all symbolic references.
  225. """
  226. _, sha = self._follow(name)
  227. if sha is None:
  228. raise KeyError(name)
  229. return sha
  230. def set_if_equals(self, name, old_ref, new_ref):
  231. """Set a refname to new_ref only if it currently equals old_ref.
  232. This method follows all symbolic references if applicable for the
  233. subclass, and can be used to perform an atomic compare-and-swap
  234. operation.
  235. :param name: The refname to set.
  236. :param old_ref: The old sha the refname must refer to, or None to set
  237. unconditionally.
  238. :param new_ref: The new sha the refname will refer to.
  239. :return: True if the set was successful, False otherwise.
  240. """
  241. raise NotImplementedError(self.set_if_equals)
  242. def add_if_new(self, name, ref):
  243. """Add a new reference only if it does not already exist."""
  244. raise NotImplementedError(self.add_if_new)
  245. def __setitem__(self, name, ref):
  246. """Set a reference name to point to the given SHA1.
  247. This method follows all symbolic references if applicable for the
  248. subclass.
  249. :note: This method unconditionally overwrites the contents of a
  250. reference. To update atomically only if the reference has not
  251. changed, use set_if_equals().
  252. :param name: The refname to set.
  253. :param ref: The new sha the refname will refer to.
  254. """
  255. self.set_if_equals(name, None, ref)
  256. def remove_if_equals(self, name, old_ref):
  257. """Remove a refname only if it currently equals old_ref.
  258. This method does not follow symbolic references, even if applicable for
  259. the subclass. It can be used to perform an atomic compare-and-delete
  260. operation.
  261. :param name: The refname to delete.
  262. :param old_ref: The old sha the refname must refer to, or None to delete
  263. unconditionally.
  264. :return: True if the delete was successful, False otherwise.
  265. """
  266. raise NotImplementedError(self.remove_if_equals)
  267. def __delitem__(self, name):
  268. """Remove a refname.
  269. This method does not follow symbolic references, even if applicable for
  270. the subclass.
  271. :note: This method unconditionally deletes the contents of a reference.
  272. To delete atomically only if the reference has not changed, use
  273. remove_if_equals().
  274. :param name: The refname to delete.
  275. """
  276. self.remove_if_equals(name, None)
  277. class DictRefsContainer(RefsContainer):
  278. """RefsContainer backed by a simple dict.
  279. This container does not support symbolic or packed references and is not
  280. threadsafe.
  281. """
  282. def __init__(self, refs):
  283. self._refs = refs
  284. self._peeled = {}
  285. def allkeys(self):
  286. return self._refs.keys()
  287. def read_loose_ref(self, name):
  288. return self._refs.get(name, None)
  289. def get_packed_refs(self):
  290. return {}
  291. def set_symbolic_ref(self, name, other):
  292. self._refs[name] = SYMREF + other
  293. def set_if_equals(self, name, old_ref, new_ref):
  294. if old_ref is not None and self._refs.get(name, None) != old_ref:
  295. return False
  296. realname, _ = self._follow(name)
  297. self._check_refname(realname)
  298. self._refs[realname] = new_ref
  299. return True
  300. def add_if_new(self, name, ref):
  301. if name in self._refs:
  302. return False
  303. self._refs[name] = ref
  304. return True
  305. def remove_if_equals(self, name, old_ref):
  306. if old_ref is not None and self._refs.get(name, None) != old_ref:
  307. return False
  308. del self._refs[name]
  309. return True
  310. def get_peeled(self, name):
  311. return self._peeled.get(name)
  312. def _update(self, refs):
  313. """Update multiple refs; intended only for testing."""
  314. # TODO(dborowitz): replace this with a public function that uses
  315. # set_if_equal.
  316. self._refs.update(refs)
  317. def _update_peeled(self, peeled):
  318. """Update cached peeled refs; intended only for testing."""
  319. self._peeled.update(peeled)
  320. class InfoRefsContainer(RefsContainer):
  321. """Refs container that reads refs from a info/refs file."""
  322. def __init__(self, f):
  323. self._refs = {}
  324. self._peeled = {}
  325. for l in f.readlines():
  326. sha, name = l.rstrip("\n").split("\t")
  327. if name.endswith("^{}"):
  328. name = name[:-3]
  329. if not check_ref_format(name):
  330. raise ValueError("invalid ref name '%s'" % name)
  331. self._peeled[name] = sha
  332. else:
  333. if not check_ref_format(name):
  334. raise ValueError("invalid ref name '%s'" % name)
  335. self._refs[name] = sha
  336. def allkeys(self):
  337. return self._refs.keys()
  338. def read_loose_ref(self, name):
  339. return self._refs.get(name, None)
  340. def get_packed_refs(self):
  341. return {}
  342. def get_peeled(self, name):
  343. try:
  344. return self._peeled[name]
  345. except KeyError:
  346. return self._refs[name]
  347. class DiskRefsContainer(RefsContainer):
  348. """Refs container that reads refs from disk."""
  349. def __init__(self, path):
  350. self.path = path
  351. self._packed_refs = None
  352. self._peeled_refs = None
  353. def __repr__(self):
  354. return "%s(%r)" % (self.__class__.__name__, self.path)
  355. def subkeys(self, base):
  356. keys = set()
  357. path = self.refpath(base)
  358. for root, dirs, files in os.walk(path):
  359. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  360. for filename in files:
  361. refname = ("%s/%s" % (dir, filename)).strip("/")
  362. # check_ref_format requires at least one /, so we prepend the
  363. # base before calling it.
  364. if check_ref_format("%s/%s" % (base, refname)):
  365. keys.add(refname)
  366. for key in self.get_packed_refs():
  367. if key.startswith(base):
  368. keys.add(key[len(base):].strip("/"))
  369. return keys
  370. def allkeys(self):
  371. keys = set()
  372. if os.path.exists(self.refpath("HEAD")):
  373. keys.add("HEAD")
  374. path = self.refpath("")
  375. for root, dirs, files in os.walk(self.refpath("refs")):
  376. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  377. for filename in files:
  378. refname = ("%s/%s" % (dir, filename)).strip("/")
  379. if check_ref_format(refname):
  380. keys.add(refname)
  381. keys.update(self.get_packed_refs())
  382. return keys
  383. def refpath(self, name):
  384. """Return the disk path of a ref.
  385. """
  386. if os.path.sep != "/":
  387. name = name.replace("/", os.path.sep)
  388. return os.path.join(self.path, name)
  389. def get_packed_refs(self):
  390. """Get contents of the packed-refs file.
  391. :return: Dictionary mapping ref names to SHA1s
  392. :note: Will return an empty dictionary when no packed-refs file is
  393. present.
  394. """
  395. # TODO: invalidate the cache on repacking
  396. if self._packed_refs is None:
  397. # set both to empty because we want _peeled_refs to be
  398. # None if and only if _packed_refs is also None.
  399. self._packed_refs = {}
  400. self._peeled_refs = {}
  401. path = os.path.join(self.path, 'packed-refs')
  402. try:
  403. f = GitFile(path, 'rb')
  404. except IOError, e:
  405. if e.errno == errno.ENOENT:
  406. return {}
  407. raise
  408. try:
  409. first_line = iter(f).next().rstrip()
  410. if (first_line.startswith("# pack-refs") and " peeled" in
  411. first_line):
  412. for sha, name, peeled in read_packed_refs_with_peeled(f):
  413. self._packed_refs[name] = sha
  414. if peeled:
  415. self._peeled_refs[name] = peeled
  416. else:
  417. f.seek(0)
  418. for sha, name in read_packed_refs(f):
  419. self._packed_refs[name] = sha
  420. finally:
  421. f.close()
  422. return self._packed_refs
  423. def get_peeled(self, name):
  424. """Return the cached peeled value of a ref, if available.
  425. :param name: Name of the ref to peel
  426. :return: The peeled value of the ref. If the ref is known not point to a
  427. tag, this will be the SHA the ref refers to. If the ref may point to
  428. a tag, but no cached information is available, None is returned.
  429. """
  430. self.get_packed_refs()
  431. if self._peeled_refs is None or name not in self._packed_refs:
  432. # No cache: no peeled refs were read, or this ref is loose
  433. return None
  434. if name in self._peeled_refs:
  435. return self._peeled_refs[name]
  436. else:
  437. # Known not peelable
  438. return self[name]
  439. def read_loose_ref(self, name):
  440. """Read a reference file and return its contents.
  441. If the reference file a symbolic reference, only read the first line of
  442. the file. Otherwise, only read the first 40 bytes.
  443. :param name: the refname to read, relative to refpath
  444. :return: The contents of the ref file, or None if the file does not
  445. exist.
  446. :raises IOError: if any other error occurs
  447. """
  448. filename = self.refpath(name)
  449. try:
  450. f = GitFile(filename, 'rb')
  451. try:
  452. header = f.read(len(SYMREF))
  453. if header == SYMREF:
  454. # Read only the first line
  455. return header + iter(f).next().rstrip("\r\n")
  456. else:
  457. # Read only the first 40 bytes
  458. return header + f.read(40 - len(SYMREF))
  459. finally:
  460. f.close()
  461. except IOError, e:
  462. if e.errno == errno.ENOENT:
  463. return None
  464. raise
  465. def _remove_packed_ref(self, name):
  466. if self._packed_refs is None:
  467. return
  468. filename = os.path.join(self.path, 'packed-refs')
  469. # reread cached refs from disk, while holding the lock
  470. f = GitFile(filename, 'wb')
  471. try:
  472. self._packed_refs = None
  473. self.get_packed_refs()
  474. if name not in self._packed_refs:
  475. return
  476. del self._packed_refs[name]
  477. if name in self._peeled_refs:
  478. del self._peeled_refs[name]
  479. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  480. f.close()
  481. finally:
  482. f.abort()
  483. def set_symbolic_ref(self, name, other):
  484. """Make a ref point at another ref.
  485. :param name: Name of the ref to set
  486. :param other: Name of the ref to point at
  487. """
  488. self._check_refname(name)
  489. self._check_refname(other)
  490. filename = self.refpath(name)
  491. try:
  492. f = GitFile(filename, 'wb')
  493. try:
  494. f.write(SYMREF + other + '\n')
  495. except (IOError, OSError):
  496. f.abort()
  497. raise
  498. finally:
  499. f.close()
  500. def set_if_equals(self, name, old_ref, new_ref):
  501. """Set a refname to new_ref only if it currently equals old_ref.
  502. This method follows all symbolic references, and can be used to perform
  503. an atomic compare-and-swap operation.
  504. :param name: The refname to set.
  505. :param old_ref: The old sha the refname must refer to, or None to set
  506. unconditionally.
  507. :param new_ref: The new sha the refname will refer to.
  508. :return: True if the set was successful, False otherwise.
  509. """
  510. self._check_refname(name)
  511. try:
  512. realname, _ = self._follow(name)
  513. except KeyError:
  514. realname = name
  515. filename = self.refpath(realname)
  516. ensure_dir_exists(os.path.dirname(filename))
  517. f = GitFile(filename, 'wb')
  518. try:
  519. if old_ref is not None:
  520. try:
  521. # read again while holding the lock
  522. orig_ref = self.read_loose_ref(realname)
  523. if orig_ref is None:
  524. orig_ref = self.get_packed_refs().get(realname, None)
  525. if orig_ref != old_ref:
  526. f.abort()
  527. return False
  528. except (OSError, IOError):
  529. f.abort()
  530. raise
  531. try:
  532. f.write(new_ref + "\n")
  533. except (OSError, IOError):
  534. f.abort()
  535. raise
  536. finally:
  537. f.close()
  538. return True
  539. def add_if_new(self, name, ref):
  540. """Add a new reference only if it does not already exist.
  541. This method follows symrefs, and only ensures that the last ref in the
  542. chain does not exist.
  543. :param name: The refname to set.
  544. :param ref: The new sha the refname will refer to.
  545. :return: True if the add was successful, False otherwise.
  546. """
  547. try:
  548. realname, contents = self._follow(name)
  549. if contents is not None:
  550. return False
  551. except KeyError:
  552. realname = name
  553. self._check_refname(realname)
  554. filename = self.refpath(realname)
  555. ensure_dir_exists(os.path.dirname(filename))
  556. f = GitFile(filename, 'wb')
  557. try:
  558. if os.path.exists(filename) or name in self.get_packed_refs():
  559. f.abort()
  560. return False
  561. try:
  562. f.write(ref + "\n")
  563. except (OSError, IOError):
  564. f.abort()
  565. raise
  566. finally:
  567. f.close()
  568. return True
  569. def remove_if_equals(self, name, old_ref):
  570. """Remove a refname only if it currently equals old_ref.
  571. This method does not follow symbolic references. It can be used to
  572. perform an atomic compare-and-delete operation.
  573. :param name: The refname to delete.
  574. :param old_ref: The old sha the refname must refer to, or None to delete
  575. unconditionally.
  576. :return: True if the delete was successful, False otherwise.
  577. """
  578. self._check_refname(name)
  579. filename = self.refpath(name)
  580. ensure_dir_exists(os.path.dirname(filename))
  581. f = GitFile(filename, 'wb')
  582. try:
  583. if old_ref is not None:
  584. orig_ref = self.read_loose_ref(name)
  585. if orig_ref is None:
  586. orig_ref = self.get_packed_refs().get(name, None)
  587. if orig_ref != old_ref:
  588. return False
  589. # may only be packed
  590. try:
  591. os.remove(filename)
  592. except OSError, e:
  593. if e.errno != errno.ENOENT:
  594. raise
  595. self._remove_packed_ref(name)
  596. finally:
  597. # never write, we just wanted the lock
  598. f.abort()
  599. return True
  600. def _split_ref_line(line):
  601. """Split a single ref line into a tuple of SHA1 and name."""
  602. fields = line.rstrip("\n").split(" ")
  603. if len(fields) != 2:
  604. raise PackedRefsException("invalid ref line '%s'" % line)
  605. sha, name = fields
  606. try:
  607. hex_to_sha(sha)
  608. except (AssertionError, TypeError), e:
  609. raise PackedRefsException(e)
  610. if not check_ref_format(name):
  611. raise PackedRefsException("invalid ref name '%s'" % name)
  612. return (sha, name)
  613. def read_packed_refs(f):
  614. """Read a packed refs file.
  615. :param f: file-like object to read from
  616. :return: Iterator over tuples with SHA1s and ref names.
  617. """
  618. for l in f:
  619. if l[0] == "#":
  620. # Comment
  621. continue
  622. if l[0] == "^":
  623. raise PackedRefsException(
  624. "found peeled ref in packed-refs without peeled")
  625. yield _split_ref_line(l)
  626. def read_packed_refs_with_peeled(f):
  627. """Read a packed refs file including peeled refs.
  628. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  629. with ref names, SHA1s, and peeled SHA1s (or None).
  630. :param f: file-like object to read from, seek'ed to the second line
  631. """
  632. last = None
  633. for l in f:
  634. if l[0] == "#":
  635. continue
  636. l = l.rstrip("\r\n")
  637. if l[0] == "^":
  638. if not last:
  639. raise PackedRefsException("unexpected peeled ref line")
  640. try:
  641. hex_to_sha(l[1:])
  642. except (AssertionError, TypeError), e:
  643. raise PackedRefsException(e)
  644. sha, name = _split_ref_line(last)
  645. last = None
  646. yield (sha, name, l[1:])
  647. else:
  648. if last:
  649. sha, name = _split_ref_line(last)
  650. yield (sha, name, None)
  651. last = l
  652. if last:
  653. sha, name = _split_ref_line(last)
  654. yield (sha, name, None)
  655. def write_packed_refs(f, packed_refs, peeled_refs=None):
  656. """Write a packed refs file.
  657. :param f: empty file-like object to write to
  658. :param packed_refs: dict of refname to sha of packed refs to write
  659. :param peeled_refs: dict of refname to peeled value of sha
  660. """
  661. if peeled_refs is None:
  662. peeled_refs = {}
  663. else:
  664. f.write('# pack-refs with: peeled\n')
  665. for refname in sorted(packed_refs.iterkeys()):
  666. f.write('%s %s\n' % (packed_refs[refname], refname))
  667. if refname in peeled_refs:
  668. f.write('^%s\n' % peeled_refs[refname])
  669. class BaseRepo(object):
  670. """Base class for a git repository.
  671. :ivar object_store: Dictionary-like object for accessing
  672. the objects
  673. :ivar refs: Dictionary-like object with the refs in this
  674. repository
  675. """
  676. def __init__(self, object_store, refs):
  677. """Open a repository.
  678. This shouldn't be called directly, but rather through one of the
  679. base classes, such as MemoryRepo or Repo.
  680. :param object_store: Object store to use
  681. :param refs: Refs container to use
  682. """
  683. self.object_store = object_store
  684. self.refs = refs
  685. def _init_files(self, bare):
  686. """Initialize a default set of named files."""
  687. from dulwich.config import ConfigFile
  688. self._put_named_file('description', "Unnamed repository")
  689. f = StringIO()
  690. cf = ConfigFile()
  691. cf.set("core", "repositoryformatversion", "0")
  692. cf.set("core", "filemode", "true")
  693. cf.set("core", "bare", str(bare).lower())
  694. cf.set("core", "logallrefupdates", "true")
  695. cf.write_to_file(f)
  696. self._put_named_file('config', f.getvalue())
  697. self._put_named_file(os.path.join('info', 'exclude'), '')
  698. def get_named_file(self, path):
  699. """Get a file from the control dir with a specific name.
  700. Although the filename should be interpreted as a filename relative to
  701. the control dir in a disk-based Repo, the object returned need not be
  702. pointing to a file in that location.
  703. :param path: The path to the file, relative to the control dir.
  704. :return: An open file object, or None if the file does not exist.
  705. """
  706. raise NotImplementedError(self.get_named_file)
  707. def _put_named_file(self, path, contents):
  708. """Write a file to the control dir with the given name and contents.
  709. :param path: The path to the file, relative to the control dir.
  710. :param contents: A string to write to the file.
  711. """
  712. raise NotImplementedError(self._put_named_file)
  713. def open_index(self):
  714. """Open the index for this repository.
  715. :raise NoIndexPresent: If no index is present
  716. :return: The matching `Index`
  717. """
  718. raise NotImplementedError(self.open_index)
  719. def fetch(self, target, determine_wants=None, progress=None):
  720. """Fetch objects into another repository.
  721. :param target: The target repository
  722. :param determine_wants: Optional function to determine what refs to
  723. fetch.
  724. :param progress: Optional progress function
  725. """
  726. if determine_wants is None:
  727. determine_wants = lambda heads: heads.values()
  728. target.object_store.add_objects(
  729. self.fetch_objects(determine_wants, target.get_graph_walker(),
  730. progress))
  731. return self.get_refs()
  732. def fetch_objects(self, determine_wants, graph_walker, progress,
  733. get_tagged=None):
  734. """Fetch the missing objects required for a set of revisions.
  735. :param determine_wants: Function that takes a dictionary with heads
  736. and returns the list of heads to fetch.
  737. :param graph_walker: Object that can iterate over the list of revisions
  738. to fetch and has an "ack" method that will be called to acknowledge
  739. that a revision is present.
  740. :param progress: Simple progress function that will be called with
  741. updated progress strings.
  742. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  743. sha for including tags.
  744. :return: iterator over objects, with __len__ implemented
  745. """
  746. wants = determine_wants(self.get_refs())
  747. if wants is None:
  748. # TODO(dborowitz): find a way to short-circuit that doesn't change
  749. # this interface.
  750. return None
  751. haves = self.object_store.find_common_revisions(graph_walker)
  752. return self.object_store.iter_shas(
  753. self.object_store.find_missing_objects(haves, wants, progress,
  754. get_tagged))
  755. def get_graph_walker(self, heads=None):
  756. """Retrieve a graph walker.
  757. A graph walker is used by a remote repository (or proxy)
  758. to find out which objects are present in this repository.
  759. :param heads: Repository heads to use (optional)
  760. :return: A graph walker object
  761. """
  762. if heads is None:
  763. heads = self.refs.as_dict('refs/heads').values()
  764. return self.object_store.get_graph_walker(heads)
  765. def ref(self, name):
  766. """Return the SHA1 a ref is pointing to.
  767. :param name: Name of the ref to look up
  768. :raise KeyError: when the ref (or the one it points to) does not exist
  769. :return: SHA1 it is pointing at
  770. """
  771. return self.refs[name]
  772. def get_refs(self):
  773. """Get dictionary with all refs.
  774. :return: A ``dict`` mapping ref names to SHA1s
  775. """
  776. return self.refs.as_dict()
  777. def head(self):
  778. """Return the SHA1 pointed at by HEAD."""
  779. return self.refs['HEAD']
  780. def _get_object(self, sha, cls):
  781. assert len(sha) in (20, 40)
  782. ret = self.get_object(sha)
  783. if not isinstance(ret, cls):
  784. if cls is Commit:
  785. raise NotCommitError(ret)
  786. elif cls is Blob:
  787. raise NotBlobError(ret)
  788. elif cls is Tree:
  789. raise NotTreeError(ret)
  790. elif cls is Tag:
  791. raise NotTagError(ret)
  792. else:
  793. raise Exception("Type invalid: %r != %r" % (
  794. ret.type_name, cls.type_name))
  795. return ret
  796. def get_object(self, sha):
  797. """Retrieve the object with the specified SHA.
  798. :param sha: SHA to retrieve
  799. :return: A ShaFile object
  800. :raise KeyError: when the object can not be found
  801. """
  802. return self.object_store[sha]
  803. def get_parents(self, sha):
  804. """Retrieve the parents of a specific commit.
  805. :param sha: SHA of the commit for which to retrieve the parents
  806. :return: List of parents
  807. """
  808. return self.commit(sha).parents
  809. def get_config(self):
  810. """Retrieve the config object.
  811. :return: `ConfigFile` object for the ``.git/config`` file.
  812. """
  813. from dulwich.config import ConfigFile
  814. path = os.path.join(self._controldir, 'config')
  815. try:
  816. return ConfigFile.from_path(path)
  817. except (IOError, OSError), e:
  818. if e.errno != errno.ENOENT:
  819. raise
  820. ret = ConfigFile()
  821. ret.path = path
  822. return ret
  823. def get_config_stack(self):
  824. """Return a config stack for this repository.
  825. This stack accesses the configuration for both this repository
  826. itself (.git/config) and the global configuration, which usually
  827. lives in ~/.gitconfig.
  828. :return: `Config` instance for this repository
  829. """
  830. from dulwich.config import StackedConfig
  831. backends = [self.get_config()] + StackedConfig.default_backends()
  832. return StackedConfig(backends, writable=backends[0])
  833. def commit(self, sha):
  834. """Retrieve the commit with a particular SHA.
  835. :param sha: SHA of the commit to retrieve
  836. :raise NotCommitError: If the SHA provided doesn't point at a Commit
  837. :raise KeyError: If the SHA provided didn't exist
  838. :return: A `Commit` object
  839. """
  840. warnings.warn("Repo.commit(sha) is deprecated. Use Repo[sha] instead.",
  841. category=DeprecationWarning, stacklevel=2)
  842. return self._get_object(sha, Commit)
  843. def tree(self, sha):
  844. """Retrieve the tree with a particular SHA.
  845. :param sha: SHA of the tree to retrieve
  846. :raise NotTreeError: If the SHA provided doesn't point at a Tree
  847. :raise KeyError: If the SHA provided didn't exist
  848. :return: A `Tree` object
  849. """
  850. warnings.warn("Repo.tree(sha) is deprecated. Use Repo[sha] instead.",
  851. category=DeprecationWarning, stacklevel=2)
  852. return self._get_object(sha, Tree)
  853. def tag(self, sha):
  854. """Retrieve the tag with a particular SHA.
  855. :param sha: SHA of the tag to retrieve
  856. :raise NotTagError: If the SHA provided doesn't point at a Tag
  857. :raise KeyError: If the SHA provided didn't exist
  858. :return: A `Tag` object
  859. """
  860. warnings.warn("Repo.tag(sha) is deprecated. Use Repo[sha] instead.",
  861. category=DeprecationWarning, stacklevel=2)
  862. return self._get_object(sha, Tag)
  863. def get_blob(self, sha):
  864. """Retrieve the blob with a particular SHA.
  865. :param sha: SHA of the blob to retrieve
  866. :raise NotBlobError: If the SHA provided doesn't point at a Blob
  867. :raise KeyError: If the SHA provided didn't exist
  868. :return: A `Blob` object
  869. """
  870. warnings.warn("Repo.get_blob(sha) is deprecated. Use Repo[sha] "
  871. "instead.", category=DeprecationWarning, stacklevel=2)
  872. return self._get_object(sha, Blob)
  873. def get_peeled(self, ref):
  874. """Get the peeled value of a ref.
  875. :param ref: The refname to peel.
  876. :return: The fully-peeled SHA1 of a tag object, after peeling all
  877. intermediate tags; if the original ref does not point to a tag, this
  878. will equal the original SHA1.
  879. """
  880. cached = self.refs.get_peeled(ref)
  881. if cached is not None:
  882. return cached
  883. return self.object_store.peel_sha(self.refs[ref]).id
  884. def get_walker(self, include=None, *args, **kwargs):
  885. """Obtain a walker for this repository.
  886. :param include: Iterable of SHAs of commits to include along with their
  887. ancestors. Defaults to [HEAD]
  888. :param exclude: Iterable of SHAs of commits to exclude along with their
  889. ancestors, overriding includes.
  890. :param order: ORDER_* constant specifying the order of results. Anything
  891. other than ORDER_DATE may result in O(n) memory usage.
  892. :param reverse: If True, reverse the order of output, requiring O(n)
  893. memory.
  894. :param max_entries: The maximum number of entries to yield, or None for
  895. no limit.
  896. :param paths: Iterable of file or subtree paths to show entries for.
  897. :param rename_detector: diff.RenameDetector object for detecting
  898. renames.
  899. :param follow: If True, follow path across renames/copies. Forces a
  900. default rename_detector.
  901. :param since: Timestamp to list commits after.
  902. :param until: Timestamp to list commits before.
  903. :param queue_cls: A class to use for a queue of commits, supporting the
  904. iterator protocol. The constructor takes a single argument, the
  905. Walker.
  906. :return: A `Walker` object
  907. """
  908. from dulwich.walk import Walker
  909. if include is None:
  910. include = [self.head()]
  911. return Walker(self.object_store, include, *args, **kwargs)
  912. def revision_history(self, head):
  913. """Returns a list of the commits reachable from head.
  914. :param head: The SHA of the head to list revision history for.
  915. :return: A list of commit objects reachable from head, starting with
  916. head itself, in descending commit time order.
  917. :raise MissingCommitError: if any missing commits are referenced,
  918. including if the head parameter isn't the SHA of a commit.
  919. """
  920. warnings.warn("Repo.revision_history() is deprecated."
  921. "Use dulwich.walker.Walker(repo) instead.",
  922. category=DeprecationWarning, stacklevel=2)
  923. return [e.commit for e in self.get_walker(include=[head])]
  924. def __getitem__(self, name):
  925. """Retrieve a Git object by SHA1 or ref.
  926. :param name: A Git object SHA1 or a ref name
  927. :return: A `ShaFile` object, such as a Commit or Blob
  928. :raise KeyError: when the specified ref or object does not exist
  929. """
  930. if len(name) in (20, 40):
  931. try:
  932. return self.object_store[name]
  933. except KeyError:
  934. pass
  935. try:
  936. return self.object_store[self.refs[name]]
  937. except RefFormatError:
  938. raise KeyError(name)
  939. def __contains__(self, name):
  940. """Check if a specific Git object or ref is present.
  941. :param name: Git object SHA1 or ref name
  942. """
  943. if len(name) in (20, 40):
  944. return name in self.object_store or name in self.refs
  945. else:
  946. return name in self.refs
  947. def __setitem__(self, name, value):
  948. """Set a ref.
  949. :param name: ref name
  950. :param value: Ref value - either a ShaFile object, or a hex sha
  951. """
  952. if name.startswith("refs/") or name == "HEAD":
  953. if isinstance(value, ShaFile):
  954. self.refs[name] = value.id
  955. elif isinstance(value, str):
  956. self.refs[name] = value
  957. else:
  958. raise TypeError(value)
  959. else:
  960. raise ValueError(name)
  961. def __delitem__(self, name):
  962. """Remove a ref.
  963. :param name: Name of the ref to remove
  964. """
  965. if name.startswith("refs/") or name == "HEAD":
  966. del self.refs[name]
  967. else:
  968. raise ValueError(name)
  969. def _get_user_identity(self):
  970. """Determine the identity to use for new commits.
  971. """
  972. config = self.get_config_stack()
  973. return "%s <%s>" % (
  974. config.get(("user", ), "name"),
  975. config.get(("user", ), "email"))
  976. def do_commit(self, message=None, committer=None,
  977. author=None, commit_timestamp=None,
  978. commit_timezone=None, author_timestamp=None,
  979. author_timezone=None, tree=None, encoding=None,
  980. ref='HEAD', merge_heads=None):
  981. """Create a new commit.
  982. :param message: Commit message
  983. :param committer: Committer fullname
  984. :param author: Author fullname (defaults to committer)
  985. :param commit_timestamp: Commit timestamp (defaults to now)
  986. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  987. :param author_timestamp: Author timestamp (defaults to commit timestamp)
  988. :param author_timezone: Author timestamp timezone
  989. (defaults to commit timestamp timezone)
  990. :param tree: SHA1 of the tree root to use (if not specified the
  991. current index will be committed).
  992. :param encoding: Encoding
  993. :param ref: Optional ref to commit to (defaults to current branch)
  994. :param merge_heads: Merge heads (defaults to .git/MERGE_HEADS)
  995. :return: New commit SHA1
  996. """
  997. import time
  998. c = Commit()
  999. if tree is None:
  1000. index = self.open_index()
  1001. c.tree = index.commit(self.object_store)
  1002. else:
  1003. if len(tree) != 40:
  1004. raise ValueError("tree must be a 40-byte hex sha string")
  1005. c.tree = tree
  1006. if merge_heads is None:
  1007. # FIXME: Read merge heads from .git/MERGE_HEADS
  1008. merge_heads = []
  1009. if committer is None:
  1010. committer = self._get_user_identity()
  1011. c.committer = committer
  1012. if commit_timestamp is None:
  1013. commit_timestamp = time.time()
  1014. c.commit_time = int(commit_timestamp)
  1015. if commit_timezone is None:
  1016. # FIXME: Use current user timezone rather than UTC
  1017. commit_timezone = 0
  1018. c.commit_timezone = commit_timezone
  1019. if author is None:
  1020. author = committer
  1021. c.author = author
  1022. if author_timestamp is None:
  1023. author_timestamp = commit_timestamp
  1024. c.author_time = int(author_timestamp)
  1025. if author_timezone is None:
  1026. author_timezone = commit_timezone
  1027. c.author_timezone = author_timezone
  1028. if encoding is not None:
  1029. c.encoding = encoding
  1030. if message is None:
  1031. # FIXME: Try to read commit message from .git/MERGE_MSG
  1032. raise ValueError("No commit message specified")
  1033. c.message = message
  1034. try:
  1035. old_head = self.refs[ref]
  1036. c.parents = [old_head] + merge_heads
  1037. self.object_store.add_object(c)
  1038. ok = self.refs.set_if_equals(ref, old_head, c.id)
  1039. except KeyError:
  1040. c.parents = merge_heads
  1041. self.object_store.add_object(c)
  1042. ok = self.refs.add_if_new(ref, c.id)
  1043. if not ok:
  1044. # Fail if the atomic compare-and-swap failed, leaving the commit and
  1045. # all its objects as garbage.
  1046. raise CommitError("%s changed during commit" % (ref,))
  1047. return c.id
  1048. class Repo(BaseRepo):
  1049. """A git repository backed by local disk.
  1050. To open an existing repository, call the contructor with
  1051. the path of the repository.
  1052. To create a new repository, use the Repo.init class method.
  1053. """
  1054. def __init__(self, root):
  1055. if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
  1056. self.bare = False
  1057. self._controldir = os.path.join(root, ".git")
  1058. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  1059. os.path.isdir(os.path.join(root, REFSDIR))):
  1060. self.bare = True
  1061. self._controldir = root
  1062. else:
  1063. raise NotGitRepository(
  1064. "No git repository was found at %(path)s" % dict(path=root)
  1065. )
  1066. self.path = root
  1067. object_store = DiskObjectStore(os.path.join(self.controldir(),
  1068. OBJECTDIR))
  1069. refs = DiskRefsContainer(self.controldir())
  1070. BaseRepo.__init__(self, object_store, refs)
  1071. def controldir(self):
  1072. """Return the path of the control directory."""
  1073. return self._controldir
  1074. def _put_named_file(self, path, contents):
  1075. """Write a file to the control dir with the given name and contents.
  1076. :param path: The path to the file, relative to the control dir.
  1077. :param contents: A string to write to the file.
  1078. """
  1079. path = path.lstrip(os.path.sep)
  1080. f = GitFile(os.path.join(self.controldir(), path), 'wb')
  1081. try:
  1082. f.write(contents)
  1083. finally:
  1084. f.close()
  1085. def get_named_file(self, path):
  1086. """Get a file from the control dir with a specific name.
  1087. Although the filename should be interpreted as a filename relative to
  1088. the control dir in a disk-based Repo, the object returned need not be
  1089. pointing to a file in that location.
  1090. :param path: The path to the file, relative to the control dir.
  1091. :return: An open file object, or None if the file does not exist.
  1092. """
  1093. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1094. # the dumb web serving code.
  1095. path = path.lstrip(os.path.sep)
  1096. try:
  1097. return open(os.path.join(self.controldir(), path), 'rb')
  1098. except (IOError, OSError), e:
  1099. if e.errno == errno.ENOENT:
  1100. return None
  1101. raise
  1102. def index_path(self):
  1103. """Return path to the index file."""
  1104. return os.path.join(self.controldir(), INDEX_FILENAME)
  1105. def open_index(self):
  1106. """Open the index for this repository.
  1107. :raise NoIndexPresent: If no index is present
  1108. :return: The matching `Index`
  1109. """
  1110. from dulwich.index import Index
  1111. if not self.has_index():
  1112. raise NoIndexPresent()
  1113. return Index(self.index_path())
  1114. def has_index(self):
  1115. """Check if an index is present."""
  1116. # Bare repos must never have index files; non-bare repos may have a
  1117. # missing index file, which is treated as empty.
  1118. return not self.bare
  1119. def stage(self, paths):
  1120. """Stage a set of paths.
  1121. :param paths: List of paths, relative to the repository path
  1122. """
  1123. if isinstance(paths, basestring):
  1124. paths = [paths]
  1125. from dulwich.index import index_entry_from_stat
  1126. index = self.open_index()
  1127. for path in paths:
  1128. full_path = os.path.join(self.path, path)
  1129. try:
  1130. st = os.stat(full_path)
  1131. except OSError:
  1132. # File no longer exists
  1133. try:
  1134. del index[path]
  1135. except KeyError:
  1136. pass # already removed
  1137. else:
  1138. blob = Blob()
  1139. f = open(full_path, 'rb')
  1140. try:
  1141. blob.data = f.read()
  1142. finally:
  1143. f.close()
  1144. self.object_store.add_object(blob)
  1145. index[path] = index_entry_from_stat(st, blob.id, 0)
  1146. index.write()
  1147. def clone(self, target_path, mkdir=True, bare=False,
  1148. origin="origin"):
  1149. """Clone this repository.
  1150. :param target_path: Target path
  1151. :param mkdir: Create the target directory
  1152. :param bare: Whether to create a bare repository
  1153. :param origin: Base name for refs in target repository
  1154. cloned from this repository
  1155. :return: Created repository as `Repo`
  1156. """
  1157. if not bare:
  1158. target = self.init(target_path, mkdir=mkdir)
  1159. else:
  1160. target = self.init_bare(target_path)
  1161. self.fetch(target)
  1162. target.refs.import_refs(
  1163. 'refs/remotes/' + origin, self.refs.as_dict('refs/heads'))
  1164. target.refs.import_refs(
  1165. 'refs/tags', self.refs.as_dict('refs/tags'))
  1166. try:
  1167. target.refs.add_if_new(
  1168. 'refs/heads/master',
  1169. self.refs['refs/heads/master'])
  1170. except KeyError:
  1171. pass
  1172. # Update target head
  1173. head, head_sha = self.refs._follow('HEAD')
  1174. target.refs.set_symbolic_ref('HEAD', head)
  1175. target['HEAD'] = head_sha
  1176. if not bare:
  1177. # Checkout HEAD to target dir
  1178. from dulwich.index import build_index_from_tree
  1179. build_index_from_tree(target.path, target.index_path(),
  1180. target.object_store, target['HEAD'].tree)
  1181. return target
  1182. def __repr__(self):
  1183. return "<Repo at %r>" % self.path
  1184. @classmethod
  1185. def _init_maybe_bare(cls, path, bare):
  1186. for d in BASE_DIRECTORIES:
  1187. os.mkdir(os.path.join(path, *d))
  1188. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  1189. ret = cls(path)
  1190. ret.refs.set_symbolic_ref("HEAD", "refs/heads/master")
  1191. ret._init_files(bare)
  1192. return ret
  1193. @classmethod
  1194. def init(cls, path, mkdir=False):
  1195. """Create a new repository.
  1196. :param path: Path in which to create the repository
  1197. :param mkdir: Whether to create the directory
  1198. :return: `Repo` instance
  1199. """
  1200. if mkdir:
  1201. os.mkdir(path)
  1202. controldir = os.path.join(path, ".git")
  1203. os.mkdir(controldir)
  1204. cls._init_maybe_bare(controldir, False)
  1205. return cls(path)
  1206. @classmethod
  1207. def init_bare(cls, path):
  1208. """Create a new bare repository.
  1209. ``path`` should already exist and be an emty directory.
  1210. :param path: Path to create bare repository in
  1211. :return: a `Repo` instance
  1212. """
  1213. return cls._init_maybe_bare(path, True)
  1214. create = init_bare
  1215. class MemoryRepo(BaseRepo):
  1216. """Repo that stores refs, objects, and named files in memory.
  1217. MemoryRepos are always bare: they have no working tree and no index, since
  1218. those have a stronger dependency on the filesystem.
  1219. """
  1220. def __init__(self):
  1221. BaseRepo.__init__(self, MemoryObjectStore(), DictRefsContainer({}))
  1222. self._named_files = {}
  1223. self.bare = True
  1224. def _put_named_file(self, path, contents):
  1225. """Write a file to the control dir with the given name and contents.
  1226. :param path: The path to the file, relative to the control dir.
  1227. :param contents: A string to write to the file.
  1228. """
  1229. self._named_files[path] = contents
  1230. def get_named_file(self, path):
  1231. """Get a file from the control dir with a specific name.
  1232. Although the filename should be interpreted as a filename relative to
  1233. the control dir in a disk-baked Repo, the object returned need not be
  1234. pointing to a file in that location.
  1235. :param path: The path to the file, relative to the control dir.
  1236. :return: An open file object, or None if the file does not exist.
  1237. """
  1238. contents = self._named_files.get(path, None)
  1239. if contents is None:
  1240. return None
  1241. return StringIO(contents)
  1242. def open_index(self):
  1243. """Fail to open index for this repo, since it is bare.
  1244. :raise NoIndexPresent: Raised when no index is present
  1245. """
  1246. raise NoIndexPresent()
  1247. @classmethod
  1248. def init_bare(cls, objects, refs):
  1249. """Create a new bare repository in memory.
  1250. :param objects: Objects for the new repository,
  1251. as iterable
  1252. :param refs: Refs as dictionary, mapping names
  1253. to object SHA1s
  1254. """
  1255. ret = cls()
  1256. for obj in objects:
  1257. ret.object_store.add_object(obj)
  1258. for refname, sha in refs.iteritems():
  1259. ret.refs[refname] = sha
  1260. ret._init_files(bare=True)
  1261. return ret