repo.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. # repo.py -- For dealing with git repositories.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2013 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. This module contains the base class for git repositories
  22. (BaseRepo) and an implementation which uses a repository on
  23. local disk (Repo).
  24. """
  25. from io import BytesIO
  26. import errno
  27. import os
  28. import sys
  29. from dulwich.errors import (
  30. NoIndexPresent,
  31. NotBlobError,
  32. NotCommitError,
  33. NotGitRepository,
  34. NotTreeError,
  35. NotTagError,
  36. CommitError,
  37. RefFormatError,
  38. HookError,
  39. )
  40. from dulwich.file import (
  41. GitFile,
  42. )
  43. from dulwich.object_store import (
  44. DiskObjectStore,
  45. MemoryObjectStore,
  46. ObjectStoreGraphWalker,
  47. )
  48. from dulwich.objects import (
  49. check_hexsha,
  50. Blob,
  51. Commit,
  52. ShaFile,
  53. Tag,
  54. Tree,
  55. )
  56. from dulwich.hooks import (
  57. PreCommitShellHook,
  58. PostCommitShellHook,
  59. CommitMsgShellHook,
  60. )
  61. from dulwich.refs import (
  62. check_ref_format,
  63. RefsContainer,
  64. DictRefsContainer,
  65. InfoRefsContainer,
  66. DiskRefsContainer,
  67. read_packed_refs,
  68. read_packed_refs_with_peeled,
  69. write_packed_refs,
  70. SYMREF,
  71. )
  72. import warnings
  73. OBJECTDIR = 'objects'
  74. REFSDIR = 'refs'
  75. REFSDIR_TAGS = 'tags'
  76. REFSDIR_HEADS = 'heads'
  77. INDEX_FILENAME = "index"
  78. BASE_DIRECTORIES = [
  79. ["branches"],
  80. [REFSDIR],
  81. [REFSDIR, REFSDIR_TAGS],
  82. [REFSDIR, REFSDIR_HEADS],
  83. ["hooks"],
  84. ["info"]
  85. ]
  86. def parse_graftpoints(graftpoints):
  87. """Convert a list of graftpoints into a dict
  88. :param graftpoints: Iterator of graftpoint lines
  89. Each line is formatted as:
  90. <commit sha1> <parent sha1> [<parent sha1>]*
  91. Resulting dictionary is:
  92. <commit sha1>: [<parent sha1>*]
  93. https://git.wiki.kernel.org/index.php/GraftPoint
  94. """
  95. grafts = {}
  96. for l in graftpoints:
  97. raw_graft = l.split(None, 1)
  98. commit = raw_graft[0]
  99. if len(raw_graft) == 2:
  100. parents = raw_graft[1].split()
  101. else:
  102. parents = []
  103. for sha in [commit] + parents:
  104. check_hexsha(sha, 'Invalid graftpoint')
  105. grafts[commit] = parents
  106. return grafts
  107. def serialize_graftpoints(graftpoints):
  108. """Convert a dictionary of grafts into string
  109. The graft dictionary is:
  110. <commit sha1>: [<parent sha1>*]
  111. Each line is formatted as:
  112. <commit sha1> <parent sha1> [<parent sha1>]*
  113. https://git.wiki.kernel.org/index.php/GraftPoint
  114. """
  115. graft_lines = []
  116. for commit, parents in graftpoints.items():
  117. if parents:
  118. graft_lines.append(commit + b' ' + b' '.join(parents))
  119. else:
  120. graft_lines.append(commit)
  121. return b'\n'.join(graft_lines)
  122. class BaseRepo(object):
  123. """Base class for a git repository.
  124. :ivar object_store: Dictionary-like object for accessing
  125. the objects
  126. :ivar refs: Dictionary-like object with the refs in this
  127. repository
  128. """
  129. def __init__(self, object_store, refs):
  130. """Open a repository.
  131. This shouldn't be called directly, but rather through one of the
  132. base classes, such as MemoryRepo or Repo.
  133. :param object_store: Object store to use
  134. :param refs: Refs container to use
  135. """
  136. self.object_store = object_store
  137. self.refs = refs
  138. self._graftpoints = {}
  139. self.hooks = {}
  140. def _init_files(self, bare):
  141. """Initialize a default set of named files."""
  142. from dulwich.config import ConfigFile
  143. self._put_named_file('description', b"Unnamed repository")
  144. f = BytesIO()
  145. cf = ConfigFile()
  146. cf.set(b"core", b"repositoryformatversion", b"0")
  147. cf.set(b"core", b"filemode", b"true")
  148. cf.set(b"core", b"bare", bare)
  149. cf.set(b"core", b"logallrefupdates", True)
  150. cf.write_to_file(f)
  151. self._put_named_file('config', f.getvalue())
  152. self._put_named_file(os.path.join('info', 'exclude'), b'')
  153. def get_named_file(self, path):
  154. """Get a file from the control dir with a specific name.
  155. Although the filename should be interpreted as a filename relative to
  156. the control dir in a disk-based Repo, the object returned need not be
  157. pointing to a file in that location.
  158. :param path: The path to the file, relative to the control dir.
  159. :return: An open file object, or None if the file does not exist.
  160. """
  161. raise NotImplementedError(self.get_named_file)
  162. def _put_named_file(self, path, contents):
  163. """Write a file to the control dir with the given name and contents.
  164. :param path: The path to the file, relative to the control dir.
  165. :param contents: A string to write to the file.
  166. """
  167. raise NotImplementedError(self._put_named_file)
  168. def open_index(self):
  169. """Open the index for this repository.
  170. :raise NoIndexPresent: If no index is present
  171. :return: The matching `Index`
  172. """
  173. raise NotImplementedError(self.open_index)
  174. def fetch(self, target, determine_wants=None, progress=None):
  175. """Fetch objects into another repository.
  176. :param target: The target repository
  177. :param determine_wants: Optional function to determine what refs to
  178. fetch.
  179. :param progress: Optional progress function
  180. :return: The local refs
  181. """
  182. if determine_wants is None:
  183. determine_wants = target.object_store.determine_wants_all
  184. target.object_store.add_objects(
  185. self.fetch_objects(determine_wants, target.get_graph_walker(),
  186. progress))
  187. return self.get_refs()
  188. def fetch_objects(self, determine_wants, graph_walker, progress,
  189. get_tagged=None):
  190. """Fetch the missing objects required for a set of revisions.
  191. :param determine_wants: Function that takes a dictionary with heads
  192. and returns the list of heads to fetch.
  193. :param graph_walker: Object that can iterate over the list of revisions
  194. to fetch and has an "ack" method that will be called to acknowledge
  195. that a revision is present.
  196. :param progress: Simple progress function that will be called with
  197. updated progress strings.
  198. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  199. sha for including tags.
  200. :return: iterator over objects, with __len__ implemented
  201. """
  202. wants = determine_wants(self.get_refs())
  203. if not isinstance(wants, list):
  204. raise TypeError("determine_wants() did not return a list")
  205. shallows = getattr(graph_walker, 'shallow', frozenset())
  206. unshallows = getattr(graph_walker, 'unshallow', frozenset())
  207. if wants == []:
  208. # TODO(dborowitz): find a way to short-circuit that doesn't change
  209. # this interface.
  210. if shallows or unshallows:
  211. # Do not send a pack in shallow short-circuit path
  212. return None
  213. return []
  214. haves = self.object_store.find_common_revisions(graph_walker)
  215. # Deal with shallow requests separately because the haves do
  216. # not reflect what objects are missing
  217. if shallows or unshallows:
  218. haves = [] # TODO: filter the haves commits from iter_shas.
  219. # the specific commits aren't missing.
  220. def get_parents(commit):
  221. if commit.id in shallows:
  222. return []
  223. return self.get_parents(commit.id, commit)
  224. return self.object_store.iter_shas(
  225. self.object_store.find_missing_objects(
  226. haves, wants, progress,
  227. get_tagged,
  228. get_parents=get_parents))
  229. def get_graph_walker(self, heads=None):
  230. """Retrieve a graph walker.
  231. A graph walker is used by a remote repository (or proxy)
  232. to find out which objects are present in this repository.
  233. :param heads: Repository heads to use (optional)
  234. :return: A graph walker object
  235. """
  236. if heads is None:
  237. heads = self.refs.as_dict(b'refs/heads').values()
  238. return ObjectStoreGraphWalker(heads, self.get_parents)
  239. def get_refs(self):
  240. """Get dictionary with all refs.
  241. :return: A ``dict`` mapping ref names to SHA1s
  242. """
  243. return self.refs.as_dict()
  244. def head(self):
  245. """Return the SHA1 pointed at by HEAD."""
  246. return self.refs[b'HEAD']
  247. def _get_object(self, sha, cls):
  248. assert len(sha) in (20, 40)
  249. ret = self.get_object(sha)
  250. if not isinstance(ret, cls):
  251. if cls is Commit:
  252. raise NotCommitError(ret)
  253. elif cls is Blob:
  254. raise NotBlobError(ret)
  255. elif cls is Tree:
  256. raise NotTreeError(ret)
  257. elif cls is Tag:
  258. raise NotTagError(ret)
  259. else:
  260. raise Exception("Type invalid: %r != %r" % (
  261. ret.type_name, cls.type_name))
  262. return ret
  263. def get_object(self, sha):
  264. """Retrieve the object with the specified SHA.
  265. :param sha: SHA to retrieve
  266. :return: A ShaFile object
  267. :raise KeyError: when the object can not be found
  268. """
  269. return self.object_store[sha]
  270. def get_parents(self, sha, commit=None):
  271. """Retrieve the parents of a specific commit.
  272. If the specific commit is a graftpoint, the graft parents
  273. will be returned instead.
  274. :param sha: SHA of the commit for which to retrieve the parents
  275. :param commit: Optional commit matching the sha
  276. :return: List of parents
  277. """
  278. try:
  279. return self._graftpoints[sha]
  280. except KeyError:
  281. if commit is None:
  282. commit = self[sha]
  283. return commit.parents
  284. def get_config(self):
  285. """Retrieve the config object.
  286. :return: `ConfigFile` object for the ``.git/config`` file.
  287. """
  288. raise NotImplementedError(self.get_config)
  289. def get_description(self):
  290. """Retrieve the description for this repository.
  291. :return: String with the description of the repository
  292. as set by the user.
  293. """
  294. raise NotImplementedError(self.get_description)
  295. def set_description(self, description):
  296. """Set the description for this repository.
  297. :param description: Text to set as description for this repository.
  298. """
  299. raise NotImplementedError(self.set_description)
  300. def get_config_stack(self):
  301. """Return a config stack for this repository.
  302. This stack accesses the configuration for both this repository
  303. itself (.git/config) and the global configuration, which usually
  304. lives in ~/.gitconfig.
  305. :return: `Config` instance for this repository
  306. """
  307. from dulwich.config import StackedConfig
  308. backends = [self.get_config()] + StackedConfig.default_backends()
  309. return StackedConfig(backends, writable=backends[0])
  310. def get_peeled(self, ref):
  311. """Get the peeled value of a ref.
  312. :param ref: The refname to peel.
  313. :return: The fully-peeled SHA1 of a tag object, after peeling all
  314. intermediate tags; if the original ref does not point to a tag, this
  315. will equal the original SHA1.
  316. """
  317. cached = self.refs.get_peeled(ref)
  318. if cached is not None:
  319. return cached
  320. return self.object_store.peel_sha(self.refs[ref]).id
  321. def get_walker(self, include=None, *args, **kwargs):
  322. """Obtain a walker for this repository.
  323. :param include: Iterable of SHAs of commits to include along with their
  324. ancestors. Defaults to [HEAD]
  325. :param exclude: Iterable of SHAs of commits to exclude along with their
  326. ancestors, overriding includes.
  327. :param order: ORDER_* constant specifying the order of results. Anything
  328. other than ORDER_DATE may result in O(n) memory usage.
  329. :param reverse: If True, reverse the order of output, requiring O(n)
  330. memory.
  331. :param max_entries: The maximum number of entries to yield, or None for
  332. no limit.
  333. :param paths: Iterable of file or subtree paths to show entries for.
  334. :param rename_detector: diff.RenameDetector object for detecting
  335. renames.
  336. :param follow: If True, follow path across renames/copies. Forces a
  337. default rename_detector.
  338. :param since: Timestamp to list commits after.
  339. :param until: Timestamp to list commits before.
  340. :param queue_cls: A class to use for a queue of commits, supporting the
  341. iterator protocol. The constructor takes a single argument, the
  342. Walker.
  343. :return: A `Walker` object
  344. """
  345. from dulwich.walk import Walker
  346. if include is None:
  347. include = [self.head()]
  348. if isinstance(include, str):
  349. include = [include]
  350. kwargs['get_parents'] = lambda commit: self.get_parents(commit.id, commit)
  351. return Walker(self.object_store, include, *args, **kwargs)
  352. def __getitem__(self, name):
  353. """Retrieve a Git object by SHA1 or ref.
  354. :param name: A Git object SHA1 or a ref name
  355. :return: A `ShaFile` object, such as a Commit or Blob
  356. :raise KeyError: when the specified ref or object does not exist
  357. """
  358. if not isinstance(name, bytes):
  359. raise TypeError("'name' must be bytestring, not %.80s" %
  360. type(name).__name__)
  361. if len(name) in (20, 40):
  362. try:
  363. return self.object_store[name]
  364. except (KeyError, ValueError):
  365. pass
  366. try:
  367. return self.object_store[self.refs[name]]
  368. except RefFormatError:
  369. raise KeyError(name)
  370. def __contains__(self, name):
  371. """Check if a specific Git object or ref is present.
  372. :param name: Git object SHA1 or ref name
  373. """
  374. if len(name) in (20, 40):
  375. return name in self.object_store or name in self.refs
  376. else:
  377. return name in self.refs
  378. def __setitem__(self, name, value):
  379. """Set a ref.
  380. :param name: ref name
  381. :param value: Ref value - either a ShaFile object, or a hex sha
  382. """
  383. if name.startswith(b"refs/") or name == b'HEAD':
  384. if isinstance(value, ShaFile):
  385. self.refs[name] = value.id
  386. elif isinstance(value, bytes):
  387. self.refs[name] = value
  388. else:
  389. raise TypeError(value)
  390. else:
  391. raise ValueError(name)
  392. def __delitem__(self, name):
  393. """Remove a ref.
  394. :param name: Name of the ref to remove
  395. """
  396. if name.startswith(b"refs/") or name == b"HEAD":
  397. del self.refs[name]
  398. else:
  399. raise ValueError(name)
  400. def _get_user_identity(self):
  401. """Determine the identity to use for new commits.
  402. """
  403. config = self.get_config_stack()
  404. return (config.get((b"user", ), b"name") + b" <" +
  405. config.get((b"user", ), b"email") + b">")
  406. def _add_graftpoints(self, updated_graftpoints):
  407. """Add or modify graftpoints
  408. :param updated_graftpoints: Dict of commit shas to list of parent shas
  409. """
  410. # Simple validation
  411. for commit, parents in updated_graftpoints.items():
  412. for sha in [commit] + parents:
  413. check_hexsha(sha, 'Invalid graftpoint')
  414. self._graftpoints.update(updated_graftpoints)
  415. def _remove_graftpoints(self, to_remove=[]):
  416. """Remove graftpoints
  417. :param to_remove: List of commit shas
  418. """
  419. for sha in to_remove:
  420. del self._graftpoints[sha]
  421. def do_commit(self, message=None, committer=None,
  422. author=None, commit_timestamp=None,
  423. commit_timezone=None, author_timestamp=None,
  424. author_timezone=None, tree=None, encoding=None,
  425. ref=b'HEAD', merge_heads=None):
  426. """Create a new commit.
  427. :param message: Commit message
  428. :param committer: Committer fullname
  429. :param author: Author fullname (defaults to committer)
  430. :param commit_timestamp: Commit timestamp (defaults to now)
  431. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  432. :param author_timestamp: Author timestamp (defaults to commit timestamp)
  433. :param author_timezone: Author timestamp timezone
  434. (defaults to commit timestamp timezone)
  435. :param tree: SHA1 of the tree root to use (if not specified the
  436. current index will be committed).
  437. :param encoding: Encoding
  438. :param ref: Optional ref to commit to (defaults to current branch)
  439. :param merge_heads: Merge heads (defaults to .git/MERGE_HEADS)
  440. :return: New commit SHA1
  441. """
  442. import time
  443. c = Commit()
  444. if tree is None:
  445. index = self.open_index()
  446. c.tree = index.commit(self.object_store)
  447. else:
  448. if len(tree) != 40:
  449. raise ValueError("tree must be a 40-byte hex sha string")
  450. c.tree = tree
  451. try:
  452. self.hooks['pre-commit'].execute()
  453. except HookError as e:
  454. raise CommitError(e)
  455. except KeyError: # no hook defined, silent fallthrough
  456. pass
  457. if merge_heads is None:
  458. # FIXME: Read merge heads from .git/MERGE_HEADS
  459. merge_heads = []
  460. if committer is None:
  461. # FIXME: Support GIT_COMMITTER_NAME/GIT_COMMITTER_EMAIL environment
  462. # variables
  463. committer = self._get_user_identity()
  464. c.committer = committer
  465. if commit_timestamp is None:
  466. # FIXME: Support GIT_COMMITTER_DATE environment variable
  467. commit_timestamp = time.time()
  468. c.commit_time = int(commit_timestamp)
  469. if commit_timezone is None:
  470. # FIXME: Use current user timezone rather than UTC
  471. commit_timezone = 0
  472. c.commit_timezone = commit_timezone
  473. if author is None:
  474. # FIXME: Support GIT_AUTHOR_NAME/GIT_AUTHOR_EMAIL environment
  475. # variables
  476. author = committer
  477. c.author = author
  478. if author_timestamp is None:
  479. # FIXME: Support GIT_AUTHOR_DATE environment variable
  480. author_timestamp = commit_timestamp
  481. c.author_time = int(author_timestamp)
  482. if author_timezone is None:
  483. author_timezone = commit_timezone
  484. c.author_timezone = author_timezone
  485. if encoding is not None:
  486. c.encoding = encoding
  487. if message is None:
  488. # FIXME: Try to read commit message from .git/MERGE_MSG
  489. raise ValueError("No commit message specified")
  490. try:
  491. c.message = self.hooks['commit-msg'].execute(message)
  492. if c.message is None:
  493. c.message = message
  494. except HookError as e:
  495. raise CommitError(e)
  496. except KeyError: # no hook defined, message not modified
  497. c.message = message
  498. if ref is None:
  499. # Create a dangling commit
  500. c.parents = merge_heads
  501. self.object_store.add_object(c)
  502. else:
  503. try:
  504. old_head = self.refs[ref]
  505. c.parents = [old_head] + merge_heads
  506. self.object_store.add_object(c)
  507. ok = self.refs.set_if_equals(ref, old_head, c.id)
  508. except KeyError:
  509. c.parents = merge_heads
  510. self.object_store.add_object(c)
  511. ok = self.refs.add_if_new(ref, c.id)
  512. if not ok:
  513. # Fail if the atomic compare-and-swap failed, leaving the commit and
  514. # all its objects as garbage.
  515. raise CommitError("%s changed during commit" % (ref,))
  516. try:
  517. self.hooks['post-commit'].execute()
  518. except HookError as e: # silent failure
  519. warnings.warn("post-commit hook failed: %s" % e, UserWarning)
  520. except KeyError: # no hook defined, silent fallthrough
  521. pass
  522. return c.id
  523. class Repo(BaseRepo):
  524. """A git repository backed by local disk.
  525. To open an existing repository, call the contructor with
  526. the path of the repository.
  527. To create a new repository, use the Repo.init class method.
  528. """
  529. def __init__(self, root):
  530. if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
  531. self.bare = False
  532. self._controldir = os.path.join(root, ".git")
  533. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  534. os.path.isdir(os.path.join(root, REFSDIR))):
  535. self.bare = True
  536. self._controldir = root
  537. elif (os.path.isfile(os.path.join(root, ".git"))):
  538. import re
  539. with open(os.path.join(root, ".git"), 'r') as f:
  540. _, path = re.match('(gitdir: )(.+$)', f.read()).groups()
  541. self.bare = False
  542. self._controldir = os.path.join(root, path)
  543. else:
  544. raise NotGitRepository(
  545. "No git repository was found at %(path)s" % dict(path=root)
  546. )
  547. self.path = root
  548. object_store = DiskObjectStore(os.path.join(self.controldir(),
  549. OBJECTDIR))
  550. refs = DiskRefsContainer(self.controldir())
  551. BaseRepo.__init__(self, object_store, refs)
  552. self._graftpoints = {}
  553. graft_file = self.get_named_file(os.path.join("info", "grafts"))
  554. if graft_file:
  555. with graft_file:
  556. self._graftpoints.update(parse_graftpoints(graft_file))
  557. graft_file = self.get_named_file("shallow")
  558. if graft_file:
  559. with graft_file:
  560. self._graftpoints.update(parse_graftpoints(graft_file))
  561. self.hooks['pre-commit'] = PreCommitShellHook(self.controldir())
  562. self.hooks['commit-msg'] = CommitMsgShellHook(self.controldir())
  563. self.hooks['post-commit'] = PostCommitShellHook(self.controldir())
  564. def controldir(self):
  565. """Return the path of the control directory."""
  566. return self._controldir
  567. def _put_named_file(self, path, contents):
  568. """Write a file to the control dir with the given name and contents.
  569. :param path: The path to the file, relative to the control dir.
  570. :param contents: A string to write to the file.
  571. """
  572. path = path.lstrip(os.path.sep)
  573. with GitFile(os.path.join(self.controldir(), path), 'wb') as f:
  574. f.write(contents)
  575. def get_named_file(self, path):
  576. """Get a file from the control dir with a specific name.
  577. Although the filename should be interpreted as a filename relative to
  578. the control dir in a disk-based Repo, the object returned need not be
  579. pointing to a file in that location.
  580. :param path: The path to the file, relative to the control dir.
  581. :return: An open file object, or None if the file does not exist.
  582. """
  583. # TODO(dborowitz): sanitize filenames, since this is used directly by
  584. # the dumb web serving code.
  585. path = path.lstrip(os.path.sep)
  586. try:
  587. return open(os.path.join(self.controldir(), path), 'rb')
  588. except (IOError, OSError) as e:
  589. if e.errno == errno.ENOENT:
  590. return None
  591. raise
  592. def index_path(self):
  593. """Return path to the index file."""
  594. return os.path.join(self.controldir(), INDEX_FILENAME)
  595. def open_index(self):
  596. """Open the index for this repository.
  597. :raise NoIndexPresent: If no index is present
  598. :return: The matching `Index`
  599. """
  600. from dulwich.index import Index
  601. if not self.has_index():
  602. raise NoIndexPresent()
  603. return Index(self.index_path())
  604. def has_index(self):
  605. """Check if an index is present."""
  606. # Bare repos must never have index files; non-bare repos may have a
  607. # missing index file, which is treated as empty.
  608. return not self.bare
  609. def stage(self, paths, fsencoding=sys.getfilesystemencoding()):
  610. """Stage a set of paths.
  611. :param paths: List of paths, relative to the repository path
  612. """
  613. if not isinstance(paths, list):
  614. paths = [paths]
  615. from dulwich.index import (
  616. blob_from_path_and_stat,
  617. index_entry_from_stat,
  618. )
  619. index = self.open_index()
  620. for path in paths:
  621. full_path = os.path.join(self.path, path)
  622. try:
  623. st = os.lstat(full_path)
  624. except OSError:
  625. # File no longer exists
  626. try:
  627. del index[path.encode(fsencoding)]
  628. except KeyError:
  629. pass # already removed
  630. else:
  631. blob = blob_from_path_and_stat(full_path, st)
  632. self.object_store.add_object(blob)
  633. index[path.encode(fsencoding)] = index_entry_from_stat(st, blob.id, 0)
  634. index.write()
  635. def clone(self, target_path, mkdir=True, bare=False,
  636. origin=b"origin"):
  637. """Clone this repository.
  638. :param target_path: Target path
  639. :param mkdir: Create the target directory
  640. :param bare: Whether to create a bare repository
  641. :param origin: Base name for refs in target repository
  642. cloned from this repository
  643. :return: Created repository as `Repo`
  644. """
  645. if not bare:
  646. target = self.init(target_path, mkdir=mkdir)
  647. else:
  648. target = self.init_bare(target_path)
  649. self.fetch(target)
  650. target.refs.import_refs(
  651. b'refs/remotes/' + origin, self.refs.as_dict(b'refs/heads'))
  652. target.refs.import_refs(
  653. b'refs/tags', self.refs.as_dict(b'refs/tags'))
  654. try:
  655. target.refs.add_if_new(
  656. b'refs/heads/master',
  657. self.refs[b'refs/heads/master'])
  658. except KeyError:
  659. pass
  660. # Update target head
  661. head, head_sha = self.refs._follow(b'HEAD')
  662. if head is not None and head_sha is not None:
  663. target.refs.set_symbolic_ref(b'HEAD', head)
  664. target[b'HEAD'] = head_sha
  665. if not bare:
  666. # Checkout HEAD to target dir
  667. target.reset_index()
  668. return target
  669. def reset_index(self, tree=None):
  670. """Reset the index back to a specific tree.
  671. :param tree: Tree SHA to reset to, None for current HEAD tree.
  672. """
  673. from dulwich.index import (
  674. build_index_from_tree,
  675. validate_path_element_default,
  676. validate_path_element_ntfs,
  677. )
  678. if tree is None:
  679. tree = self[b'HEAD'].tree
  680. config = self.get_config()
  681. honor_filemode = config.get_boolean('core', 'filemode', os.name != "nt")
  682. if config.get_boolean('core', 'core.protectNTFS', os.name == "nt"):
  683. validate_path_element = validate_path_element_ntfs
  684. else:
  685. validate_path_element = validate_path_element_default
  686. return build_index_from_tree(self.path, self.index_path(),
  687. self.object_store, tree, honor_filemode=honor_filemode,
  688. validate_path_element=validate_path_element)
  689. def get_config(self):
  690. """Retrieve the config object.
  691. :return: `ConfigFile` object for the ``.git/config`` file.
  692. """
  693. from dulwich.config import ConfigFile
  694. path = os.path.join(self._controldir, 'config')
  695. try:
  696. return ConfigFile.from_path(path)
  697. except (IOError, OSError) as e:
  698. if e.errno != errno.ENOENT:
  699. raise
  700. ret = ConfigFile()
  701. ret.path = path
  702. return ret
  703. def get_description(self):
  704. """Retrieve the description of this repository.
  705. :return: A string describing the repository or None.
  706. """
  707. path = os.path.join(self._controldir, 'description')
  708. try:
  709. with GitFile(path, 'rb') as f:
  710. return f.read()
  711. except (IOError, OSError) as e:
  712. if e.errno != errno.ENOENT:
  713. raise
  714. return None
  715. def __repr__(self):
  716. return "<Repo at %r>" % self.path
  717. def set_description(self, description):
  718. """Set the description for this repository.
  719. :param description: Text to set as description for this repository.
  720. """
  721. self._put_named_file('description', description)
  722. @classmethod
  723. def _init_maybe_bare(cls, path, bare):
  724. for d in BASE_DIRECTORIES:
  725. os.mkdir(os.path.join(path, *d))
  726. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  727. ret = cls(path)
  728. ret.refs.set_symbolic_ref(b'HEAD', b"refs/heads/master")
  729. ret._init_files(bare)
  730. return ret
  731. @classmethod
  732. def init(cls, path, mkdir=False):
  733. """Create a new repository.
  734. :param path: Path in which to create the repository
  735. :param mkdir: Whether to create the directory
  736. :return: `Repo` instance
  737. """
  738. if mkdir:
  739. os.mkdir(path)
  740. controldir = os.path.join(path, ".git")
  741. os.mkdir(controldir)
  742. cls._init_maybe_bare(controldir, False)
  743. return cls(path)
  744. @classmethod
  745. def init_bare(cls, path):
  746. """Create a new bare repository.
  747. ``path`` should already exist and be an emty directory.
  748. :param path: Path to create bare repository in
  749. :return: a `Repo` instance
  750. """
  751. return cls._init_maybe_bare(path, True)
  752. create = init_bare
  753. class MemoryRepo(BaseRepo):
  754. """Repo that stores refs, objects, and named files in memory.
  755. MemoryRepos are always bare: they have no working tree and no index, since
  756. those have a stronger dependency on the filesystem.
  757. """
  758. def __init__(self):
  759. from dulwich.config import ConfigFile
  760. BaseRepo.__init__(self, MemoryObjectStore(), DictRefsContainer({}))
  761. self._named_files = {}
  762. self.bare = True
  763. self._config = ConfigFile()
  764. def _put_named_file(self, path, contents):
  765. """Write a file to the control dir with the given name and contents.
  766. :param path: The path to the file, relative to the control dir.
  767. :param contents: A string to write to the file.
  768. """
  769. self._named_files[path] = contents
  770. def get_named_file(self, path):
  771. """Get a file from the control dir with a specific name.
  772. Although the filename should be interpreted as a filename relative to
  773. the control dir in a disk-baked Repo, the object returned need not be
  774. pointing to a file in that location.
  775. :param path: The path to the file, relative to the control dir.
  776. :return: An open file object, or None if the file does not exist.
  777. """
  778. contents = self._named_files.get(path, None)
  779. if contents is None:
  780. return None
  781. return BytesIO(contents)
  782. def open_index(self):
  783. """Fail to open index for this repo, since it is bare.
  784. :raise NoIndexPresent: Raised when no index is present
  785. """
  786. raise NoIndexPresent()
  787. def get_config(self):
  788. """Retrieve the config object.
  789. :return: `ConfigFile` object.
  790. """
  791. return self._config
  792. def get_description(self):
  793. """Retrieve the repository description.
  794. This defaults to None, for no description.
  795. """
  796. return None
  797. @classmethod
  798. def init_bare(cls, objects, refs):
  799. """Create a new bare repository in memory.
  800. :param objects: Objects for the new repository,
  801. as iterable
  802. :param refs: Refs as dictionary, mapping names
  803. to object SHA1s
  804. """
  805. ret = cls()
  806. for obj in objects:
  807. ret.object_store.add_object(obj)
  808. for refname, sha in refs.items():
  809. ret.refs[refname] = sha
  810. ret._init_files(bare=True)
  811. return ret