repo.py 29 KB

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