2
0

repo.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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. :raises NoIndexPresent: If no index is present
  716. :return: Index instance
  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. return self.refs[name]
  768. def get_refs(self):
  769. """Get dictionary with all refs."""
  770. return self.refs.as_dict()
  771. def head(self):
  772. """Return the SHA1 pointed at by HEAD."""
  773. return self.refs['HEAD']
  774. def _get_object(self, sha, cls):
  775. assert len(sha) in (20, 40)
  776. ret = self.get_object(sha)
  777. if not isinstance(ret, cls):
  778. if cls is Commit:
  779. raise NotCommitError(ret)
  780. elif cls is Blob:
  781. raise NotBlobError(ret)
  782. elif cls is Tree:
  783. raise NotTreeError(ret)
  784. elif cls is Tag:
  785. raise NotTagError(ret)
  786. else:
  787. raise Exception("Type invalid: %r != %r" % (
  788. ret.type_name, cls.type_name))
  789. return ret
  790. def get_object(self, sha):
  791. """Retrieve the object with the specified SHA.
  792. :param sha: SHA to retrieve
  793. :return: A ShaFile object
  794. :raise KeyError: when the object can not be found
  795. """
  796. return self.object_store[sha]
  797. def get_parents(self, sha):
  798. """Retrieve the parents of a specific commit.
  799. :param sha: SHA of the commit for which to retrieve the parents
  800. :return: List of parents
  801. """
  802. return self.commit(sha).parents
  803. def get_config(self):
  804. """Retrieve the config object.
  805. :return: `ConfigFile` object for the ``.git/config`` file.
  806. """
  807. from dulwich.config import ConfigFile
  808. path = os.path.join(self._controldir, 'config')
  809. try:
  810. return ConfigFile.from_path(path)
  811. except (IOError, OSError), e:
  812. if e.errno != errno.ENOENT:
  813. raise
  814. ret = ConfigFile()
  815. ret.path = path
  816. return ret
  817. def get_config_stack(self):
  818. """Return a config stack for this repository.
  819. This stack accesses the configuration for both this repository
  820. itself (.git/config) and the global configuration, which usually
  821. lives in ~/.gitconfig.
  822. :return: `Config` instance for this repository
  823. """
  824. from dulwich.config import StackedConfig
  825. backends = [self.get_config()] + StackedConfig.default_backends()
  826. return StackedConfig(backends, writable=backends[0])
  827. def commit(self, sha):
  828. """Retrieve the commit with a particular SHA.
  829. :param sha: SHA of the commit to retrieve
  830. :raise NotCommitError: If the SHA provided doesn't point at a Commit
  831. :raise KeyError: If the SHA provided didn't exist
  832. :return: A `Commit` object
  833. """
  834. warnings.warn("Repo.commit(sha) is deprecated. Use Repo[sha] instead.",
  835. category=DeprecationWarning, stacklevel=2)
  836. return self._get_object(sha, Commit)
  837. def tree(self, sha):
  838. """Retrieve the tree with a particular SHA.
  839. :param sha: SHA of the tree to retrieve
  840. :raise NotTreeError: If the SHA provided doesn't point at a Tree
  841. :raise KeyError: If the SHA provided didn't exist
  842. :return: A `Tree` object
  843. """
  844. warnings.warn("Repo.tree(sha) is deprecated. Use Repo[sha] instead.",
  845. category=DeprecationWarning, stacklevel=2)
  846. return self._get_object(sha, Tree)
  847. def tag(self, sha):
  848. """Retrieve the tag with a particular SHA.
  849. :param sha: SHA of the tag to retrieve
  850. :raise NotTagError: If the SHA provided doesn't point at a Tag
  851. :raise KeyError: If the SHA provided didn't exist
  852. :return: A `Tag` object
  853. """
  854. warnings.warn("Repo.tag(sha) is deprecated. Use Repo[sha] instead.",
  855. category=DeprecationWarning, stacklevel=2)
  856. return self._get_object(sha, Tag)
  857. def get_blob(self, sha):
  858. """Retrieve the blob with a particular SHA.
  859. :param sha: SHA of the blob to retrieve
  860. :raise NotBlobError: If the SHA provided doesn't point at a Blob
  861. :raise KeyError: If the SHA provided didn't exist
  862. :return: A `Blob` object
  863. """
  864. warnings.warn("Repo.get_blob(sha) is deprecated. Use Repo[sha] "
  865. "instead.", category=DeprecationWarning, stacklevel=2)
  866. return self._get_object(sha, Blob)
  867. def get_peeled(self, ref):
  868. """Get the peeled value of a ref.
  869. :param ref: The refname to peel.
  870. :return: The fully-peeled SHA1 of a tag object, after peeling all
  871. intermediate tags; if the original ref does not point to a tag, this
  872. will equal the original SHA1.
  873. """
  874. cached = self.refs.get_peeled(ref)
  875. if cached is not None:
  876. return cached
  877. return self.object_store.peel_sha(self.refs[ref]).id
  878. def get_walker(self, include=None, *args, **kwargs):
  879. """Obtain a walker for this repository.
  880. :param include: Iterable of SHAs of commits to include along with their
  881. ancestors. Defaults to [HEAD]
  882. :param exclude: Iterable of SHAs of commits to exclude along with their
  883. ancestors, overriding includes.
  884. :param order: ORDER_* constant specifying the order of results. Anything
  885. other than ORDER_DATE may result in O(n) memory usage.
  886. :param reverse: If True, reverse the order of output, requiring O(n)
  887. memory.
  888. :param max_entries: The maximum number of entries to yield, or None for
  889. no limit.
  890. :param paths: Iterable of file or subtree paths to show entries for.
  891. :param rename_detector: diff.RenameDetector object for detecting
  892. renames.
  893. :param follow: If True, follow path across renames/copies. Forces a
  894. default rename_detector.
  895. :param since: Timestamp to list commits after.
  896. :param until: Timestamp to list commits before.
  897. :param queue_cls: A class to use for a queue of commits, supporting the
  898. iterator protocol. The constructor takes a single argument, the
  899. Walker.
  900. """
  901. from dulwich.walk import Walker
  902. if include is None:
  903. include = [self.head()]
  904. return Walker(self.object_store, include, *args, **kwargs)
  905. def revision_history(self, head):
  906. """Returns a list of the commits reachable from head.
  907. :param head: The SHA of the head to list revision history for.
  908. :return: A list of commit objects reachable from head, starting with
  909. head itself, in descending commit time order.
  910. :raise MissingCommitError: if any missing commits are referenced,
  911. including if the head parameter isn't the SHA of a commit.
  912. """
  913. warnings.warn("Repo.revision_history() is deprecated."
  914. "Use dulwich.walker.Walker(repo) instead.",
  915. category=DeprecationWarning, stacklevel=2)
  916. return [e.commit for e in self.get_walker(include=[head])]
  917. def __getitem__(self, name):
  918. """Retrieve a Git object by SHA1 or ref.
  919. :param name: A Git object SHA1 or a ref name
  920. :return: A `ShaFile` object, such as a Commit or Blob
  921. :raise KeyError: when the specified ref or object does not exist
  922. """
  923. if len(name) in (20, 40):
  924. try:
  925. return self.object_store[name]
  926. except KeyError:
  927. pass
  928. try:
  929. return self.object_store[self.refs[name]]
  930. except RefFormatError:
  931. raise KeyError(name)
  932. def __contains__(self, name):
  933. """Check if a specific Git object or ref is present.
  934. :param name: Git object SHA1 or ref name
  935. """
  936. if len(name) in (20, 40):
  937. return name in self.object_store or name in self.refs
  938. else:
  939. return name in self.refs
  940. def __setitem__(self, name, value):
  941. """Set a ref.
  942. :param name: ref name
  943. :param value: Ref value - either a ShaFile object, or a hex sha
  944. """
  945. if name.startswith("refs/") or name == "HEAD":
  946. if isinstance(value, ShaFile):
  947. self.refs[name] = value.id
  948. elif isinstance(value, str):
  949. self.refs[name] = value
  950. else:
  951. raise TypeError(value)
  952. else:
  953. raise ValueError(name)
  954. def __delitem__(self, name):
  955. """Remove a ref.
  956. :param name: Name of the ref to remove
  957. """
  958. if name.startswith("refs/") or name == "HEAD":
  959. del self.refs[name]
  960. else:
  961. raise ValueError(name)
  962. def _get_user_identity(self):
  963. config = self.get_config_stack()
  964. return "%s <%s>" % (
  965. config.get(("user", ), "name"),
  966. config.get(("user", ), "email"))
  967. def do_commit(self, message=None, committer=None,
  968. author=None, commit_timestamp=None,
  969. commit_timezone=None, author_timestamp=None,
  970. author_timezone=None, tree=None, encoding=None,
  971. ref='HEAD', merge_heads=None):
  972. """Create a new commit.
  973. :param message: Commit message
  974. :param committer: Committer fullname
  975. :param author: Author fullname (defaults to committer)
  976. :param commit_timestamp: Commit timestamp (defaults to now)
  977. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  978. :param author_timestamp: Author timestamp (defaults to commit timestamp)
  979. :param author_timezone: Author timestamp timezone
  980. (defaults to commit timestamp timezone)
  981. :param tree: SHA1 of the tree root to use (if not specified the
  982. current index will be committed).
  983. :param encoding: Encoding
  984. :param ref: Optional ref to commit to (defaults to current branch)
  985. :param merge_heads: Merge heads (defaults to .git/MERGE_HEADS)
  986. :return: New commit SHA1
  987. """
  988. import time
  989. c = Commit()
  990. if tree is None:
  991. index = self.open_index()
  992. c.tree = index.commit(self.object_store)
  993. else:
  994. if len(tree) != 40:
  995. raise ValueError("tree must be a 40-byte hex sha string")
  996. c.tree = tree
  997. if merge_heads is None:
  998. # FIXME: Read merge heads from .git/MERGE_HEADS
  999. merge_heads = []
  1000. if committer is None:
  1001. committer = self._get_user_identity()
  1002. c.committer = committer
  1003. if commit_timestamp is None:
  1004. commit_timestamp = time.time()
  1005. c.commit_time = int(commit_timestamp)
  1006. if commit_timezone is None:
  1007. # FIXME: Use current user timezone rather than UTC
  1008. commit_timezone = 0
  1009. c.commit_timezone = commit_timezone
  1010. if author is None:
  1011. author = committer
  1012. c.author = author
  1013. if author_timestamp is None:
  1014. author_timestamp = commit_timestamp
  1015. c.author_time = int(author_timestamp)
  1016. if author_timezone is None:
  1017. author_timezone = commit_timezone
  1018. c.author_timezone = author_timezone
  1019. if encoding is not None:
  1020. c.encoding = encoding
  1021. if message is None:
  1022. # FIXME: Try to read commit message from .git/MERGE_MSG
  1023. raise ValueError("No commit message specified")
  1024. c.message = message
  1025. try:
  1026. old_head = self.refs[ref]
  1027. c.parents = [old_head] + merge_heads
  1028. self.object_store.add_object(c)
  1029. ok = self.refs.set_if_equals(ref, old_head, c.id)
  1030. except KeyError:
  1031. c.parents = merge_heads
  1032. self.object_store.add_object(c)
  1033. ok = self.refs.add_if_new(ref, c.id)
  1034. if not ok:
  1035. # Fail if the atomic compare-and-swap failed, leaving the commit and
  1036. # all its objects as garbage.
  1037. raise CommitError("%s changed during commit" % (ref,))
  1038. return c.id
  1039. class Repo(BaseRepo):
  1040. """A git repository backed by local disk.
  1041. To open an existing repository, call the contructor with
  1042. the path of the repository.
  1043. To create a new repository, use the Repo.init class method.
  1044. """
  1045. def __init__(self, root):
  1046. if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
  1047. self.bare = False
  1048. self._controldir = os.path.join(root, ".git")
  1049. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  1050. os.path.isdir(os.path.join(root, REFSDIR))):
  1051. self.bare = True
  1052. self._controldir = root
  1053. else:
  1054. raise NotGitRepository(root)
  1055. self.path = root
  1056. object_store = DiskObjectStore(os.path.join(self.controldir(),
  1057. OBJECTDIR))
  1058. refs = DiskRefsContainer(self.controldir())
  1059. BaseRepo.__init__(self, object_store, refs)
  1060. def controldir(self):
  1061. """Return the path of the control directory."""
  1062. return self._controldir
  1063. def _put_named_file(self, path, contents):
  1064. """Write a file to the control dir with the given name and contents.
  1065. :param path: The path to the file, relative to the control dir.
  1066. :param contents: A string to write to the file.
  1067. """
  1068. path = path.lstrip(os.path.sep)
  1069. f = GitFile(os.path.join(self.controldir(), path), 'wb')
  1070. try:
  1071. f.write(contents)
  1072. finally:
  1073. f.close()
  1074. def get_named_file(self, path):
  1075. """Get a file from the control dir with a specific name.
  1076. Although the filename should be interpreted as a filename relative to
  1077. the control dir in a disk-based Repo, the object returned need not be
  1078. pointing to a file in that location.
  1079. :param path: The path to the file, relative to the control dir.
  1080. :return: An open file object, or None if the file does not exist.
  1081. """
  1082. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1083. # the dumb web serving code.
  1084. path = path.lstrip(os.path.sep)
  1085. try:
  1086. return open(os.path.join(self.controldir(), path), 'rb')
  1087. except (IOError, OSError), e:
  1088. if e.errno == errno.ENOENT:
  1089. return None
  1090. raise
  1091. def index_path(self):
  1092. """Return path to the index file."""
  1093. return os.path.join(self.controldir(), INDEX_FILENAME)
  1094. def open_index(self):
  1095. """Open the index for this repository."""
  1096. from dulwich.index import Index
  1097. if not self.has_index():
  1098. raise NoIndexPresent()
  1099. return Index(self.index_path())
  1100. def has_index(self):
  1101. """Check if an index is present."""
  1102. # Bare repos must never have index files; non-bare repos may have a
  1103. # missing index file, which is treated as empty.
  1104. return not self.bare
  1105. def stage(self, paths):
  1106. """Stage a set of paths.
  1107. :param paths: List of paths, relative to the repository path
  1108. """
  1109. if isinstance(paths, basestring):
  1110. paths = [paths]
  1111. from dulwich.index import index_entry_from_stat
  1112. index = self.open_index()
  1113. for path in paths:
  1114. full_path = os.path.join(self.path, path)
  1115. try:
  1116. st = os.stat(full_path)
  1117. except OSError:
  1118. # File no longer exists
  1119. try:
  1120. del index[path]
  1121. except KeyError:
  1122. pass # already removed
  1123. else:
  1124. blob = Blob()
  1125. f = open(full_path, 'rb')
  1126. try:
  1127. blob.data = f.read()
  1128. finally:
  1129. f.close()
  1130. self.object_store.add_object(blob)
  1131. index[path] = index_entry_from_stat(st, blob.id, 0)
  1132. index.write()
  1133. def clone(self, target_path, mkdir=True, bare=False,
  1134. origin="origin"):
  1135. """Clone this repository.
  1136. :param target_path: Target path
  1137. :param mkdir: Create the target directory
  1138. :param bare: Whether to create a bare repository
  1139. :return: Created repository
  1140. """
  1141. if not bare:
  1142. target = self.init(target_path, mkdir=mkdir)
  1143. else:
  1144. target = self.init_bare(target_path)
  1145. self.fetch(target)
  1146. target.refs.import_refs(
  1147. 'refs/remotes/'+origin, self.refs.as_dict('refs/heads'))
  1148. target.refs.import_refs(
  1149. 'refs/tags', self.refs.as_dict('refs/tags'))
  1150. try:
  1151. target.refs.add_if_new(
  1152. 'refs/heads/master',
  1153. self.refs['refs/heads/master'])
  1154. except KeyError:
  1155. pass
  1156. return target
  1157. def __repr__(self):
  1158. return "<Repo at %r>" % self.path
  1159. @classmethod
  1160. def _init_maybe_bare(cls, path, bare):
  1161. for d in BASE_DIRECTORIES:
  1162. os.mkdir(os.path.join(path, *d))
  1163. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  1164. ret = cls(path)
  1165. ret.refs.set_symbolic_ref("HEAD", "refs/heads/master")
  1166. ret._init_files(bare)
  1167. return ret
  1168. @classmethod
  1169. def init(cls, path, mkdir=False):
  1170. """Create a new repository.
  1171. :param path: Path in which to create the repository
  1172. :param mkdir: Whether to create the directory
  1173. :return: `Repo` instance
  1174. """
  1175. if mkdir:
  1176. os.mkdir(path)
  1177. controldir = os.path.join(path, ".git")
  1178. os.mkdir(controldir)
  1179. cls._init_maybe_bare(controldir, False)
  1180. return cls(path)
  1181. @classmethod
  1182. def init_bare(cls, path):
  1183. """Create a new bare repository.
  1184. ``path`` should already exist and be an emty directory.
  1185. :param path: Path to create bare repository in
  1186. :return: a `Repo` instance
  1187. """
  1188. return cls._init_maybe_bare(path, True)
  1189. create = init_bare
  1190. class MemoryRepo(BaseRepo):
  1191. """Repo that stores refs, objects, and named files in memory.
  1192. MemoryRepos are always bare: they have no working tree and no index, since
  1193. those have a stronger dependency on the filesystem.
  1194. """
  1195. def __init__(self):
  1196. BaseRepo.__init__(self, MemoryObjectStore(), DictRefsContainer({}))
  1197. self._named_files = {}
  1198. self.bare = True
  1199. def _put_named_file(self, path, contents):
  1200. """Write a file to the control dir with the given name and contents.
  1201. :param path: The path to the file, relative to the control dir.
  1202. :param contents: A string to write to the file.
  1203. """
  1204. self._named_files[path] = contents
  1205. def get_named_file(self, path):
  1206. """Get a file from the control dir with a specific name.
  1207. Although the filename should be interpreted as a filename relative to
  1208. the control dir in a disk-baked Repo, the object returned need not be
  1209. pointing to a file in that location.
  1210. :param path: The path to the file, relative to the control dir.
  1211. :return: An open file object, or None if the file does not exist.
  1212. """
  1213. contents = self._named_files.get(path, None)
  1214. if contents is None:
  1215. return None
  1216. return StringIO(contents)
  1217. def open_index(self):
  1218. """Fail to open index for this repo, since it is bare."""
  1219. raise NoIndexPresent()
  1220. @classmethod
  1221. def init_bare(cls, objects, refs):
  1222. """Create a new bare repository in memory.
  1223. :param objects: Objects for the new repository,
  1224. as iterable
  1225. :param refs: Refs as dictionary, mapping names
  1226. to object SHA1s
  1227. """
  1228. ret = cls()
  1229. for obj in objects:
  1230. ret.object_store.add_object(obj)
  1231. for refname, sha in refs.iteritems():
  1232. ret.refs[refname] = sha
  1233. ret._init_files(bare=True)
  1234. return ret