repo.py 28 KB

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