repo.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. # repo.py -- For dealing with 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. from cStringIO import StringIO
  22. import errno
  23. import os
  24. from dulwich.errors import (
  25. MissingCommitError,
  26. NoIndexPresent,
  27. NotBlobError,
  28. NotCommitError,
  29. NotGitRepository,
  30. NotTreeError,
  31. NotTagError,
  32. PackedRefsException,
  33. CommitError,
  34. RefFormatError,
  35. )
  36. from dulwich.file import (
  37. ensure_dir_exists,
  38. GitFile,
  39. )
  40. from dulwich.object_store import (
  41. DiskObjectStore,
  42. MemoryObjectStore,
  43. )
  44. from dulwich.objects import (
  45. Blob,
  46. Commit,
  47. ShaFile,
  48. Tag,
  49. Tree,
  50. hex_to_sha,
  51. )
  52. import warnings
  53. OBJECTDIR = 'objects'
  54. SYMREF = 'ref: '
  55. REFSDIR = 'refs'
  56. REFSDIR_TAGS = 'tags'
  57. REFSDIR_HEADS = 'heads'
  58. INDEX_FILENAME = "index"
  59. BASE_DIRECTORIES = [
  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("\r\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. warnings.warn("RefsContainer.set_ref() is deprecated."
  104. "Use set_symblic_ref instead.",
  105. category=DeprecationWarning, stacklevel=2)
  106. return self.set_symbolic_ref(name, other)
  107. def set_symbolic_ref(self, name, other):
  108. """Make a ref point at another ref.
  109. :param name: Name of the ref to set
  110. :param other: Name of the ref to point at
  111. """
  112. raise NotImplementedError(self.set_symbolic_ref)
  113. def get_packed_refs(self):
  114. """Get contents of the packed-refs file.
  115. :return: Dictionary mapping ref names to SHA1s
  116. :note: Will return an empty dictionary when no packed-refs file is
  117. present.
  118. """
  119. raise NotImplementedError(self.get_packed_refs)
  120. def get_peeled(self, name):
  121. """Return the cached peeled value of a ref, if available.
  122. :param name: Name of the ref to peel
  123. :return: The peeled value of the ref. If the ref is known not point to a
  124. tag, this will be the SHA the ref refers to. If the ref may point to
  125. a tag, but no cached information is available, None is returned.
  126. """
  127. return None
  128. def import_refs(self, base, other):
  129. for name, value in other.iteritems():
  130. self["%s/%s" % (base, name)] = value
  131. def allkeys(self):
  132. """All refs present in this container."""
  133. raise NotImplementedError(self.allkeys)
  134. def keys(self, base=None):
  135. """Refs present in this container.
  136. :param base: An optional base to return refs under.
  137. :return: An unsorted set of valid refs in this container, including
  138. packed refs.
  139. """
  140. if base is not None:
  141. return self.subkeys(base)
  142. else:
  143. return self.allkeys()
  144. def subkeys(self, base):
  145. """Refs present in this container under a base.
  146. :param base: The base to return refs under.
  147. :return: A set of valid refs in this container under the base; the base
  148. prefix is stripped from the ref names returned.
  149. """
  150. keys = set()
  151. base_len = len(base) + 1
  152. for refname in self.allkeys():
  153. if refname.startswith(base):
  154. keys.add(refname[base_len:])
  155. return keys
  156. def as_dict(self, base=None):
  157. """Return the contents of this container as a dictionary.
  158. """
  159. ret = {}
  160. keys = self.keys(base)
  161. if base is None:
  162. base = ""
  163. for key in keys:
  164. try:
  165. ret[key] = self[("%s/%s" % (base, key)).strip("/")]
  166. except KeyError:
  167. continue # Unable to resolve
  168. return ret
  169. def _check_refname(self, name):
  170. """Ensure a refname is valid and lives in refs or is HEAD.
  171. HEAD is not a valid refname according to git-check-ref-format, but this
  172. class needs to be able to touch HEAD. Also, check_ref_format expects
  173. refnames without the leading 'refs/', but this class requires that
  174. so it cannot touch anything outside the refs dir (or HEAD).
  175. :param name: The name of the reference.
  176. :raises KeyError: if a refname is not HEAD or is otherwise not valid.
  177. """
  178. if name == 'HEAD':
  179. return
  180. if not name.startswith('refs/') or not check_ref_format(name[5:]):
  181. raise RefFormatError(name)
  182. def read_ref(self, refname):
  183. """Read a reference without following any references.
  184. :param refname: The name of the reference
  185. :return: The contents of the ref file, or None if it does
  186. not exist.
  187. """
  188. contents = self.read_loose_ref(refname)
  189. if not contents:
  190. contents = self.get_packed_refs().get(refname, None)
  191. return contents
  192. def read_loose_ref(self, name):
  193. """Read a loose reference and return its contents.
  194. :param name: the refname to read
  195. :return: The contents of the ref file, or None if it does
  196. not exist.
  197. """
  198. raise NotImplementedError(self.read_loose_ref)
  199. def _follow(self, name):
  200. """Follow a reference name.
  201. :return: a tuple of (refname, sha), where refname is the name of the
  202. last reference in the symbolic reference chain
  203. """
  204. self._check_refname(name)
  205. contents = SYMREF + name
  206. depth = 0
  207. while contents.startswith(SYMREF):
  208. refname = contents[len(SYMREF):]
  209. contents = self.read_ref(refname)
  210. if not contents:
  211. break
  212. depth += 1
  213. if depth > 5:
  214. raise KeyError(name)
  215. return refname, contents
  216. def __contains__(self, refname):
  217. if self.read_ref(refname):
  218. return True
  219. return False
  220. def __getitem__(self, name):
  221. """Get the SHA1 for a reference name.
  222. This method follows all symbolic references.
  223. """
  224. _, sha = self._follow(name)
  225. if sha is None:
  226. raise KeyError(name)
  227. return sha
  228. def set_if_equals(self, name, old_ref, new_ref):
  229. """Set a refname to new_ref only if it currently equals old_ref.
  230. This method follows all symbolic references if applicable for the
  231. subclass, and can be used to perform an atomic compare-and-swap
  232. operation.
  233. :param name: The refname to set.
  234. :param old_ref: The old sha the refname must refer to, or None to set
  235. unconditionally.
  236. :param new_ref: The new sha the refname will refer to.
  237. :return: True if the set was successful, False otherwise.
  238. """
  239. raise NotImplementedError(self.set_if_equals)
  240. def add_if_new(self, name, ref):
  241. """Add a new reference only if it does not already exist."""
  242. raise NotImplementedError(self.add_if_new)
  243. def __setitem__(self, name, ref):
  244. """Set a reference name to point to the given SHA1.
  245. This method follows all symbolic references if applicable for the
  246. subclass.
  247. :note: This method unconditionally overwrites the contents of a
  248. reference. To update atomically only if the reference has not
  249. changed, use set_if_equals().
  250. :param name: The refname to set.
  251. :param ref: The new sha the refname will refer to.
  252. """
  253. self.set_if_equals(name, None, ref)
  254. def remove_if_equals(self, name, old_ref):
  255. """Remove a refname only if it currently equals old_ref.
  256. This method does not follow symbolic references, even if applicable for
  257. the subclass. It can be used to perform an atomic compare-and-delete
  258. operation.
  259. :param name: The refname to delete.
  260. :param old_ref: The old sha the refname must refer to, or None to delete
  261. unconditionally.
  262. :return: True if the delete was successful, False otherwise.
  263. """
  264. raise NotImplementedError(self.remove_if_equals)
  265. def __delitem__(self, name):
  266. """Remove a refname.
  267. This method does not follow symbolic references, even if applicable for
  268. the subclass.
  269. :note: This method unconditionally deletes the contents of a reference.
  270. To delete atomically only if the reference has not changed, use
  271. remove_if_equals().
  272. :param name: The refname to delete.
  273. """
  274. self.remove_if_equals(name, None)
  275. class DictRefsContainer(RefsContainer):
  276. """RefsContainer backed by a simple dict.
  277. This container does not support symbolic or packed references and is not
  278. threadsafe.
  279. """
  280. def __init__(self, refs):
  281. self._refs = refs
  282. self._peeled = {}
  283. def allkeys(self):
  284. return self._refs.keys()
  285. def read_loose_ref(self, name):
  286. return self._refs.get(name, None)
  287. def get_packed_refs(self):
  288. return {}
  289. def set_symbolic_ref(self, name, other):
  290. self._refs[name] = SYMREF + other
  291. def set_if_equals(self, name, old_ref, new_ref):
  292. if old_ref is not None and self._refs.get(name, None) != old_ref:
  293. return False
  294. realname, _ = self._follow(name)
  295. self._refs[realname] = new_ref
  296. return True
  297. def add_if_new(self, name, ref):
  298. if name in self._refs:
  299. return False
  300. self._refs[name] = ref
  301. return True
  302. def remove_if_equals(self, name, old_ref):
  303. if old_ref is not None and self._refs.get(name, None) != old_ref:
  304. return False
  305. del self._refs[name]
  306. return True
  307. def get_peeled(self, name):
  308. return self._peeled.get(name)
  309. def _update(self, refs):
  310. """Update multiple refs; intended only for testing."""
  311. # TODO(dborowitz): replace this with a public function that uses
  312. # set_if_equal.
  313. self._refs.update(refs)
  314. def _update_peeled(self, peeled):
  315. """Update cached peeled refs; intended only for testing."""
  316. self._peeled.update(peeled)
  317. class DiskRefsContainer(RefsContainer):
  318. """Refs container that reads refs from disk."""
  319. def __init__(self, path):
  320. self.path = path
  321. self._packed_refs = None
  322. self._peeled_refs = None
  323. def __repr__(self):
  324. return "%s(%r)" % (self.__class__.__name__, self.path)
  325. def subkeys(self, base):
  326. keys = set()
  327. path = self.refpath(base)
  328. for root, dirs, files in os.walk(path):
  329. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  330. for filename in files:
  331. refname = ("%s/%s" % (dir, filename)).strip("/")
  332. # check_ref_format requires at least one /, so we prepend the
  333. # base before calling it.
  334. if check_ref_format("%s/%s" % (base, refname)):
  335. keys.add(refname)
  336. for key in self.get_packed_refs():
  337. if key.startswith(base):
  338. keys.add(key[len(base):].strip("/"))
  339. return keys
  340. def allkeys(self):
  341. keys = set()
  342. if os.path.exists(self.refpath("HEAD")):
  343. keys.add("HEAD")
  344. path = self.refpath("")
  345. for root, dirs, files in os.walk(self.refpath("refs")):
  346. dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
  347. for filename in files:
  348. refname = ("%s/%s" % (dir, filename)).strip("/")
  349. if check_ref_format(refname):
  350. keys.add(refname)
  351. keys.update(self.get_packed_refs())
  352. return keys
  353. def refpath(self, name):
  354. """Return the disk path of a ref.
  355. """
  356. if os.path.sep != "/":
  357. name = name.replace("/", os.path.sep)
  358. return os.path.join(self.path, name)
  359. def get_packed_refs(self):
  360. """Get contents of the packed-refs file.
  361. :return: Dictionary mapping ref names to SHA1s
  362. :note: Will return an empty dictionary when no packed-refs file is
  363. present.
  364. """
  365. # TODO: invalidate the cache on repacking
  366. if self._packed_refs is None:
  367. # set both to empty because we want _peeled_refs to be
  368. # None if and only if _packed_refs is also None.
  369. self._packed_refs = {}
  370. self._peeled_refs = {}
  371. path = os.path.join(self.path, 'packed-refs')
  372. try:
  373. f = GitFile(path, 'rb')
  374. except IOError, e:
  375. if e.errno == errno.ENOENT:
  376. return {}
  377. raise
  378. try:
  379. first_line = iter(f).next().rstrip()
  380. if (first_line.startswith("# pack-refs") and " peeled" in
  381. first_line):
  382. for sha, name, peeled in read_packed_refs_with_peeled(f):
  383. self._packed_refs[name] = sha
  384. if peeled:
  385. self._peeled_refs[name] = peeled
  386. else:
  387. f.seek(0)
  388. for sha, name in read_packed_refs(f):
  389. self._packed_refs[name] = sha
  390. finally:
  391. f.close()
  392. return self._packed_refs
  393. def get_peeled(self, name):
  394. """Return the cached peeled value of a ref, if available.
  395. :param name: Name of the ref to peel
  396. :return: The peeled value of the ref. If the ref is known not point to a
  397. tag, this will be the SHA the ref refers to. If the ref may point to
  398. a tag, but no cached information is available, None is returned.
  399. """
  400. self.get_packed_refs()
  401. if self._peeled_refs is None or name not in self._packed_refs:
  402. # No cache: no peeled refs were read, or this ref is loose
  403. return None
  404. if name in self._peeled_refs:
  405. return self._peeled_refs[name]
  406. else:
  407. # Known not peelable
  408. return self[name]
  409. def read_loose_ref(self, name):
  410. """Read a reference file and return its contents.
  411. If the reference file a symbolic reference, only read the first line of
  412. the file. Otherwise, only read the first 40 bytes.
  413. :param name: the refname to read, relative to refpath
  414. :return: The contents of the ref file, or None if the file does not
  415. exist.
  416. :raises IOError: if any other error occurs
  417. """
  418. filename = self.refpath(name)
  419. try:
  420. f = GitFile(filename, 'rb')
  421. try:
  422. header = f.read(len(SYMREF))
  423. if header == SYMREF:
  424. # Read only the first line
  425. return header + iter(f).next().rstrip("\r\n")
  426. else:
  427. # Read only the first 40 bytes
  428. return header + f.read(40-len(SYMREF))
  429. finally:
  430. f.close()
  431. except IOError, e:
  432. if e.errno == errno.ENOENT:
  433. return None
  434. raise
  435. def _remove_packed_ref(self, name):
  436. if self._packed_refs is None:
  437. return
  438. filename = os.path.join(self.path, 'packed-refs')
  439. # reread cached refs from disk, while holding the lock
  440. f = GitFile(filename, 'wb')
  441. try:
  442. self._packed_refs = None
  443. self.get_packed_refs()
  444. if name not in self._packed_refs:
  445. return
  446. del self._packed_refs[name]
  447. if name in self._peeled_refs:
  448. del self._peeled_refs[name]
  449. write_packed_refs(f, self._packed_refs, self._peeled_refs)
  450. f.close()
  451. finally:
  452. f.abort()
  453. def set_symbolic_ref(self, name, other):
  454. """Make a ref point at another ref.
  455. :param name: Name of the ref to set
  456. :param other: Name of the ref to point at
  457. """
  458. self._check_refname(name)
  459. self._check_refname(other)
  460. filename = self.refpath(name)
  461. try:
  462. f = GitFile(filename, 'wb')
  463. try:
  464. f.write(SYMREF + other + '\n')
  465. except (IOError, OSError):
  466. f.abort()
  467. raise
  468. finally:
  469. f.close()
  470. def set_if_equals(self, name, old_ref, new_ref):
  471. """Set a refname to new_ref only if it currently equals old_ref.
  472. This method follows all symbolic references, and can be used to perform
  473. an atomic compare-and-swap operation.
  474. :param name: The refname to set.
  475. :param old_ref: The old sha the refname must refer to, or None to set
  476. unconditionally.
  477. :param new_ref: The new sha the refname will refer to.
  478. :return: True if the set was successful, False otherwise.
  479. """
  480. try:
  481. realname, _ = self._follow(name)
  482. except KeyError:
  483. realname = name
  484. filename = self.refpath(realname)
  485. ensure_dir_exists(os.path.dirname(filename))
  486. f = GitFile(filename, 'wb')
  487. try:
  488. if old_ref is not None:
  489. try:
  490. # read again while holding the lock
  491. orig_ref = self.read_loose_ref(realname)
  492. if orig_ref is None:
  493. orig_ref = self.get_packed_refs().get(realname, None)
  494. if orig_ref != old_ref:
  495. f.abort()
  496. return False
  497. except (OSError, IOError):
  498. f.abort()
  499. raise
  500. try:
  501. f.write(new_ref+"\n")
  502. except (OSError, IOError):
  503. f.abort()
  504. raise
  505. finally:
  506. f.close()
  507. return True
  508. def add_if_new(self, name, ref):
  509. """Add a new reference only if it does not already exist.
  510. This method follows symrefs, and only ensures that the last ref in the
  511. chain does not exist.
  512. :param name: The refname to set.
  513. :param ref: The new sha the refname will refer to.
  514. :return: True if the add was successful, False otherwise.
  515. """
  516. try:
  517. realname, contents = self._follow(name)
  518. if contents is not None:
  519. return False
  520. except KeyError:
  521. realname = name
  522. self._check_refname(realname)
  523. filename = self.refpath(realname)
  524. ensure_dir_exists(os.path.dirname(filename))
  525. f = GitFile(filename, 'wb')
  526. try:
  527. if os.path.exists(filename) or name in self.get_packed_refs():
  528. f.abort()
  529. return False
  530. try:
  531. f.write(ref+"\n")
  532. except (OSError, IOError):
  533. f.abort()
  534. raise
  535. finally:
  536. f.close()
  537. return True
  538. def remove_if_equals(self, name, old_ref):
  539. """Remove a refname only if it currently equals old_ref.
  540. This method does not follow symbolic references. It can be used to
  541. perform an atomic compare-and-delete operation.
  542. :param name: The refname to delete.
  543. :param old_ref: The old sha the refname must refer to, or None to delete
  544. unconditionally.
  545. :return: True if the delete was successful, False otherwise.
  546. """
  547. self._check_refname(name)
  548. filename = self.refpath(name)
  549. ensure_dir_exists(os.path.dirname(filename))
  550. f = GitFile(filename, 'wb')
  551. try:
  552. if old_ref is not None:
  553. orig_ref = self.read_loose_ref(name)
  554. if orig_ref is None:
  555. orig_ref = self.get_packed_refs().get(name, None)
  556. if orig_ref != old_ref:
  557. return False
  558. # may only be packed
  559. try:
  560. os.remove(filename)
  561. except OSError, e:
  562. if e.errno != errno.ENOENT:
  563. raise
  564. self._remove_packed_ref(name)
  565. finally:
  566. # never write, we just wanted the lock
  567. f.abort()
  568. return True
  569. def _split_ref_line(line):
  570. """Split a single ref line into a tuple of SHA1 and name."""
  571. fields = line.rstrip("\n").split(" ")
  572. if len(fields) != 2:
  573. raise PackedRefsException("invalid ref line '%s'" % line)
  574. sha, name = fields
  575. try:
  576. hex_to_sha(sha)
  577. except (AssertionError, TypeError), e:
  578. raise PackedRefsException(e)
  579. if not check_ref_format(name):
  580. raise PackedRefsException("invalid ref name '%s'" % name)
  581. return (sha, name)
  582. def read_packed_refs(f):
  583. """Read a packed refs file.
  584. :param f: file-like object to read from
  585. :return: Iterator over tuples with SHA1s and ref names.
  586. """
  587. for l in f:
  588. if l[0] == "#":
  589. # Comment
  590. continue
  591. if l[0] == "^":
  592. raise PackedRefsException(
  593. "found peeled ref in packed-refs without peeled")
  594. yield _split_ref_line(l)
  595. def read_packed_refs_with_peeled(f):
  596. """Read a packed refs file including peeled refs.
  597. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples
  598. with ref names, SHA1s, and peeled SHA1s (or None).
  599. :param f: file-like object to read from, seek'ed to the second line
  600. """
  601. last = None
  602. for l in f:
  603. if l[0] == "#":
  604. continue
  605. l = l.rstrip("\r\n")
  606. if l[0] == "^":
  607. if not last:
  608. raise PackedRefsException("unexpected peeled ref line")
  609. try:
  610. hex_to_sha(l[1:])
  611. except (AssertionError, TypeError), e:
  612. raise PackedRefsException(e)
  613. sha, name = _split_ref_line(last)
  614. last = None
  615. yield (sha, name, l[1:])
  616. else:
  617. if last:
  618. sha, name = _split_ref_line(last)
  619. yield (sha, name, None)
  620. last = l
  621. if last:
  622. sha, name = _split_ref_line(last)
  623. yield (sha, name, None)
  624. def write_packed_refs(f, packed_refs, peeled_refs=None):
  625. """Write a packed refs file.
  626. :param f: empty file-like object to write to
  627. :param packed_refs: dict of refname to sha of packed refs to write
  628. :param peeled_refs: dict of refname to peeled value of sha
  629. """
  630. if peeled_refs is None:
  631. peeled_refs = {}
  632. else:
  633. f.write('# pack-refs with: peeled\n')
  634. for refname in sorted(packed_refs.iterkeys()):
  635. f.write('%s %s\n' % (packed_refs[refname], refname))
  636. if refname in peeled_refs:
  637. f.write('^%s\n' % peeled_refs[refname])
  638. class BaseRepo(object):
  639. """Base class for a git repository.
  640. :ivar object_store: Dictionary-like object for accessing
  641. the objects
  642. :ivar refs: Dictionary-like object with the refs in this repository
  643. """
  644. def __init__(self, object_store, refs):
  645. self.object_store = object_store
  646. self.refs = refs
  647. def _init_files(self, bare):
  648. """Initialize a default set of named files."""
  649. self._put_named_file('description', "Unnamed repository")
  650. self._put_named_file('config', ('[core]\n'
  651. 'repositoryformatversion = 0\n'
  652. 'filemode = true\n'
  653. 'bare = ' + str(bare).lower() + '\n'
  654. 'logallrefupdates = true\n'))
  655. self._put_named_file(os.path.join('info', 'exclude'), '')
  656. def get_named_file(self, path):
  657. """Get a file from the control dir with a specific name.
  658. Although the filename should be interpreted as a filename relative to
  659. the control dir in a disk-based Repo, the object returned need not be
  660. pointing to a file in that location.
  661. :param path: The path to the file, relative to the control dir.
  662. :return: An open file object, or None if the file does not exist.
  663. """
  664. raise NotImplementedError(self.get_named_file)
  665. def _put_named_file(self, path, contents):
  666. """Write a file to the control dir with the given name and contents.
  667. :param path: The path to the file, relative to the control dir.
  668. :param contents: A string to write to the file.
  669. """
  670. raise NotImplementedError(self._put_named_file)
  671. def open_index(self):
  672. """Open the index for this repository.
  673. :raises NoIndexPresent: If no index is present
  674. :return: Index instance
  675. """
  676. raise NotImplementedError(self.open_index)
  677. def fetch(self, target, determine_wants=None, progress=None):
  678. """Fetch objects into another repository.
  679. :param target: The target repository
  680. :param determine_wants: Optional function to determine what refs to
  681. fetch.
  682. :param progress: Optional progress function
  683. """
  684. if determine_wants is None:
  685. determine_wants = lambda heads: heads.values()
  686. target.object_store.add_objects(
  687. self.fetch_objects(determine_wants, target.get_graph_walker(),
  688. progress))
  689. return self.get_refs()
  690. def fetch_objects(self, determine_wants, graph_walker, progress,
  691. get_tagged=None):
  692. """Fetch the missing objects required for a set of revisions.
  693. :param determine_wants: Function that takes a dictionary with heads
  694. and returns the list of heads to fetch.
  695. :param graph_walker: Object that can iterate over the list of revisions
  696. to fetch and has an "ack" method that will be called to acknowledge
  697. that a revision is present.
  698. :param progress: Simple progress function that will be called with
  699. updated progress strings.
  700. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  701. sha for including tags.
  702. :return: iterator over objects, with __len__ implemented
  703. """
  704. wants = determine_wants(self.get_refs())
  705. if wants is None:
  706. # TODO(dborowitz): find a way to short-circuit that doesn't change
  707. # this interface.
  708. return None
  709. haves = self.object_store.find_common_revisions(graph_walker)
  710. return self.object_store.iter_shas(
  711. self.object_store.find_missing_objects(haves, wants, progress,
  712. get_tagged))
  713. def get_graph_walker(self, heads=None):
  714. if heads is None:
  715. heads = self.refs.as_dict('refs/heads').values()
  716. return self.object_store.get_graph_walker(heads)
  717. def ref(self, name):
  718. """Return the SHA1 a ref is pointing to."""
  719. return self.refs[name]
  720. def get_refs(self):
  721. """Get dictionary with all refs."""
  722. return self.refs.as_dict()
  723. def head(self):
  724. """Return the SHA1 pointed at by HEAD."""
  725. return self.refs['HEAD']
  726. def _get_object(self, sha, cls):
  727. assert len(sha) in (20, 40)
  728. ret = self.get_object(sha)
  729. if not isinstance(ret, cls):
  730. if cls is Commit:
  731. raise NotCommitError(ret)
  732. elif cls is Blob:
  733. raise NotBlobError(ret)
  734. elif cls is Tree:
  735. raise NotTreeError(ret)
  736. elif cls is Tag:
  737. raise NotTagError(ret)
  738. else:
  739. raise Exception("Type invalid: %r != %r" % (
  740. ret.type_name, cls.type_name))
  741. return ret
  742. def get_object(self, sha):
  743. return self.object_store[sha]
  744. def get_parents(self, sha):
  745. return self.commit(sha).parents
  746. def get_config(self):
  747. import ConfigParser
  748. p = ConfigParser.RawConfigParser()
  749. p.read(os.path.join(self._controldir, 'config'))
  750. return dict((section, dict(p.items(section)))
  751. for section in p.sections())
  752. def commit(self, sha):
  753. """Retrieve the commit with a particular SHA.
  754. :param sha: SHA of the commit to retrieve
  755. :raise NotCommitError: If the SHA provided doesn't point at a Commit
  756. :raise KeyError: If the SHA provided didn't exist
  757. :return: A `Commit` object
  758. """
  759. warnings.warn("Repo.commit(sha) is deprecated. Use Repo[sha] instead.",
  760. category=DeprecationWarning, stacklevel=2)
  761. return self._get_object(sha, Commit)
  762. def tree(self, sha):
  763. """Retrieve the tree with a particular SHA.
  764. :param sha: SHA of the tree to retrieve
  765. :raise NotTreeError: If the SHA provided doesn't point at a Tree
  766. :raise KeyError: If the SHA provided didn't exist
  767. :return: A `Tree` object
  768. """
  769. warnings.warn("Repo.tree(sha) is deprecated. Use Repo[sha] instead.",
  770. category=DeprecationWarning, stacklevel=2)
  771. return self._get_object(sha, Tree)
  772. def tag(self, sha):
  773. """Retrieve the tag with a particular SHA.
  774. :param sha: SHA of the tag to retrieve
  775. :raise NotTagError: If the SHA provided doesn't point at a Tag
  776. :raise KeyError: If the SHA provided didn't exist
  777. :return: A `Tag` object
  778. """
  779. warnings.warn("Repo.tag(sha) is deprecated. Use Repo[sha] instead.",
  780. category=DeprecationWarning, stacklevel=2)
  781. return self._get_object(sha, Tag)
  782. def get_blob(self, sha):
  783. """Retrieve the blob with a particular SHA.
  784. :param sha: SHA of the blob to retrieve
  785. :raise NotBlobError: If the SHA provided doesn't point at a Blob
  786. :raise KeyError: If the SHA provided didn't exist
  787. :return: A `Blob` object
  788. """
  789. warnings.warn("Repo.get_blob(sha) is deprecated. Use Repo[sha] "
  790. "instead.", category=DeprecationWarning, stacklevel=2)
  791. return self._get_object(sha, Blob)
  792. def get_peeled(self, ref):
  793. """Get the peeled value of a ref.
  794. :param ref: The refname to peel.
  795. :return: The fully-peeled SHA1 of a tag object, after peeling all
  796. intermediate tags; if the original ref does not point to a tag, this
  797. will equal the original SHA1.
  798. """
  799. cached = self.refs.get_peeled(ref)
  800. if cached is not None:
  801. return cached
  802. return self.object_store.peel_sha(self.refs[ref]).id
  803. def revision_history(self, head):
  804. """Returns a list of the commits reachable from head.
  805. Returns a list of commit objects. the first of which will be the commit
  806. of head, then following theat will be the parents.
  807. Raises NotCommitError if any no commits are referenced, including if the
  808. head parameter isn't the sha of a commit.
  809. XXX: work out how to handle merges.
  810. """
  811. # We build the list backwards, as parents are more likely to be older
  812. # than children
  813. pending_commits = [head]
  814. history = []
  815. while pending_commits != []:
  816. head = pending_commits.pop(0)
  817. try:
  818. commit = self[head]
  819. except KeyError:
  820. raise MissingCommitError(head)
  821. if type(commit) != Commit:
  822. raise NotCommitError(commit)
  823. if commit in history:
  824. continue
  825. i = 0
  826. for known_commit in history:
  827. if known_commit.commit_time > commit.commit_time:
  828. break
  829. i += 1
  830. history.insert(i, commit)
  831. pending_commits += commit.parents
  832. history.reverse()
  833. return history
  834. def __getitem__(self, name):
  835. if len(name) in (20, 40):
  836. try:
  837. return self.object_store[name]
  838. except KeyError:
  839. pass
  840. try:
  841. return self.object_store[self.refs[name]]
  842. except RefFormatError:
  843. raise KeyError(name)
  844. def __contains__(self, name):
  845. if len(name) in (20, 40):
  846. return name in self.object_store or name in self.refs
  847. else:
  848. return name in self.refs
  849. def __setitem__(self, name, value):
  850. if name.startswith("refs/") or name == "HEAD":
  851. if isinstance(value, ShaFile):
  852. self.refs[name] = value.id
  853. elif isinstance(value, str):
  854. self.refs[name] = value
  855. else:
  856. raise TypeError(value)
  857. else:
  858. raise ValueError(name)
  859. def __delitem__(self, name):
  860. if name.startswith("refs") or name == "HEAD":
  861. del self.refs[name]
  862. raise ValueError(name)
  863. def do_commit(self, message, committer=None,
  864. author=None, commit_timestamp=None,
  865. commit_timezone=None, author_timestamp=None,
  866. author_timezone=None, tree=None, encoding=None):
  867. """Create a new commit.
  868. :param message: Commit message
  869. :param committer: Committer fullname
  870. :param author: Author fullname (defaults to committer)
  871. :param commit_timestamp: Commit timestamp (defaults to now)
  872. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  873. :param author_timestamp: Author timestamp (defaults to commit timestamp)
  874. :param author_timezone: Author timestamp timezone
  875. (defaults to commit timestamp timezone)
  876. :param tree: SHA1 of the tree root to use (if not specified the
  877. current index will be committed).
  878. :param encoding: Encoding
  879. :return: New commit SHA1
  880. """
  881. import time
  882. c = Commit()
  883. if tree is None:
  884. index = self.open_index()
  885. c.tree = index.commit(self.object_store)
  886. else:
  887. if len(tree) != 40:
  888. raise ValueError("tree must be a 40-byte hex sha string")
  889. c.tree = tree
  890. # TODO: Allow username to be missing, and get it from .git/config
  891. if committer is None:
  892. raise ValueError("committer not set")
  893. c.committer = committer
  894. if commit_timestamp is None:
  895. commit_timestamp = time.time()
  896. c.commit_time = int(commit_timestamp)
  897. if commit_timezone is None:
  898. # FIXME: Use current user timezone rather than UTC
  899. commit_timezone = 0
  900. c.commit_timezone = commit_timezone
  901. if author is None:
  902. author = committer
  903. c.author = author
  904. if author_timestamp is None:
  905. author_timestamp = commit_timestamp
  906. c.author_time = int(author_timestamp)
  907. if author_timezone is None:
  908. author_timezone = commit_timezone
  909. c.author_timezone = author_timezone
  910. if encoding is not None:
  911. c.encoding = encoding
  912. c.message = message
  913. try:
  914. old_head = self.refs["HEAD"]
  915. c.parents = [old_head]
  916. self.object_store.add_object(c)
  917. ok = self.refs.set_if_equals("HEAD", old_head, c.id)
  918. except KeyError:
  919. c.parents = []
  920. self.object_store.add_object(c)
  921. ok = self.refs.add_if_new("HEAD", c.id)
  922. if not ok:
  923. # Fail if the atomic compare-and-swap failed, leaving the commit and
  924. # all its objects as garbage.
  925. raise CommitError("HEAD changed during commit")
  926. return c.id
  927. class Repo(BaseRepo):
  928. """A git repository backed by local disk."""
  929. def __init__(self, root):
  930. if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
  931. self.bare = False
  932. self._controldir = os.path.join(root, ".git")
  933. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  934. os.path.isdir(os.path.join(root, REFSDIR))):
  935. self.bare = True
  936. self._controldir = root
  937. else:
  938. raise NotGitRepository(root)
  939. self.path = root
  940. object_store = DiskObjectStore(os.path.join(self.controldir(),
  941. OBJECTDIR))
  942. refs = DiskRefsContainer(self.controldir())
  943. BaseRepo.__init__(self, object_store, refs)
  944. def controldir(self):
  945. """Return the path of the control directory."""
  946. return self._controldir
  947. def _put_named_file(self, path, contents):
  948. """Write a file to the control dir with the given name and contents.
  949. :param path: The path to the file, relative to the control dir.
  950. :param contents: A string to write to the file.
  951. """
  952. path = path.lstrip(os.path.sep)
  953. f = GitFile(os.path.join(self.controldir(), path), 'wb')
  954. try:
  955. f.write(contents)
  956. finally:
  957. f.close()
  958. def get_named_file(self, path):
  959. """Get a file from the control dir with a specific name.
  960. Although the filename should be interpreted as a filename relative to
  961. the control dir in a disk-based Repo, the object returned need not be
  962. pointing to a file in that location.
  963. :param path: The path to the file, relative to the control dir.
  964. :return: An open file object, or None if the file does not exist.
  965. """
  966. # TODO(dborowitz): sanitize filenames, since this is used directly by
  967. # the dumb web serving code.
  968. path = path.lstrip(os.path.sep)
  969. try:
  970. return open(os.path.join(self.controldir(), path), 'rb')
  971. except (IOError, OSError), e:
  972. if e.errno == errno.ENOENT:
  973. return None
  974. raise
  975. def index_path(self):
  976. """Return path to the index file."""
  977. return os.path.join(self.controldir(), INDEX_FILENAME)
  978. def open_index(self):
  979. """Open the index for this repository."""
  980. from dulwich.index import Index
  981. if not self.has_index():
  982. raise NoIndexPresent()
  983. return Index(self.index_path())
  984. def has_index(self):
  985. """Check if an index is present."""
  986. # Bare repos must never have index files; non-bare repos may have a
  987. # missing index file, which is treated as empty.
  988. return not self.bare
  989. def stage(self, paths):
  990. """Stage a set of paths.
  991. :param paths: List of paths, relative to the repository path
  992. """
  993. from dulwich.index import cleanup_mode
  994. index = self.open_index()
  995. for path in paths:
  996. full_path = os.path.join(self.path, path)
  997. blob = Blob()
  998. try:
  999. st = os.stat(full_path)
  1000. except OSError:
  1001. # File no longer exists
  1002. try:
  1003. del index[path]
  1004. except KeyError:
  1005. pass # Doesn't exist in the index either
  1006. else:
  1007. f = open(full_path, 'rb')
  1008. try:
  1009. blob.data = f.read()
  1010. finally:
  1011. f.close()
  1012. self.object_store.add_object(blob)
  1013. # XXX: Cleanup some of the other file properties as well?
  1014. index[path] = (st.st_ctime, st.st_mtime, st.st_dev, st.st_ino,
  1015. cleanup_mode(st.st_mode), st.st_uid, st.st_gid, st.st_size,
  1016. blob.id, 0)
  1017. index.write()
  1018. def __repr__(self):
  1019. return "<Repo at %r>" % self.path
  1020. @classmethod
  1021. def _init_maybe_bare(cls, path, bare):
  1022. for d in BASE_DIRECTORIES:
  1023. os.mkdir(os.path.join(path, *d))
  1024. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  1025. ret = cls(path)
  1026. ret.refs.set_symbolic_ref("HEAD", "refs/heads/master")
  1027. ret._init_files(bare)
  1028. return ret
  1029. @classmethod
  1030. def init(cls, path, mkdir=False):
  1031. if mkdir:
  1032. os.mkdir(path)
  1033. controldir = os.path.join(path, ".git")
  1034. os.mkdir(controldir)
  1035. cls._init_maybe_bare(controldir, False)
  1036. return cls(path)
  1037. @classmethod
  1038. def init_bare(cls, path):
  1039. return cls._init_maybe_bare(path, True)
  1040. create = init_bare
  1041. class MemoryRepo(BaseRepo):
  1042. """Repo that stores refs, objects, and named files in memory.
  1043. MemoryRepos are always bare: they have no working tree and no index, since
  1044. those have a stronger dependency on the filesystem.
  1045. """
  1046. def __init__(self):
  1047. BaseRepo.__init__(self, MemoryObjectStore(), DictRefsContainer({}))
  1048. self._named_files = {}
  1049. self.bare = True
  1050. def _put_named_file(self, path, contents):
  1051. """Write a file to the control dir with the given name and contents.
  1052. :param path: The path to the file, relative to the control dir.
  1053. :param contents: A string to write to the file.
  1054. """
  1055. self._named_files[path] = contents
  1056. def get_named_file(self, path):
  1057. """Get a file from the control dir with a specific name.
  1058. Although the filename should be interpreted as a filename relative to
  1059. the control dir in a disk-baked Repo, the object returned need not be
  1060. pointing to a file in that location.
  1061. :param path: The path to the file, relative to the control dir.
  1062. :return: An open file object, or None if the file does not exist.
  1063. """
  1064. contents = self._named_files.get(path, None)
  1065. if contents is None:
  1066. return None
  1067. return StringIO(contents)
  1068. def open_index(self):
  1069. """Fail to open index for this repo, since it is bare."""
  1070. raise NoIndexPresent()
  1071. @classmethod
  1072. def init_bare(cls, objects, refs):
  1073. ret = cls()
  1074. for obj in objects:
  1075. ret.object_store.add_object(obj)
  1076. for refname, sha in refs.iteritems():
  1077. ret.refs[refname] = sha
  1078. ret._init_files(bare=True)
  1079. return ret