repo.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Repository access.
  22. This module contains the base class for git repositories
  23. (BaseRepo) and an implementation which uses a repository on
  24. local disk (Repo).
  25. """
  26. from io import BytesIO
  27. import errno
  28. import os
  29. import sys
  30. import stat
  31. import time
  32. from dulwich.errors import (
  33. NoIndexPresent,
  34. NotBlobError,
  35. NotCommitError,
  36. NotGitRepository,
  37. NotTreeError,
  38. NotTagError,
  39. CommitError,
  40. RefFormatError,
  41. HookError,
  42. )
  43. from dulwich.file import (
  44. GitFile,
  45. )
  46. from dulwich.object_store import (
  47. DiskObjectStore,
  48. MemoryObjectStore,
  49. ObjectStoreGraphWalker,
  50. )
  51. from dulwich.objects import (
  52. check_hexsha,
  53. Blob,
  54. Commit,
  55. ShaFile,
  56. Tag,
  57. Tree,
  58. )
  59. from dulwich.hooks import (
  60. PreCommitShellHook,
  61. PostCommitShellHook,
  62. CommitMsgShellHook,
  63. )
  64. from dulwich.refs import ( # noqa: F401
  65. check_ref_format,
  66. RefsContainer,
  67. DictRefsContainer,
  68. InfoRefsContainer,
  69. DiskRefsContainer,
  70. read_packed_refs,
  71. read_packed_refs_with_peeled,
  72. write_packed_refs,
  73. SYMREF,
  74. )
  75. import warnings
  76. CONTROLDIR = '.git'
  77. OBJECTDIR = 'objects'
  78. REFSDIR = 'refs'
  79. REFSDIR_TAGS = 'tags'
  80. REFSDIR_HEADS = 'heads'
  81. INDEX_FILENAME = "index"
  82. COMMONDIR = 'commondir'
  83. GITDIR = 'gitdir'
  84. WORKTREES = 'worktrees'
  85. BASE_DIRECTORIES = [
  86. ["branches"],
  87. [REFSDIR],
  88. [REFSDIR, REFSDIR_TAGS],
  89. [REFSDIR, REFSDIR_HEADS],
  90. ["hooks"],
  91. ["info"]
  92. ]
  93. DEFAULT_REF = b'refs/heads/master'
  94. class InvalidUserIdentity(Exception):
  95. """User identity is not of the format 'user <email>'"""
  96. def __init__(self, identity):
  97. self.identity = identity
  98. def check_user_identity(identity):
  99. """Verify that a user identity is formatted correctly.
  100. :param identity: User identity bytestring
  101. :raise InvalidUserIdentity: Raised when identity is invalid
  102. """
  103. try:
  104. fst, snd = identity.split(b' <', 1)
  105. except ValueError:
  106. raise InvalidUserIdentity(identity)
  107. if b'>' not in snd:
  108. raise InvalidUserIdentity(identity)
  109. def parse_graftpoints(graftpoints):
  110. """Convert a list of graftpoints into a dict
  111. :param graftpoints: Iterator of graftpoint lines
  112. Each line is formatted as:
  113. <commit sha1> <parent sha1> [<parent sha1>]*
  114. Resulting dictionary is:
  115. <commit sha1>: [<parent sha1>*]
  116. https://git.wiki.kernel.org/index.php/GraftPoint
  117. """
  118. grafts = {}
  119. for l in graftpoints:
  120. raw_graft = l.split(None, 1)
  121. commit = raw_graft[0]
  122. if len(raw_graft) == 2:
  123. parents = raw_graft[1].split()
  124. else:
  125. parents = []
  126. for sha in [commit] + parents:
  127. check_hexsha(sha, 'Invalid graftpoint')
  128. grafts[commit] = parents
  129. return grafts
  130. def serialize_graftpoints(graftpoints):
  131. """Convert a dictionary of grafts into string
  132. The graft dictionary is:
  133. <commit sha1>: [<parent sha1>*]
  134. Each line is formatted as:
  135. <commit sha1> <parent sha1> [<parent sha1>]*
  136. https://git.wiki.kernel.org/index.php/GraftPoint
  137. """
  138. graft_lines = []
  139. for commit, parents in graftpoints.items():
  140. if parents:
  141. graft_lines.append(commit + b' ' + b' '.join(parents))
  142. else:
  143. graft_lines.append(commit)
  144. return b'\n'.join(graft_lines)
  145. class BaseRepo(object):
  146. """Base class for a git repository.
  147. :ivar object_store: Dictionary-like object for accessing
  148. the objects
  149. :ivar refs: Dictionary-like object with the refs in this
  150. repository
  151. """
  152. def __init__(self, object_store, refs):
  153. """Open a repository.
  154. This shouldn't be called directly, but rather through one of the
  155. base classes, such as MemoryRepo or Repo.
  156. :param object_store: Object store to use
  157. :param refs: Refs container to use
  158. """
  159. self.object_store = object_store
  160. self.refs = refs
  161. self._graftpoints = {}
  162. self.hooks = {}
  163. def _determine_file_mode(self):
  164. """Probe the file-system to determine whether permissions can be trusted.
  165. :return: True if permissions can be trusted, False otherwise.
  166. """
  167. raise NotImplementedError(self._determine_file_mode)
  168. def _init_files(self, bare):
  169. """Initialize a default set of named files."""
  170. from dulwich.config import ConfigFile
  171. self._put_named_file('description', b"Unnamed repository")
  172. f = BytesIO()
  173. cf = ConfigFile()
  174. cf.set("core", "repositoryformatversion", "0")
  175. if self._determine_file_mode():
  176. cf.set("core", "filemode", True)
  177. else:
  178. cf.set("core", "filemode", False)
  179. cf.set("core", "bare", bare)
  180. cf.set("core", "logallrefupdates", True)
  181. cf.write_to_file(f)
  182. self._put_named_file('config', f.getvalue())
  183. self._put_named_file(os.path.join('info', 'exclude'), b'')
  184. def get_named_file(self, path):
  185. """Get a file from the control dir with a specific name.
  186. Although the filename should be interpreted as a filename relative to
  187. the control dir in a disk-based Repo, the object returned need not be
  188. pointing to a file in that location.
  189. :param path: The path to the file, relative to the control dir.
  190. :return: An open file object, or None if the file does not exist.
  191. """
  192. raise NotImplementedError(self.get_named_file)
  193. def _put_named_file(self, path, contents):
  194. """Write a file to the control dir with the given name and contents.
  195. :param path: The path to the file, relative to the control dir.
  196. :param contents: A string to write to the file.
  197. """
  198. raise NotImplementedError(self._put_named_file)
  199. def open_index(self):
  200. """Open the index for this repository.
  201. :raise NoIndexPresent: If no index is present
  202. :return: The matching `Index`
  203. """
  204. raise NotImplementedError(self.open_index)
  205. def fetch(self, target, determine_wants=None, progress=None):
  206. """Fetch objects into another repository.
  207. :param target: The target repository
  208. :param determine_wants: Optional function to determine what refs to
  209. fetch.
  210. :param progress: Optional progress function
  211. :return: The local refs
  212. """
  213. if determine_wants is None:
  214. determine_wants = target.object_store.determine_wants_all
  215. target.object_store.add_objects(
  216. self.fetch_objects(determine_wants, target.get_graph_walker(),
  217. progress))
  218. return self.get_refs()
  219. def fetch_objects(self, determine_wants, graph_walker, progress,
  220. get_tagged=None):
  221. """Fetch the missing objects required for a set of revisions.
  222. :param determine_wants: Function that takes a dictionary with heads
  223. and returns the list of heads to fetch.
  224. :param graph_walker: Object that can iterate over the list of revisions
  225. to fetch and has an "ack" method that will be called to acknowledge
  226. that a revision is present.
  227. :param progress: Simple progress function that will be called with
  228. updated progress strings.
  229. :param get_tagged: Function that returns a dict of pointed-to sha ->
  230. tag sha for including tags.
  231. :return: iterator over objects, with __len__ implemented
  232. """
  233. wants = determine_wants(self.get_refs())
  234. if not isinstance(wants, list):
  235. raise TypeError("determine_wants() did not return a list")
  236. shallows = getattr(graph_walker, 'shallow', frozenset())
  237. unshallows = getattr(graph_walker, 'unshallow', frozenset())
  238. if wants == []:
  239. # TODO(dborowitz): find a way to short-circuit that doesn't change
  240. # this interface.
  241. if shallows or unshallows:
  242. # Do not send a pack in shallow short-circuit path
  243. return None
  244. return []
  245. # If the graph walker is set up with an implementation that can
  246. # ACK/NAK to the wire, it will write data to the client through
  247. # this call as a side-effect.
  248. haves = self.object_store.find_common_revisions(graph_walker)
  249. # Deal with shallow requests separately because the haves do
  250. # not reflect what objects are missing
  251. if shallows or unshallows:
  252. # TODO: filter the haves commits from iter_shas. the specific
  253. # commits aren't missing.
  254. haves = []
  255. def get_parents(commit):
  256. if commit.id in shallows:
  257. return []
  258. return self.get_parents(commit.id, commit)
  259. return self.object_store.iter_shas(
  260. self.object_store.find_missing_objects(
  261. haves, wants, progress,
  262. get_tagged,
  263. get_parents=get_parents))
  264. def get_graph_walker(self, heads=None):
  265. """Retrieve a graph walker.
  266. A graph walker is used by a remote repository (or proxy)
  267. to find out which objects are present in this repository.
  268. :param heads: Repository heads to use (optional)
  269. :return: A graph walker object
  270. """
  271. if heads is None:
  272. heads = self.refs.as_dict(b'refs/heads').values()
  273. return ObjectStoreGraphWalker(heads, self.get_parents)
  274. def get_refs(self):
  275. """Get dictionary with all refs.
  276. :return: A ``dict`` mapping ref names to SHA1s
  277. """
  278. return self.refs.as_dict()
  279. def head(self):
  280. """Return the SHA1 pointed at by HEAD."""
  281. return self.refs[b'HEAD']
  282. def _get_object(self, sha, cls):
  283. assert len(sha) in (20, 40)
  284. ret = self.get_object(sha)
  285. if not isinstance(ret, cls):
  286. if cls is Commit:
  287. raise NotCommitError(ret)
  288. elif cls is Blob:
  289. raise NotBlobError(ret)
  290. elif cls is Tree:
  291. raise NotTreeError(ret)
  292. elif cls is Tag:
  293. raise NotTagError(ret)
  294. else:
  295. raise Exception("Type invalid: %r != %r" % (
  296. ret.type_name, cls.type_name))
  297. return ret
  298. def get_object(self, sha):
  299. """Retrieve the object with the specified SHA.
  300. :param sha: SHA to retrieve
  301. :return: A ShaFile object
  302. :raise KeyError: when the object can not be found
  303. """
  304. return self.object_store[sha]
  305. def get_parents(self, sha, commit=None):
  306. """Retrieve the parents of a specific commit.
  307. If the specific commit is a graftpoint, the graft parents
  308. will be returned instead.
  309. :param sha: SHA of the commit for which to retrieve the parents
  310. :param commit: Optional commit matching the sha
  311. :return: List of parents
  312. """
  313. try:
  314. return self._graftpoints[sha]
  315. except KeyError:
  316. if commit is None:
  317. commit = self[sha]
  318. return commit.parents
  319. def get_config(self):
  320. """Retrieve the config object.
  321. :return: `ConfigFile` object for the ``.git/config`` file.
  322. """
  323. raise NotImplementedError(self.get_config)
  324. def get_description(self):
  325. """Retrieve the description for this repository.
  326. :return: String with the description of the repository
  327. as set by the user.
  328. """
  329. raise NotImplementedError(self.get_description)
  330. def set_description(self, description):
  331. """Set the description for this repository.
  332. :param description: Text to set as description for this repository.
  333. """
  334. raise NotImplementedError(self.set_description)
  335. def get_config_stack(self):
  336. """Return a config stack for this repository.
  337. This stack accesses the configuration for both this repository
  338. itself (.git/config) and the global configuration, which usually
  339. lives in ~/.gitconfig.
  340. :return: `Config` instance for this repository
  341. """
  342. from dulwich.config import StackedConfig
  343. backends = [self.get_config()] + StackedConfig.default_backends()
  344. return StackedConfig(backends, writable=backends[0])
  345. def get_peeled(self, ref):
  346. """Get the peeled value of a ref.
  347. :param ref: The refname to peel.
  348. :return: The fully-peeled SHA1 of a tag object, after peeling all
  349. intermediate tags; if the original ref does not point to a tag,
  350. this will equal the original SHA1.
  351. """
  352. cached = self.refs.get_peeled(ref)
  353. if cached is not None:
  354. return cached
  355. return self.object_store.peel_sha(self.refs[ref]).id
  356. def get_walker(self, include=None, *args, **kwargs):
  357. """Obtain a walker for this repository.
  358. :param include: Iterable of SHAs of commits to include along with their
  359. ancestors. Defaults to [HEAD]
  360. :param exclude: Iterable of SHAs of commits to exclude along with their
  361. ancestors, overriding includes.
  362. :param order: ORDER_* constant specifying the order of results.
  363. Anything other than ORDER_DATE may result in O(n) memory usage.
  364. :param reverse: If True, reverse the order of output, requiring O(n)
  365. memory.
  366. :param max_entries: The maximum number of entries to yield, or None for
  367. no limit.
  368. :param paths: Iterable of file or subtree paths to show entries for.
  369. :param rename_detector: diff.RenameDetector object for detecting
  370. renames.
  371. :param follow: If True, follow path across renames/copies. Forces a
  372. default rename_detector.
  373. :param since: Timestamp to list commits after.
  374. :param until: Timestamp to list commits before.
  375. :param queue_cls: A class to use for a queue of commits, supporting the
  376. iterator protocol. The constructor takes a single argument, the
  377. Walker.
  378. :return: A `Walker` object
  379. """
  380. from dulwich.walk import Walker
  381. if include is None:
  382. include = [self.head()]
  383. if isinstance(include, str):
  384. include = [include]
  385. kwargs['get_parents'] = lambda commit: self.get_parents(
  386. commit.id, commit)
  387. return Walker(self.object_store, include, *args, **kwargs)
  388. def __getitem__(self, name):
  389. """Retrieve a Git object by SHA1 or ref.
  390. :param name: A Git object SHA1 or a ref name
  391. :return: A `ShaFile` object, such as a Commit or Blob
  392. :raise KeyError: when the specified ref or object does not exist
  393. """
  394. if not isinstance(name, bytes):
  395. raise TypeError("'name' must be bytestring, not %.80s" %
  396. type(name).__name__)
  397. if len(name) in (20, 40):
  398. try:
  399. return self.object_store[name]
  400. except (KeyError, ValueError):
  401. pass
  402. try:
  403. return self.object_store[self.refs[name]]
  404. except RefFormatError:
  405. raise KeyError(name)
  406. def __contains__(self, name):
  407. """Check if a specific Git object or ref is present.
  408. :param name: Git object SHA1 or ref name
  409. """
  410. if len(name) in (20, 40):
  411. return name in self.object_store or name in self.refs
  412. else:
  413. return name in self.refs
  414. def __setitem__(self, name, value):
  415. """Set a ref.
  416. :param name: ref name
  417. :param value: Ref value - either a ShaFile object, or a hex sha
  418. """
  419. if name.startswith(b"refs/") or name == b'HEAD':
  420. if isinstance(value, ShaFile):
  421. self.refs[name] = value.id
  422. elif isinstance(value, bytes):
  423. self.refs[name] = value
  424. else:
  425. raise TypeError(value)
  426. else:
  427. raise ValueError(name)
  428. def __delitem__(self, name):
  429. """Remove a ref.
  430. :param name: Name of the ref to remove
  431. """
  432. if name.startswith(b"refs/") or name == b"HEAD":
  433. del self.refs[name]
  434. else:
  435. raise ValueError(name)
  436. def _get_user_identity(self):
  437. """Determine the identity to use for new commits.
  438. """
  439. user = os.environ.get("GIT_COMMITTER_NAME")
  440. email = os.environ.get("GIT_COMMITTER_EMAIL")
  441. config = self.get_config_stack()
  442. if user is None:
  443. try:
  444. user = config.get(("user", ), "name")
  445. except KeyError:
  446. user = None
  447. if email is None:
  448. try:
  449. email = config.get(("user", ), "email")
  450. except KeyError:
  451. email = None
  452. if user is None:
  453. import getpass
  454. user = getpass.getuser().encode(sys.getdefaultencoding())
  455. if email is None:
  456. import getpass
  457. import socket
  458. email = ("{}@{}".format(getpass.getuser(), socket.gethostname())
  459. .encode(sys.getdefaultencoding()))
  460. return (user + b" <" + email + b">")
  461. def _add_graftpoints(self, updated_graftpoints):
  462. """Add or modify graftpoints
  463. :param updated_graftpoints: Dict of commit shas to list of parent shas
  464. """
  465. # Simple validation
  466. for commit, parents in updated_graftpoints.items():
  467. for sha in [commit] + parents:
  468. check_hexsha(sha, 'Invalid graftpoint')
  469. self._graftpoints.update(updated_graftpoints)
  470. def _remove_graftpoints(self, to_remove=[]):
  471. """Remove graftpoints
  472. :param to_remove: List of commit shas
  473. """
  474. for sha in to_remove:
  475. del self._graftpoints[sha]
  476. def do_commit(self, message=None, committer=None,
  477. author=None, commit_timestamp=None,
  478. commit_timezone=None, author_timestamp=None,
  479. author_timezone=None, tree=None, encoding=None,
  480. ref=b'HEAD', merge_heads=None):
  481. """Create a new commit.
  482. :param message: Commit message
  483. :param committer: Committer fullname
  484. :param author: Author fullname (defaults to committer)
  485. :param commit_timestamp: Commit timestamp (defaults to now)
  486. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  487. :param author_timestamp: Author timestamp (defaults to commit
  488. timestamp)
  489. :param author_timezone: Author timestamp timezone
  490. (defaults to commit timestamp timezone)
  491. :param tree: SHA1 of the tree root to use (if not specified the
  492. current index will be committed).
  493. :param encoding: Encoding
  494. :param ref: Optional ref to commit to (defaults to current branch)
  495. :param merge_heads: Merge heads (defaults to .git/MERGE_HEADS)
  496. :return: New commit SHA1
  497. """
  498. import time
  499. c = Commit()
  500. if tree is None:
  501. index = self.open_index()
  502. c.tree = index.commit(self.object_store)
  503. else:
  504. if len(tree) != 40:
  505. raise ValueError("tree must be a 40-byte hex sha string")
  506. c.tree = tree
  507. try:
  508. self.hooks['pre-commit'].execute()
  509. except HookError as e:
  510. raise CommitError(e)
  511. except KeyError: # no hook defined, silent fallthrough
  512. pass
  513. if merge_heads is None:
  514. # FIXME: Read merge heads from .git/MERGE_HEADS
  515. merge_heads = []
  516. if committer is None:
  517. committer = self._get_user_identity()
  518. check_user_identity(committer)
  519. c.committer = committer
  520. if commit_timestamp is None:
  521. # FIXME: Support GIT_COMMITTER_DATE environment variable
  522. commit_timestamp = time.time()
  523. c.commit_time = int(commit_timestamp)
  524. if commit_timezone is None:
  525. # FIXME: Use current user timezone rather than UTC
  526. commit_timezone = 0
  527. c.commit_timezone = commit_timezone
  528. if author is None:
  529. # FIXME: Support GIT_AUTHOR_NAME/GIT_AUTHOR_EMAIL environment
  530. # variables
  531. author = committer
  532. c.author = author
  533. check_user_identity(author)
  534. if author_timestamp is None:
  535. # FIXME: Support GIT_AUTHOR_DATE environment variable
  536. author_timestamp = commit_timestamp
  537. c.author_time = int(author_timestamp)
  538. if author_timezone is None:
  539. author_timezone = commit_timezone
  540. c.author_timezone = author_timezone
  541. if encoding is not None:
  542. c.encoding = encoding
  543. if message is None:
  544. # FIXME: Try to read commit message from .git/MERGE_MSG
  545. raise ValueError("No commit message specified")
  546. try:
  547. c.message = self.hooks['commit-msg'].execute(message)
  548. if c.message is None:
  549. c.message = message
  550. except HookError as e:
  551. raise CommitError(e)
  552. except KeyError: # no hook defined, message not modified
  553. c.message = message
  554. if ref is None:
  555. # Create a dangling commit
  556. c.parents = merge_heads
  557. self.object_store.add_object(c)
  558. else:
  559. try:
  560. old_head = self.refs[ref]
  561. c.parents = [old_head] + merge_heads
  562. self.object_store.add_object(c)
  563. ok = self.refs.set_if_equals(
  564. ref, old_head, c.id, message=b"commit: " + message,
  565. committer=committer, timestamp=commit_timestamp,
  566. timezone=commit_timezone)
  567. except KeyError:
  568. c.parents = merge_heads
  569. self.object_store.add_object(c)
  570. ok = self.refs.add_if_new(
  571. ref, c.id, message=b"commit: " + message,
  572. committer=committer, timestamp=commit_timestamp,
  573. timezone=commit_timezone)
  574. if not ok:
  575. # Fail if the atomic compare-and-swap failed, leaving the
  576. # commit and all its objects as garbage.
  577. raise CommitError("%s changed during commit" % (ref,))
  578. try:
  579. self.hooks['post-commit'].execute()
  580. except HookError as e: # silent failure
  581. warnings.warn("post-commit hook failed: %s" % e, UserWarning)
  582. except KeyError: # no hook defined, silent fallthrough
  583. pass
  584. return c.id
  585. def read_gitfile(f):
  586. """Read a ``.git`` file.
  587. The first line of the file should start with "gitdir: "
  588. :param f: File-like object to read from
  589. :return: A path
  590. """
  591. cs = f.read()
  592. if not cs.startswith("gitdir: "):
  593. raise ValueError("Expected file to start with 'gitdir: '")
  594. return cs[len("gitdir: "):].rstrip("\n")
  595. class Repo(BaseRepo):
  596. """A git repository backed by local disk.
  597. To open an existing repository, call the contructor with
  598. the path of the repository.
  599. To create a new repository, use the Repo.init class method.
  600. """
  601. def __init__(self, root):
  602. hidden_path = os.path.join(root, CONTROLDIR)
  603. if os.path.isdir(os.path.join(hidden_path, OBJECTDIR)):
  604. self.bare = False
  605. self._controldir = hidden_path
  606. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  607. os.path.isdir(os.path.join(root, REFSDIR))):
  608. self.bare = True
  609. self._controldir = root
  610. elif os.path.isfile(hidden_path):
  611. self.bare = False
  612. with open(hidden_path, 'r') as f:
  613. path = read_gitfile(f)
  614. self.bare = False
  615. self._controldir = os.path.join(root, path)
  616. else:
  617. raise NotGitRepository(
  618. "No git repository was found at %(path)s" % dict(path=root)
  619. )
  620. commondir = self.get_named_file(COMMONDIR)
  621. if commondir is not None:
  622. with commondir:
  623. self._commondir = os.path.join(
  624. self.controldir(),
  625. commondir.read().rstrip(b"\r\n").decode(
  626. sys.getfilesystemencoding()))
  627. else:
  628. self._commondir = self._controldir
  629. self.path = root
  630. object_store = DiskObjectStore(
  631. os.path.join(self.commondir(), OBJECTDIR))
  632. refs = DiskRefsContainer(self.commondir(), self._controldir,
  633. logger=self._write_reflog)
  634. BaseRepo.__init__(self, object_store, refs)
  635. self._graftpoints = {}
  636. graft_file = self.get_named_file(os.path.join("info", "grafts"),
  637. basedir=self.commondir())
  638. if graft_file:
  639. with graft_file:
  640. self._graftpoints.update(parse_graftpoints(graft_file))
  641. graft_file = self.get_named_file("shallow",
  642. basedir=self.commondir())
  643. if graft_file:
  644. with graft_file:
  645. self._graftpoints.update(parse_graftpoints(graft_file))
  646. self.hooks['pre-commit'] = PreCommitShellHook(self.controldir())
  647. self.hooks['commit-msg'] = CommitMsgShellHook(self.controldir())
  648. self.hooks['post-commit'] = PostCommitShellHook(self.controldir())
  649. def _write_reflog(self, ref, old_sha, new_sha, committer, timestamp,
  650. timezone, message):
  651. from .reflog import format_reflog_line
  652. path = os.path.join(
  653. self.controldir(), 'logs',
  654. ref.decode(sys.getfilesystemencoding()))
  655. try:
  656. os.makedirs(os.path.dirname(path))
  657. except OSError as e:
  658. if e.errno != errno.EEXIST:
  659. raise
  660. if committer is None:
  661. committer = self._get_user_identity()
  662. check_user_identity(committer)
  663. if timestamp is None:
  664. timestamp = int(time.time())
  665. if timezone is None:
  666. timezone = 0 # FIXME
  667. with open(path, 'ab') as f:
  668. f.write(format_reflog_line(old_sha, new_sha, committer,
  669. timestamp, timezone, message) + b'\n')
  670. @classmethod
  671. def discover(cls, start='.'):
  672. """Iterate parent directories to discover a repository
  673. Return a Repo object for the first parent directory that looks like a
  674. Git repository.
  675. :param start: The directory to start discovery from (defaults to '.')
  676. """
  677. remaining = True
  678. path = os.path.abspath(start)
  679. while remaining:
  680. try:
  681. return cls(path)
  682. except NotGitRepository:
  683. path, remaining = os.path.split(path)
  684. raise NotGitRepository(
  685. "No git repository was found at %(path)s" % dict(path=start)
  686. )
  687. def controldir(self):
  688. """Return the path of the control directory."""
  689. return self._controldir
  690. def commondir(self):
  691. """Return the path of the common directory.
  692. For a main working tree, it is identical to controldir().
  693. For a linked working tree, it is the control directory of the
  694. main working tree."""
  695. return self._commondir
  696. def _determine_file_mode(self):
  697. """Probe the file-system to determine whether permissions can be trusted.
  698. :return: True if permissions can be trusted, False otherwise.
  699. """
  700. fname = os.path.join(self.path, '.probe-permissions')
  701. with open(fname, 'w') as f:
  702. f.write('')
  703. st1 = os.lstat(fname)
  704. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  705. st2 = os.lstat(fname)
  706. os.unlink(fname)
  707. mode_differs = st1.st_mode != st2.st_mode
  708. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  709. return mode_differs and st2_has_exec
  710. def _put_named_file(self, path, contents):
  711. """Write a file to the control dir with the given name and contents.
  712. :param path: The path to the file, relative to the control dir.
  713. :param contents: A string to write to the file.
  714. """
  715. path = path.lstrip(os.path.sep)
  716. with GitFile(os.path.join(self.controldir(), path), 'wb') as f:
  717. f.write(contents)
  718. def get_named_file(self, path, basedir=None):
  719. """Get a file from the control dir with a specific name.
  720. Although the filename should be interpreted as a filename relative to
  721. the control dir in a disk-based Repo, the object returned need not be
  722. pointing to a file in that location.
  723. :param path: The path to the file, relative to the control dir.
  724. :param basedir: Optional argument that specifies an alternative to the
  725. control dir.
  726. :return: An open file object, or None if the file does not exist.
  727. """
  728. # TODO(dborowitz): sanitize filenames, since this is used directly by
  729. # the dumb web serving code.
  730. if basedir is None:
  731. basedir = self.controldir()
  732. path = path.lstrip(os.path.sep)
  733. try:
  734. return open(os.path.join(basedir, path), 'rb')
  735. except (IOError, OSError) as e:
  736. if e.errno == errno.ENOENT:
  737. return None
  738. raise
  739. def index_path(self):
  740. """Return path to the index file."""
  741. return os.path.join(self.controldir(), INDEX_FILENAME)
  742. def open_index(self):
  743. """Open the index for this repository.
  744. :raise NoIndexPresent: If no index is present
  745. :return: The matching `Index`
  746. """
  747. from dulwich.index import Index
  748. if not self.has_index():
  749. raise NoIndexPresent()
  750. return Index(self.index_path())
  751. def has_index(self):
  752. """Check if an index is present."""
  753. # Bare repos must never have index files; non-bare repos may have a
  754. # missing index file, which is treated as empty.
  755. return not self.bare
  756. def stage(self, fs_paths):
  757. """Stage a set of paths.
  758. :param fs_paths: List of paths, relative to the repository path
  759. """
  760. root_path_bytes = self.path.encode(sys.getfilesystemencoding())
  761. if not isinstance(fs_paths, list):
  762. fs_paths = [fs_paths]
  763. from dulwich.index import (
  764. blob_from_path_and_stat,
  765. index_entry_from_stat,
  766. _fs_to_tree_path,
  767. )
  768. index = self.open_index()
  769. for fs_path in fs_paths:
  770. if not isinstance(fs_path, bytes):
  771. fs_path = fs_path.encode(sys.getfilesystemencoding())
  772. if os.path.isabs(fs_path):
  773. raise ValueError(
  774. "path %r should be relative to "
  775. "repository root, not absolute" % fs_path)
  776. tree_path = _fs_to_tree_path(fs_path)
  777. full_path = os.path.join(root_path_bytes, fs_path)
  778. try:
  779. st = os.lstat(full_path)
  780. except OSError:
  781. # File no longer exists
  782. try:
  783. del index[tree_path]
  784. except KeyError:
  785. pass # already removed
  786. else:
  787. if not stat.S_ISDIR(st.st_mode):
  788. blob = blob_from_path_and_stat(full_path, st)
  789. self.object_store.add_object(blob)
  790. index[tree_path] = index_entry_from_stat(st, blob.id, 0)
  791. else:
  792. try:
  793. del index[tree_path]
  794. except KeyError:
  795. pass
  796. index.write()
  797. def clone(self, target_path, mkdir=True, bare=False,
  798. origin=b"origin"):
  799. """Clone this repository.
  800. :param target_path: Target path
  801. :param mkdir: Create the target directory
  802. :param bare: Whether to create a bare repository
  803. :param origin: Base name for refs in target repository
  804. cloned from this repository
  805. :return: Created repository as `Repo`
  806. """
  807. if not bare:
  808. target = self.init(target_path, mkdir=mkdir)
  809. else:
  810. target = self.init_bare(target_path, mkdir=mkdir)
  811. self.fetch(target)
  812. encoded_path = self.path
  813. if not isinstance(encoded_path, bytes):
  814. encoded_path = encoded_path.encode(sys.getfilesystemencoding())
  815. ref_message = b"clone: from " + encoded_path
  816. target.refs.import_refs(
  817. b'refs/remotes/' + origin, self.refs.as_dict(b'refs/heads'),
  818. message=ref_message)
  819. target.refs.import_refs(
  820. b'refs/tags', self.refs.as_dict(b'refs/tags'),
  821. message=ref_message)
  822. try:
  823. target.refs.add_if_new(
  824. DEFAULT_REF, self.refs[DEFAULT_REF],
  825. message=ref_message)
  826. except KeyError:
  827. pass
  828. target_config = target.get_config()
  829. target_config.set(('remote', 'origin'), 'url', encoded_path)
  830. target_config.set(('remote', 'origin'), 'fetch',
  831. '+refs/heads/*:refs/remotes/origin/*')
  832. target_config.write_to_path()
  833. # Update target head
  834. head_chain, head_sha = self.refs.follow(b'HEAD')
  835. if head_chain and head_sha is not None:
  836. target.refs.set_symbolic_ref(b'HEAD', head_chain[-1],
  837. message=ref_message)
  838. target[b'HEAD'] = head_sha
  839. if not bare:
  840. # Checkout HEAD to target dir
  841. target.reset_index()
  842. return target
  843. def reset_index(self, tree=None):
  844. """Reset the index back to a specific tree.
  845. :param tree: Tree SHA to reset to, None for current HEAD tree.
  846. """
  847. from dulwich.index import (
  848. build_index_from_tree,
  849. validate_path_element_default,
  850. validate_path_element_ntfs,
  851. )
  852. if tree is None:
  853. tree = self[b'HEAD'].tree
  854. config = self.get_config()
  855. honor_filemode = config.get_boolean(
  856. b'core', b'filemode', os.name != "nt")
  857. if config.get_boolean(b'core', b'core.protectNTFS', os.name == "nt"):
  858. validate_path_element = validate_path_element_ntfs
  859. else:
  860. validate_path_element = validate_path_element_default
  861. return build_index_from_tree(
  862. self.path, self.index_path(), self.object_store, tree,
  863. honor_filemode=honor_filemode,
  864. validate_path_element=validate_path_element)
  865. def get_config(self):
  866. """Retrieve the config object.
  867. :return: `ConfigFile` object for the ``.git/config`` file.
  868. """
  869. from dulwich.config import ConfigFile
  870. path = os.path.join(self._controldir, 'config')
  871. try:
  872. return ConfigFile.from_path(path)
  873. except (IOError, OSError) as e:
  874. if e.errno != errno.ENOENT:
  875. raise
  876. ret = ConfigFile()
  877. ret.path = path
  878. return ret
  879. def get_description(self):
  880. """Retrieve the description of this repository.
  881. :return: A string describing the repository or None.
  882. """
  883. path = os.path.join(self._controldir, 'description')
  884. try:
  885. with GitFile(path, 'rb') as f:
  886. return f.read()
  887. except (IOError, OSError) as e:
  888. if e.errno != errno.ENOENT:
  889. raise
  890. return None
  891. def __repr__(self):
  892. return "<Repo at %r>" % self.path
  893. def set_description(self, description):
  894. """Set the description for this repository.
  895. :param description: Text to set as description for this repository.
  896. """
  897. self._put_named_file('description', description)
  898. @classmethod
  899. def _init_maybe_bare(cls, path, bare):
  900. for d in BASE_DIRECTORIES:
  901. os.mkdir(os.path.join(path, *d))
  902. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  903. ret = cls(path)
  904. ret.refs.set_symbolic_ref(b'HEAD', DEFAULT_REF)
  905. ret._init_files(bare)
  906. return ret
  907. @classmethod
  908. def init(cls, path, mkdir=False):
  909. """Create a new repository.
  910. :param path: Path in which to create the repository
  911. :param mkdir: Whether to create the directory
  912. :return: `Repo` instance
  913. """
  914. if mkdir:
  915. os.mkdir(path)
  916. controldir = os.path.join(path, CONTROLDIR)
  917. os.mkdir(controldir)
  918. cls._init_maybe_bare(controldir, False)
  919. return cls(path)
  920. @classmethod
  921. def _init_new_working_directory(cls, path, main_repo, identifier=None,
  922. mkdir=False):
  923. """Create a new working directory linked to a repository.
  924. :param path: Path in which to create the working tree.
  925. :param main_repo: Main repository to reference
  926. :param identifier: Worktree identifier
  927. :param mkdir: Whether to create the directory
  928. :return: `Repo` instance
  929. """
  930. if mkdir:
  931. os.mkdir(path)
  932. if identifier is None:
  933. identifier = os.path.basename(path)
  934. main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES)
  935. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  936. gitdirfile = os.path.join(path, CONTROLDIR)
  937. with open(gitdirfile, 'wb') as f:
  938. f.write(b'gitdir: ' +
  939. worktree_controldir.encode(sys.getfilesystemencoding()) +
  940. b'\n')
  941. try:
  942. os.mkdir(main_worktreesdir)
  943. except OSError as e:
  944. if e.errno != errno.EEXIST:
  945. raise
  946. try:
  947. os.mkdir(worktree_controldir)
  948. except OSError as e:
  949. if e.errno != errno.EEXIST:
  950. raise
  951. with open(os.path.join(worktree_controldir, GITDIR), 'wb') as f:
  952. f.write(gitdirfile.encode(sys.getfilesystemencoding()) + b'\n')
  953. with open(os.path.join(worktree_controldir, COMMONDIR), 'wb') as f:
  954. f.write(b'../..\n')
  955. with open(os.path.join(worktree_controldir, 'HEAD'), 'wb') as f:
  956. f.write(main_repo.head() + b'\n')
  957. r = cls(path)
  958. r.reset_index()
  959. return r
  960. @classmethod
  961. def init_bare(cls, path, mkdir=False):
  962. """Create a new bare repository.
  963. ``path`` should already exist and be an empty directory.
  964. :param path: Path to create bare repository in
  965. :return: a `Repo` instance
  966. """
  967. if mkdir:
  968. os.mkdir(path)
  969. return cls._init_maybe_bare(path, True)
  970. create = init_bare
  971. def close(self):
  972. """Close any files opened by this repository."""
  973. self.object_store.close()
  974. def __enter__(self):
  975. return self
  976. def __exit__(self, exc_type, exc_val, exc_tb):
  977. self.close()
  978. class MemoryRepo(BaseRepo):
  979. """Repo that stores refs, objects, and named files in memory.
  980. MemoryRepos are always bare: they have no working tree and no index, since
  981. those have a stronger dependency on the filesystem.
  982. """
  983. def __init__(self):
  984. from dulwich.config import ConfigFile
  985. self._reflog = []
  986. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  987. BaseRepo.__init__(self, MemoryObjectStore(), refs_container)
  988. self._named_files = {}
  989. self.bare = True
  990. self._config = ConfigFile()
  991. self._description = None
  992. def _append_reflog(self, *args):
  993. self._reflog.append(args)
  994. def set_description(self, description):
  995. self._description = description
  996. def get_description(self):
  997. return self._description
  998. def _determine_file_mode(self):
  999. """Probe the file-system to determine whether permissions can be trusted.
  1000. :return: True if permissions can be trusted, False otherwise.
  1001. """
  1002. return sys.platform != 'win32'
  1003. def _put_named_file(self, path, contents):
  1004. """Write a file to the control dir with the given name and contents.
  1005. :param path: The path to the file, relative to the control dir.
  1006. :param contents: A string to write to the file.
  1007. """
  1008. self._named_files[path] = contents
  1009. def get_named_file(self, path):
  1010. """Get a file from the control dir with a specific name.
  1011. Although the filename should be interpreted as a filename relative to
  1012. the control dir in a disk-baked Repo, the object returned need not be
  1013. pointing to a file in that location.
  1014. :param path: The path to the file, relative to the control dir.
  1015. :return: An open file object, or None if the file does not exist.
  1016. """
  1017. contents = self._named_files.get(path, None)
  1018. if contents is None:
  1019. return None
  1020. return BytesIO(contents)
  1021. def open_index(self):
  1022. """Fail to open index for this repo, since it is bare.
  1023. :raise NoIndexPresent: Raised when no index is present
  1024. """
  1025. raise NoIndexPresent()
  1026. def get_config(self):
  1027. """Retrieve the config object.
  1028. :return: `ConfigFile` object.
  1029. """
  1030. return self._config
  1031. @classmethod
  1032. def init_bare(cls, objects, refs):
  1033. """Create a new bare repository in memory.
  1034. :param objects: Objects for the new repository,
  1035. as iterable
  1036. :param refs: Refs as dictionary, mapping names
  1037. to object SHA1s
  1038. """
  1039. ret = cls()
  1040. for obj in objects:
  1041. ret.object_store.add_object(obj)
  1042. for refname, sha in refs.items():
  1043. ret.refs.add_if_new(refname, sha)
  1044. ret._init_files(bare=True)
  1045. return ret