2
0

repo.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. # repo.py -- For dealing wih 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. import ConfigParser
  22. import errno
  23. import os
  24. from dulwich.errors import (
  25. MissingCommitError,
  26. NoIndexPresent,
  27. NotBlobError,
  28. NotCommitError,
  29. NotGitRepository,
  30. NotTreeError,
  31. PackedRefsException,
  32. )
  33. from dulwich.file import (
  34. ensure_dir_exists,
  35. GitFile,
  36. )
  37. from dulwich.object_store import (
  38. DiskObjectStore,
  39. )
  40. from dulwich.objects import (
  41. Blob,
  42. Commit,
  43. ShaFile,
  44. Tag,
  45. Tree,
  46. hex_to_sha,
  47. )
  48. OBJECTDIR = 'objects'
  49. SYMREF = 'ref: '
  50. REFSDIR = 'refs'
  51. REFSDIR_TAGS = 'tags'
  52. REFSDIR_HEADS = 'heads'
  53. INDEX_FILENAME = "index"
  54. BASE_DIRECTORIES = [
  55. [OBJECTDIR],
  56. [OBJECTDIR, "info"],
  57. [OBJECTDIR, "pack"],
  58. ["branches"],
  59. [REFSDIR],
  60. [REFSDIR, REFSDIR_TAGS],
  61. [REFSDIR, REFSDIR_HEADS],
  62. ["hooks"],
  63. ["info"]
  64. ]
  65. def read_info_refs(f):
  66. ret = {}
  67. for l in f.readlines():
  68. (sha, name) = l.rstrip("\n").split("\t", 1)
  69. ret[name] = sha
  70. return ret
  71. def check_ref_format(refname):
  72. """Check if a refname is correctly formatted.
  73. Implements all the same rules as git-check-ref-format[1].
  74. [1] http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  75. :param refname: The refname to check
  76. :return: True if refname is valid, False otherwise
  77. """
  78. # These could be combined into one big expression, but are listed separately
  79. # to parallel [1].
  80. if '/.' in refname or refname.startswith('.'):
  81. return False
  82. if '/' not in refname:
  83. return False
  84. if '..' in refname:
  85. return False
  86. for c in refname:
  87. if ord(c) < 040 or c in '\177 ~^:?*[':
  88. return False
  89. if refname[-1] in '/.':
  90. return False
  91. if refname.endswith('.lock'):
  92. return False
  93. if '@{' in refname:
  94. return False
  95. if '\\' in refname:
  96. return False
  97. return True
  98. class RefsContainer(object):
  99. """A container for refs."""
  100. def set_ref(self, name, other):
  101. """Make a ref point at another ref.
  102. :param name: Name of the ref to set
  103. :param other: Name of the ref to point at
  104. """
  105. self[name] = SYMREF + other + '\n'
  106. def get_packed_refs(self):
  107. """Get contents of the packed-refs file.
  108. :return: Dictionary mapping ref names to SHA1s
  109. :note: Will return an empty dictionary when no packed-refs file is
  110. present.
  111. """
  112. raise NotImplementedError(self.get_packed_refs)
  113. def import_refs(self, base, other):
  114. for name, value in other.iteritems():
  115. self["%s/%s" % (base, name)] = value
  116. def keys(self, base=None):
  117. """Refs present in this container.
  118. :param base: An optional base to return refs under
  119. :return: An unsorted set of valid refs in this container, including
  120. packed refs.
  121. """
  122. if base is not None:
  123. return self.subkeys(base)
  124. else:
  125. return self.allkeys()
  126. def subkeys(self, base):
  127. keys = set()
  128. for refname in self.allkeys():
  129. if refname.startswith(base):
  130. keys.add(refname)
  131. return keys
  132. def as_dict(self, base=None):
  133. """Return the contents of this container as a dictionary.
  134. """
  135. ret = {}
  136. keys = self.keys(base)
  137. if base is None:
  138. base = ""
  139. for key in keys:
  140. try:
  141. ret[key] = self[("%s/%s" % (base, key)).strip("/")]
  142. except KeyError:
  143. continue # Unable to resolve
  144. return ret
  145. def _check_refname(self, name):
  146. """Ensure a refname is valid and lives in refs or is HEAD.
  147. HEAD is not a valid refname according to git-check-ref-format, but this
  148. class needs to be able to touch HEAD. Also, check_ref_format expects
  149. refnames without the leading 'refs/', but this class requires that
  150. so it cannot touch anything outside the refs dir (or HEAD).
  151. :param name: The name of the reference.
  152. :raises KeyError: if a refname is not HEAD or is otherwise not valid.
  153. """
  154. if name == 'HEAD':
  155. return
  156. if not name.startswith('refs/') or not check_ref_format(name[5:]):
  157. raise KeyError(name)
  158. def read_loose_ref(self, name):
  159. """Read a loose reference and return its contents.
  160. :param name: the refname to read
  161. :return: The contents of the ref file, or None if it does
  162. not exist.
  163. """
  164. raise NotImplementedError(self.read_loose_ref)
  165. def _follow(self, name):
  166. """Follow a reference name.
  167. :return: a tuple of (refname, sha), where refname is the name of the
  168. last reference in the symbolic reference chain
  169. """
  170. self._check_refname(name)
  171. contents = SYMREF + name
  172. depth = 0
  173. while contents.startswith(SYMREF):
  174. refname = contents[len(SYMREF):]
  175. contents = self.read_loose_ref(refname)
  176. if not contents:
  177. contents = self.get_packed_refs().get(refname, None)
  178. if not contents:
  179. break
  180. depth += 1
  181. if depth > 5:
  182. raise KeyError(name)
  183. return refname, contents
  184. def __getitem__(self, name):
  185. """Get the SHA1 for a reference name.
  186. This method follows all symbolic references.
  187. """
  188. _, sha = self._follow(name)
  189. if sha is None:
  190. raise KeyError(name)
  191. return sha
  192. class DictRefsContainer(RefsContainer):
  193. def __init__(self, refs):
  194. self._refs = refs
  195. def allkeys(self):
  196. return self._refs.keys()
  197. def read_loose_ref(self, name):
  198. return self._refs[name]
  199. class DiskRefsContainer(RefsContainer):
  200. """Refs container that reads refs from disk."""
  201. def __init__(self, path):
  202. self.path = path
  203. self._packed_refs = None
  204. self._peeled_refs = {}
  205. def __repr__(self):
  206. return "%s(%r)" % (self.__class__.__name__, self.path)
  207. def subkeys(self, base):
  208. keys = set()
  209. path = self.refpath(base)
  210. for root, dirs, files in os.walk(path):
  211. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  212. for filename in files:
  213. refname = ("%s/%s" % (dir, filename)).strip("/")
  214. # check_ref_format requires at least one /, so we prepend the
  215. # base before calling it.
  216. if check_ref_format("%s/%s" % (base, refname)):
  217. keys.add(refname)
  218. for key in self.get_packed_refs():
  219. if key.startswith(base):
  220. keys.add(key[len(base):].strip("/"))
  221. return keys
  222. def allkeys(self):
  223. keys = set()
  224. if os.path.exists(self.refpath("HEAD")):
  225. keys.add("HEAD")
  226. path = self.refpath("")
  227. for root, dirs, files in os.walk(self.refpath("refs")):
  228. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  229. for filename in files:
  230. refname = ("%s/%s" % (dir, filename)).strip("/")
  231. if check_ref_format(refname):
  232. keys.add(refname)
  233. keys.update(self.get_packed_refs())
  234. return keys
  235. def refpath(self, name):
  236. """Return the disk path of a ref.
  237. """
  238. if os.path.sep != "/":
  239. name = name.replace("/", os.path.sep)
  240. return os.path.join(self.path, name)
  241. def get_packed_refs(self):
  242. """Get contents of the packed-refs file.
  243. :return: Dictionary mapping ref names to SHA1s
  244. :note: Will return an empty dictionary when no packed-refs file is
  245. present.
  246. """
  247. # TODO: invalidate the cache on repacking
  248. if self._packed_refs is None:
  249. self._packed_refs = {}
  250. path = os.path.join(self.path, 'packed-refs')
  251. try:
  252. f = GitFile(path, 'rb')
  253. except IOError, e:
  254. if e.errno == errno.ENOENT:
  255. return {}
  256. raise
  257. try:
  258. first_line = iter(f).next().rstrip()
  259. if (first_line.startswith("# pack-refs") and " peeled" in
  260. first_line):
  261. for sha, name, peeled in read_packed_refs_with_peeled(f):
  262. self._packed_refs[name] = sha
  263. if peeled:
  264. self._peeled_refs[name] = peeled
  265. else:
  266. f.seek(0)
  267. for sha, name in read_packed_refs(f):
  268. self._packed_refs[name] = sha
  269. finally:
  270. f.close()
  271. return self._packed_refs
  272. def read_loose_ref(self, name):
  273. """Read a reference file and return its contents.
  274. If the reference file a symbolic reference, only read the first line of
  275. the file. Otherwise, only read the first 40 bytes.
  276. :param name: the refname to read, relative to refpath
  277. :return: The contents of the ref file, or None if the file does not
  278. exist.
  279. :raises IOError: if any other error occurs
  280. """
  281. filename = self.refpath(name)
  282. try:
  283. f = GitFile(filename, 'rb')
  284. try:
  285. header = f.read(len(SYMREF))
  286. if header == SYMREF:
  287. # Read only the first line
  288. return header + iter(f).next().rstrip("\n")
  289. else:
  290. # Read only the first 40 bytes
  291. return header + f.read(40-len(SYMREF))
  292. finally:
  293. f.close()
  294. except IOError, e:
  295. if e.errno == errno.ENOENT:
  296. return None
  297. raise
  298. def _remove_packed_ref(self, name):
  299. if self._packed_refs is None:
  300. return
  301. filename = os.path.join(self.path, 'packed-refs')
  302. # reread cached refs from disk, while holding the lock
  303. f = GitFile(filename, 'wb')
  304. try:
  305. self._packed_refs = None
  306. self.get_packed_refs()
  307. if name not in self._packed_refs:
  308. return
  309. del self._packed_refs[name]
  310. if name in self._peeled_refs:
  311. del self._peeled_refs[name]
  312. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  313. f.close()
  314. finally:
  315. f.abort()
  316. def set_if_equals(self, name, old_ref, new_ref):
  317. """Set a refname to new_ref only if it currently equals old_ref.
  318. This method follows all symbolic references, and can be used to perform
  319. an atomic compare-and-swap operation.
  320. :param name: The refname to set.
  321. :param old_ref: The old sha the refname must refer to, or None to set
  322. unconditionally.
  323. :param new_ref: The new sha the refname will refer to.
  324. :return: True if the set was successful, False otherwise.
  325. """
  326. try:
  327. realname, _ = self._follow(name)
  328. except KeyError:
  329. realname = name
  330. filename = self.refpath(realname)
  331. ensure_dir_exists(os.path.dirname(filename))
  332. f = GitFile(filename, 'wb')
  333. try:
  334. if old_ref is not None:
  335. try:
  336. # read again while holding the lock
  337. orig_ref = self.read_loose_ref(realname)
  338. if orig_ref is None:
  339. orig_ref = self.get_packed_refs().get(realname, None)
  340. if orig_ref != old_ref:
  341. f.abort()
  342. return False
  343. except (OSError, IOError):
  344. f.abort()
  345. raise
  346. try:
  347. f.write(new_ref+"\n")
  348. except (OSError, IOError):
  349. f.abort()
  350. raise
  351. finally:
  352. f.close()
  353. return True
  354. def add_if_new(self, name, ref):
  355. """Add a new reference only if it does not already exist."""
  356. self._check_refname(name)
  357. filename = self.refpath(name)
  358. ensure_dir_exists(os.path.dirname(filename))
  359. f = GitFile(filename, 'wb')
  360. try:
  361. if os.path.exists(filename) or name in self.get_packed_refs():
  362. f.abort()
  363. return False
  364. try:
  365. f.write(ref+"\n")
  366. except (OSError, IOError):
  367. f.abort()
  368. raise
  369. finally:
  370. f.close()
  371. return True
  372. def __setitem__(self, name, ref):
  373. """Set a reference name to point to the given SHA1.
  374. This method follows all symbolic references.
  375. :note: This method unconditionally overwrites the contents of a reference
  376. on disk. To update atomically only if the reference has not changed
  377. on disk, use set_if_equals().
  378. """
  379. self.set_if_equals(name, None, ref)
  380. def remove_if_equals(self, name, old_ref):
  381. """Remove a refname only if it currently equals old_ref.
  382. This method does not follow symbolic references. It can be used to
  383. perform an atomic compare-and-delete operation.
  384. :param name: The refname to delete.
  385. :param old_ref: The old sha the refname must refer to, or None to delete
  386. unconditionally.
  387. :return: True if the delete was successful, False otherwise.
  388. """
  389. self._check_refname(name)
  390. filename = self.refpath(name)
  391. ensure_dir_exists(os.path.dirname(filename))
  392. f = GitFile(filename, 'wb')
  393. try:
  394. if old_ref is not None:
  395. orig_ref = self.read_loose_ref(name)
  396. if orig_ref is None:
  397. orig_ref = self.get_packed_refs().get(name, None)
  398. if orig_ref != old_ref:
  399. return False
  400. # may only be packed
  401. try:
  402. os.remove(filename)
  403. except OSError, e:
  404. if e.errno != errno.ENOENT:
  405. raise
  406. self._remove_packed_ref(name)
  407. finally:
  408. # never write, we just wanted the lock
  409. f.abort()
  410. return True
  411. def __delitem__(self, name):
  412. """Remove a refname.
  413. This method does not follow symbolic references.
  414. :note: This method unconditionally deletes the contents of a reference
  415. on disk. To delete atomically only if the reference has not changed
  416. on disk, use set_if_equals().
  417. """
  418. self.remove_if_equals(name, None)
  419. def _split_ref_line(line):
  420. """Split a single ref line into a tuple of SHA1 and name."""
  421. fields = line.rstrip("\n").split(" ")
  422. if len(fields) != 2:
  423. raise PackedRefsException("invalid ref line '%s'" % line)
  424. sha, name = fields
  425. try:
  426. hex_to_sha(sha)
  427. except (AssertionError, TypeError), e:
  428. raise PackedRefsException(e)
  429. if not check_ref_format(name):
  430. raise PackedRefsException("invalid ref name '%s'" % name)
  431. return (sha, name)
  432. def read_packed_refs(f):
  433. """Read a packed refs file.
  434. Yields tuples with SHA1s and ref names.
  435. :param f: file-like object to read from
  436. """
  437. for l in f:
  438. if l[0] == "#":
  439. # Comment
  440. continue
  441. if l[0] == "^":
  442. raise PackedRefsException(
  443. "found peeled ref in packed-refs without peeled")
  444. yield _split_ref_line(l)
  445. def read_packed_refs_with_peeled(f):
  446. """Read a packed refs file including peeled refs.
  447. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  448. with ref names, SHA1s, and peeled SHA1s (or None).
  449. :param f: file-like object to read from, seek'ed to the second line
  450. """
  451. last = None
  452. for l in f:
  453. if l[0] == "#":
  454. continue
  455. l = l.rstrip("\n")
  456. if l[0] == "^":
  457. if not last:
  458. raise PackedRefsException("unexpected peeled ref line")
  459. try:
  460. hex_to_sha(l[1:])
  461. except (AssertionError, TypeError), e:
  462. raise PackedRefsException(e)
  463. sha, name = _split_ref_line(last)
  464. last = None
  465. yield (sha, name, l[1:])
  466. else:
  467. if last:
  468. sha, name = _split_ref_line(last)
  469. yield (sha, name, None)
  470. last = l
  471. if last:
  472. sha, name = _split_ref_line(last)
  473. yield (sha, name, None)
  474. def write_packed_refs(f, packed_refs, peeled_refs=None):
  475. """Write a packed refs file.
  476. :param f: empty file-like object to write to
  477. :param packed_refs: dict of refname to sha of packed refs to write
  478. """
  479. if peeled_refs is None:
  480. peeled_refs = {}
  481. else:
  482. f.write('# pack-refs with: peeled\n')
  483. for refname in sorted(packed_refs.iterkeys()):
  484. f.write('%s %s\n' % (packed_refs[refname], refname))
  485. if refname in peeled_refs:
  486. f.write('^%s\n' % peeled_refs[refname])
  487. class BaseRepo(object):
  488. """Base class for a git repository.
  489. :ivar object_store: Dictionary-like object for accessing
  490. the objects
  491. :ivar refs: Dictionary-like object with the refs in this repository
  492. """
  493. def __init__(self, object_store, refs):
  494. self.object_store = object_store
  495. self.refs = refs
  496. def get_named_file(self, path):
  497. """Get a file from the control dir with a specific name.
  498. Although the filename should be interpreted as a filename relative to
  499. the control dir in a disk-baked Repo, the object returned need not be
  500. pointing to a file in that location.
  501. :param path: The path to the file, relative to the control dir.
  502. :return: An open file object, or None if the file does not exist.
  503. """
  504. raise NotImplementedError(self.get_named_file)
  505. def open_index(self):
  506. """Open the index for this repository.
  507. :raises NoIndexPresent: If no index is present
  508. :return: Index instance
  509. """
  510. raise NotImplementedError(self.open_index)
  511. def fetch(self, target, determine_wants=None, progress=None):
  512. """Fetch objects into another repository.
  513. :param target: The target repository
  514. :param determine_wants: Optional function to determine what refs to
  515. fetch.
  516. :param progress: Optional progress function
  517. """
  518. if determine_wants is None:
  519. determine_wants = lambda heads: heads.values()
  520. target.object_store.add_objects(
  521. self.fetch_objects(determine_wants, target.get_graph_walker(),
  522. progress))
  523. return self.get_refs()
  524. def fetch_objects(self, determine_wants, graph_walker, progress):
  525. """Fetch the missing objects required for a set of revisions.
  526. :param determine_wants: Function that takes a dictionary with heads
  527. and returns the list of heads to fetch.
  528. :param graph_walker: Object that can iterate over the list of revisions
  529. to fetch and has an "ack" method that will be called to acknowledge
  530. that a revision is present.
  531. :param progress: Simple progress function that will be called with
  532. updated progress strings.
  533. :return: iterator over objects, with __len__ implemented
  534. """
  535. wants = determine_wants(self.get_refs())
  536. haves = self.object_store.find_common_revisions(graph_walker)
  537. return self.object_store.iter_shas(
  538. self.object_store.find_missing_objects(haves, wants, progress))
  539. def get_graph_walker(self, heads=None):
  540. if heads is None:
  541. heads = self.refs.as_dict('refs/heads').values()
  542. return self.object_store.get_graph_walker(heads)
  543. def ref(self, name):
  544. """Return the SHA1 a ref is pointing to."""
  545. return self.refs[name]
  546. def get_refs(self):
  547. """Get dictionary with all refs."""
  548. return self.refs.as_dict()
  549. def head(self):
  550. """Return the SHA1 pointed at by HEAD."""
  551. return self.refs['HEAD']
  552. def _get_object(self, sha, cls):
  553. assert len(sha) in (20, 40)
  554. ret = self.get_object(sha)
  555. if ret._type != cls._type:
  556. if cls is Commit:
  557. raise NotCommitError(ret)
  558. elif cls is Blob:
  559. raise NotBlobError(ret)
  560. elif cls is Tree:
  561. raise NotTreeError(ret)
  562. else:
  563. raise Exception("Type invalid: %r != %r" % (ret._type, cls._type))
  564. return ret
  565. def get_object(self, sha):
  566. return self.object_store[sha]
  567. def get_parents(self, sha):
  568. return self.commit(sha).parents
  569. def get_config(self):
  570. p = ConfigParser.RawConfigParser()
  571. p.read(os.path.join(self._controldir, 'config'))
  572. return dict((section, dict(p.items(section))) for section in p.sections())
  573. def commit(self, sha):
  574. return self._get_object(sha, Commit)
  575. def tree(self, sha):
  576. return self._get_object(sha, Tree)
  577. def tag(self, sha):
  578. return self._get_object(sha, Tag)
  579. def get_blob(self, sha):
  580. return self._get_object(sha, Blob)
  581. def revision_history(self, head):
  582. """Returns a list of the commits reachable from head.
  583. Returns a list of commit objects. the first of which will be the commit
  584. of head, then following theat will be the parents.
  585. Raises NotCommitError if any no commits are referenced, including if the
  586. head parameter isn't the sha of a commit.
  587. XXX: work out how to handle merges.
  588. """
  589. # We build the list backwards, as parents are more likely to be older
  590. # than children
  591. pending_commits = [head]
  592. history = []
  593. while pending_commits != []:
  594. head = pending_commits.pop(0)
  595. try:
  596. commit = self.commit(head)
  597. except KeyError:
  598. raise MissingCommitError(head)
  599. if commit in history:
  600. continue
  601. i = 0
  602. for known_commit in history:
  603. if known_commit.commit_time > commit.commit_time:
  604. break
  605. i += 1
  606. history.insert(i, commit)
  607. parents = commit.parents
  608. pending_commits += parents
  609. history.reverse()
  610. return history
  611. def __getitem__(self, name):
  612. if len(name) in (20, 40):
  613. return self.object_store[name]
  614. return self.object_store[self.refs[name]]
  615. def __setitem__(self, name, value):
  616. if name.startswith("refs/") or name == "HEAD":
  617. if isinstance(value, ShaFile):
  618. self.refs[name] = value.id
  619. elif isinstance(value, str):
  620. self.refs[name] = value
  621. else:
  622. raise TypeError(value)
  623. raise ValueError(name)
  624. def __delitem__(self, name):
  625. if name.startswith("refs") or name == "HEAD":
  626. del self.refs[name]
  627. raise ValueError(name)
  628. def do_commit(self, committer, message,
  629. author=None, commit_timestamp=None,
  630. commit_timezone=None, author_timestamp=None,
  631. author_timezone=None, tree=None):
  632. """Create a new commit.
  633. :param committer: Committer fullname
  634. :param message: Commit message
  635. :param author: Author fullname (defaults to committer)
  636. :param commit_timestamp: Commit timestamp (defaults to now)
  637. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  638. :param author_timestamp: Author timestamp (defaults to commit timestamp)
  639. :param author_timezone: Author timestamp timezone
  640. (defaults to commit timestamp timezone)
  641. :param tree: SHA1 of the tree root to use (if not specified the current index will be committed).
  642. :return: New commit SHA1
  643. """
  644. from dulwich.index import commit_index
  645. import time
  646. index = self.open_index()
  647. c = Commit()
  648. if tree is None:
  649. c.tree = commit_index(self.object_store, index)
  650. else:
  651. c.tree = tree
  652. c.committer = committer
  653. if commit_timestamp is None:
  654. commit_timestamp = time.time()
  655. c.commit_time = int(commit_timestamp)
  656. if commit_timezone is None:
  657. commit_timezone = 0
  658. c.commit_timezone = commit_timezone
  659. if author is None:
  660. author = committer
  661. c.author = author
  662. if author_timestamp is None:
  663. author_timestamp = commit_timestamp
  664. c.author_time = int(author_timestamp)
  665. if author_timezone is None:
  666. author_timezone = commit_timezone
  667. c.author_timezone = author_timezone
  668. c.message = message
  669. self.object_store.add_object(c)
  670. self.refs["HEAD"] = c.id
  671. return c.id
  672. class Repo(BaseRepo):
  673. """A git repository backed by local disk."""
  674. def __init__(self, root):
  675. if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
  676. self.bare = False
  677. self._controldir = os.path.join(root, ".git")
  678. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  679. os.path.isdir(os.path.join(root, REFSDIR))):
  680. self.bare = True
  681. self._controldir = root
  682. else:
  683. raise NotGitRepository(root)
  684. self.path = root
  685. object_store = DiskObjectStore(
  686. os.path.join(self.controldir(), OBJECTDIR))
  687. refs = DiskRefsContainer(self.controldir())
  688. BaseRepo.__init__(self, object_store, refs)
  689. def controldir(self):
  690. """Return the path of the control directory."""
  691. return self._controldir
  692. def _put_named_file(self, path, contents):
  693. """Write a file from the control dir with a specific name and contents.
  694. """
  695. f = GitFile(os.path.join(self.controldir(), path), 'wb')
  696. try:
  697. f.write(contents)
  698. finally:
  699. f.close()
  700. def get_named_file(self, path):
  701. """Get a file from the control dir with a specific name.
  702. Although the filename should be interpreted as a filename relative to
  703. the control dir in a disk-baked Repo, the object returned need not be
  704. pointing to a file in that location.
  705. :param path: The path to the file, relative to the control dir.
  706. :return: An open file object, or None if the file does not exist.
  707. """
  708. try:
  709. return open(os.path.join(self.controldir(), path.lstrip('/')), 'rb')
  710. except (IOError, OSError), e:
  711. if e.errno == errno.ENOENT:
  712. return None
  713. raise
  714. def index_path(self):
  715. """Return path to the index file."""
  716. return os.path.join(self.controldir(), INDEX_FILENAME)
  717. def open_index(self):
  718. """Open the index for this repository."""
  719. from dulwich.index import Index
  720. if not self.has_index():
  721. raise NoIndexPresent()
  722. return Index(self.index_path())
  723. def has_index(self):
  724. """Check if an index is present."""
  725. return os.path.exists(self.index_path())
  726. def __repr__(self):
  727. return "<Repo at %r>" % self.path
  728. @classmethod
  729. def init(cls, path, mkdir=True):
  730. controldir = os.path.join(path, ".git")
  731. os.mkdir(controldir)
  732. cls.init_bare(controldir)
  733. return cls(path)
  734. @classmethod
  735. def init_bare(cls, path, mkdir=True):
  736. for d in BASE_DIRECTORIES:
  737. os.mkdir(os.path.join(path, *d))
  738. ret = cls(path)
  739. ret.refs.set_ref("HEAD", "refs/heads/master")
  740. ret._put_named_file('description', "Unnamed repository")
  741. ret._put_named_file('config', """[core]
  742. repositoryformatversion = 0
  743. filemode = true
  744. bare = false
  745. logallrefupdates = true
  746. """)
  747. ret._put_named_file(os.path.join('info', 'excludes'), '')
  748. return ret
  749. create = init_bare