repo.py 28 KB

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