repo.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  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(root)
  1064. self.path = root
  1065. object_store = DiskObjectStore(os.path.join(self.controldir(),
  1066. OBJECTDIR))
  1067. refs = DiskRefsContainer(self.controldir())
  1068. BaseRepo.__init__(self, object_store, refs)
  1069. def controldir(self):
  1070. """Return the path of the control directory."""
  1071. return self._controldir
  1072. def _put_named_file(self, path, contents):
  1073. """Write a file to the control dir with the given name and contents.
  1074. :param path: The path to the file, relative to the control dir.
  1075. :param contents: A string to write to the file.
  1076. """
  1077. path = path.lstrip(os.path.sep)
  1078. f = GitFile(os.path.join(self.controldir(), path), 'wb')
  1079. try:
  1080. f.write(contents)
  1081. finally:
  1082. f.close()
  1083. def get_named_file(self, path):
  1084. """Get a file from the control dir with a specific name.
  1085. Although the filename should be interpreted as a filename relative to
  1086. the control dir in a disk-based Repo, the object returned need not be
  1087. pointing to a file in that location.
  1088. :param path: The path to the file, relative to the control dir.
  1089. :return: An open file object, or None if the file does not exist.
  1090. """
  1091. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1092. # the dumb web serving code.
  1093. path = path.lstrip(os.path.sep)
  1094. try:
  1095. return open(os.path.join(self.controldir(), path), 'rb')
  1096. except (IOError, OSError), e:
  1097. if e.errno == errno.ENOENT:
  1098. return None
  1099. raise
  1100. def index_path(self):
  1101. """Return path to the index file."""
  1102. return os.path.join(self.controldir(), INDEX_FILENAME)
  1103. def open_index(self):
  1104. """Open the index for this repository.
  1105. :raise NoIndexPresent: If no index is present
  1106. :return: The matching `Index`
  1107. """
  1108. from dulwich.index import Index
  1109. if not self.has_index():
  1110. raise NoIndexPresent()
  1111. return Index(self.index_path())
  1112. def has_index(self):
  1113. """Check if an index is present."""
  1114. # Bare repos must never have index files; non-bare repos may have a
  1115. # missing index file, which is treated as empty.
  1116. return not self.bare
  1117. def stage(self, paths):
  1118. """Stage a set of paths.
  1119. :param paths: List of paths, relative to the repository path
  1120. """
  1121. if isinstance(paths, basestring):
  1122. paths = [paths]
  1123. from dulwich.index import index_entry_from_stat
  1124. index = self.open_index()
  1125. for path in paths:
  1126. full_path = os.path.join(self.path, path)
  1127. try:
  1128. st = os.stat(full_path)
  1129. except OSError:
  1130. # File no longer exists
  1131. try:
  1132. del index[path]
  1133. except KeyError:
  1134. pass # already removed
  1135. else:
  1136. blob = Blob()
  1137. f = open(full_path, 'rb')
  1138. try:
  1139. blob.data = f.read()
  1140. finally:
  1141. f.close()
  1142. self.object_store.add_object(blob)
  1143. index[path] = index_entry_from_stat(st, blob.id, 0)
  1144. index.write()
  1145. def clone(self, target_path, mkdir=True, bare=False,
  1146. origin="origin"):
  1147. """Clone this repository.
  1148. :param target_path: Target path
  1149. :param mkdir: Create the target directory
  1150. :param bare: Whether to create a bare repository
  1151. :param origin: Base name for refs in target repository
  1152. cloned from this repository
  1153. :return: Created repository as `Repo`
  1154. """
  1155. if not bare:
  1156. target = self.init(target_path, mkdir=mkdir)
  1157. else:
  1158. target = self.init_bare(target_path)
  1159. self.fetch(target)
  1160. target.refs.import_refs(
  1161. 'refs/remotes/'+origin, self.refs.as_dict('refs/heads'))
  1162. target.refs.import_refs(
  1163. 'refs/tags', self.refs.as_dict('refs/tags'))
  1164. try:
  1165. target.refs.add_if_new(
  1166. 'refs/heads/master',
  1167. self.refs['refs/heads/master'])
  1168. except KeyError:
  1169. pass
  1170. return target
  1171. def __repr__(self):
  1172. return "<Repo at %r>" % self.path
  1173. @classmethod
  1174. def _init_maybe_bare(cls, path, bare):
  1175. for d in BASE_DIRECTORIES:
  1176. os.mkdir(os.path.join(path, *d))
  1177. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  1178. ret = cls(path)
  1179. ret.refs.set_symbolic_ref("HEAD", "refs/heads/master")
  1180. ret._init_files(bare)
  1181. return ret
  1182. @classmethod
  1183. def init(cls, path, mkdir=False):
  1184. """Create a new repository.
  1185. :param path: Path in which to create the repository
  1186. :param mkdir: Whether to create the directory
  1187. :return: `Repo` instance
  1188. """
  1189. if mkdir:
  1190. os.mkdir(path)
  1191. controldir = os.path.join(path, ".git")
  1192. os.mkdir(controldir)
  1193. cls._init_maybe_bare(controldir, False)
  1194. return cls(path)
  1195. @classmethod
  1196. def init_bare(cls, path):
  1197. """Create a new bare repository.
  1198. ``path`` should already exist and be an emty directory.
  1199. :param path: Path to create bare repository in
  1200. :return: a `Repo` instance
  1201. """
  1202. return cls._init_maybe_bare(path, True)
  1203. create = init_bare
  1204. class MemoryRepo(BaseRepo):
  1205. """Repo that stores refs, objects, and named files in memory.
  1206. MemoryRepos are always bare: they have no working tree and no index, since
  1207. those have a stronger dependency on the filesystem.
  1208. """
  1209. def __init__(self):
  1210. BaseRepo.__init__(self, MemoryObjectStore(), DictRefsContainer({}))
  1211. self._named_files = {}
  1212. self.bare = True
  1213. def _put_named_file(self, path, contents):
  1214. """Write a file to the control dir with the given name and contents.
  1215. :param path: The path to the file, relative to the control dir.
  1216. :param contents: A string to write to the file.
  1217. """
  1218. self._named_files[path] = contents
  1219. def get_named_file(self, path):
  1220. """Get a file from the control dir with a specific name.
  1221. Although the filename should be interpreted as a filename relative to
  1222. the control dir in a disk-baked Repo, the object returned need not be
  1223. pointing to a file in that location.
  1224. :param path: The path to the file, relative to the control dir.
  1225. :return: An open file object, or None if the file does not exist.
  1226. """
  1227. contents = self._named_files.get(path, None)
  1228. if contents is None:
  1229. return None
  1230. return StringIO(contents)
  1231. def open_index(self):
  1232. """Fail to open index for this repo, since it is bare.
  1233. :raise NoIndexPresent: Raised when no index is present
  1234. """
  1235. raise NoIndexPresent()
  1236. @classmethod
  1237. def init_bare(cls, objects, refs):
  1238. """Create a new bare repository in memory.
  1239. :param objects: Objects for the new repository,
  1240. as iterable
  1241. :param refs: Refs as dictionary, mapping names
  1242. to object SHA1s
  1243. """
  1244. ret = cls()
  1245. for obj in objects:
  1246. ret.object_store.add_object(obj)
  1247. for refname, sha in refs.iteritems():
  1248. ret.refs[refname] = sha
  1249. ret._init_files(bare=True)
  1250. return ret