repo.py 34 KB

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