repo.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  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@jelmer.uk>
  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 os
  28. import sys
  29. import stat
  30. import time
  31. from typing import Optional, Tuple, TYPE_CHECKING, List, Dict, Union, Iterable
  32. if TYPE_CHECKING:
  33. # There are no circular imports here, but we try to defer imports as long
  34. # as possible to reduce start-up time for anything that doesn't need
  35. # these imports.
  36. from dulwich.config import StackedConfig, ConfigFile
  37. from dulwich.index import Index
  38. from dulwich.errors import (
  39. NoIndexPresent,
  40. NotBlobError,
  41. NotCommitError,
  42. NotGitRepository,
  43. NotTreeError,
  44. NotTagError,
  45. CommitError,
  46. RefFormatError,
  47. HookError,
  48. )
  49. from dulwich.file import (
  50. GitFile,
  51. )
  52. from dulwich.object_store import (
  53. DiskObjectStore,
  54. MemoryObjectStore,
  55. BaseObjectStore,
  56. ObjectStoreGraphWalker,
  57. )
  58. from dulwich.objects import (
  59. check_hexsha,
  60. valid_hexsha,
  61. Blob,
  62. Commit,
  63. ShaFile,
  64. Tag,
  65. Tree,
  66. )
  67. from dulwich.pack import (
  68. pack_objects_to_data,
  69. )
  70. from dulwich.hooks import (
  71. Hook,
  72. PreCommitShellHook,
  73. PostCommitShellHook,
  74. CommitMsgShellHook,
  75. PostReceiveShellHook,
  76. )
  77. from dulwich.line_ending import BlobNormalizer, TreeBlobNormalizer
  78. from dulwich.refs import ( # noqa: F401
  79. ANNOTATED_TAG_SUFFIX,
  80. check_ref_format,
  81. RefsContainer,
  82. DictRefsContainer,
  83. InfoRefsContainer,
  84. DiskRefsContainer,
  85. read_packed_refs,
  86. read_packed_refs_with_peeled,
  87. write_packed_refs,
  88. SYMREF,
  89. )
  90. import warnings
  91. CONTROLDIR = ".git"
  92. OBJECTDIR = "objects"
  93. REFSDIR = "refs"
  94. REFSDIR_TAGS = "tags"
  95. REFSDIR_HEADS = "heads"
  96. INDEX_FILENAME = "index"
  97. COMMONDIR = "commondir"
  98. GITDIR = "gitdir"
  99. WORKTREES = "worktrees"
  100. BASE_DIRECTORIES = [
  101. ["branches"],
  102. [REFSDIR],
  103. [REFSDIR, REFSDIR_TAGS],
  104. [REFSDIR, REFSDIR_HEADS],
  105. ["hooks"],
  106. ["info"],
  107. ]
  108. DEFAULT_REF = b"refs/heads/master"
  109. class InvalidUserIdentity(Exception):
  110. """User identity is not of the format 'user <email>'"""
  111. def __init__(self, identity):
  112. self.identity = identity
  113. def _get_default_identity() -> Tuple[str, str]:
  114. import getpass
  115. import socket
  116. username = getpass.getuser()
  117. try:
  118. import pwd
  119. except ImportError:
  120. fullname = None
  121. else:
  122. try:
  123. gecos = pwd.getpwnam(username).pw_gecos
  124. except KeyError:
  125. fullname = None
  126. else:
  127. fullname = gecos.split(",")[0]
  128. if not fullname:
  129. fullname = username
  130. email = os.environ.get("EMAIL")
  131. if email is None:
  132. email = "{}@{}".format(username, socket.gethostname())
  133. return (fullname, email)
  134. def get_user_identity(config: "StackedConfig", kind: Optional[str] = None) -> bytes:
  135. """Determine the identity to use for new commits.
  136. If kind is set, this first checks
  137. GIT_${KIND}_NAME and GIT_${KIND}_EMAIL.
  138. If those variables are not set, then it will fall back
  139. to reading the user.name and user.email settings from
  140. the specified configuration.
  141. If that also fails, then it will fall back to using
  142. the current users' identity as obtained from the host
  143. system (e.g. the gecos field, $EMAIL, $USER@$(hostname -f).
  144. Args:
  145. kind: Optional kind to return identity for,
  146. usually either "AUTHOR" or "COMMITTER".
  147. Returns:
  148. A user identity
  149. """
  150. user = None # type: Optional[bytes]
  151. email = None # type: Optional[bytes]
  152. if kind:
  153. user_uc = os.environ.get("GIT_" + kind + "_NAME")
  154. if user_uc is not None:
  155. user = user_uc.encode("utf-8")
  156. email_uc = os.environ.get("GIT_" + kind + "_EMAIL")
  157. if email_uc is not None:
  158. email = email_uc.encode("utf-8")
  159. if user is None:
  160. try:
  161. user = config.get(("user",), "name")
  162. except KeyError:
  163. user = None
  164. if email is None:
  165. try:
  166. email = config.get(("user",), "email")
  167. except KeyError:
  168. email = None
  169. default_user, default_email = _get_default_identity()
  170. if user is None:
  171. user = default_user.encode("utf-8")
  172. if email is None:
  173. email = default_email.encode("utf-8")
  174. if email.startswith(b"<") and email.endswith(b">"):
  175. email = email[1:-1]
  176. return user + b" <" + email + b">"
  177. def check_user_identity(identity):
  178. """Verify that a user identity is formatted correctly.
  179. Args:
  180. identity: User identity bytestring
  181. Raises:
  182. InvalidUserIdentity: Raised when identity is invalid
  183. """
  184. try:
  185. fst, snd = identity.split(b" <", 1)
  186. except ValueError:
  187. raise InvalidUserIdentity(identity)
  188. if b">" not in snd:
  189. raise InvalidUserIdentity(identity)
  190. def parse_graftpoints(
  191. graftpoints: Iterable[bytes],
  192. ) -> Dict[bytes, List[bytes]]:
  193. """Convert a list of graftpoints into a dict
  194. Args:
  195. graftpoints: Iterator of graftpoint lines
  196. Each line is formatted as:
  197. <commit sha1> <parent sha1> [<parent sha1>]*
  198. Resulting dictionary is:
  199. <commit sha1>: [<parent sha1>*]
  200. https://git.wiki.kernel.org/index.php/GraftPoint
  201. """
  202. grafts = {}
  203. for line in graftpoints:
  204. raw_graft = line.split(None, 1)
  205. commit = raw_graft[0]
  206. if len(raw_graft) == 2:
  207. parents = raw_graft[1].split()
  208. else:
  209. parents = []
  210. for sha in [commit] + parents:
  211. check_hexsha(sha, "Invalid graftpoint")
  212. grafts[commit] = parents
  213. return grafts
  214. def serialize_graftpoints(graftpoints: Dict[bytes, List[bytes]]) -> bytes:
  215. """Convert a dictionary of grafts into string
  216. The graft dictionary is:
  217. <commit sha1>: [<parent sha1>*]
  218. Each line is formatted as:
  219. <commit sha1> <parent sha1> [<parent sha1>]*
  220. https://git.wiki.kernel.org/index.php/GraftPoint
  221. """
  222. graft_lines = []
  223. for commit, parents in graftpoints.items():
  224. if parents:
  225. graft_lines.append(commit + b" " + b" ".join(parents))
  226. else:
  227. graft_lines.append(commit)
  228. return b"\n".join(graft_lines)
  229. def _set_filesystem_hidden(path):
  230. """Mark path as to be hidden if supported by platform and filesystem.
  231. On win32 uses SetFileAttributesW api:
  232. <https://docs.microsoft.com/windows/desktop/api/fileapi/nf-fileapi-setfileattributesw>
  233. """
  234. if sys.platform == "win32":
  235. import ctypes
  236. from ctypes.wintypes import BOOL, DWORD, LPCWSTR
  237. FILE_ATTRIBUTE_HIDDEN = 2
  238. SetFileAttributesW = ctypes.WINFUNCTYPE(BOOL, LPCWSTR, DWORD)(
  239. ("SetFileAttributesW", ctypes.windll.kernel32)
  240. )
  241. if isinstance(path, bytes):
  242. path = os.fsdecode(path)
  243. if not SetFileAttributesW(path, FILE_ATTRIBUTE_HIDDEN):
  244. pass # Could raise or log `ctypes.WinError()` here
  245. # Could implement other platform specific filesytem hiding here
  246. class ParentsProvider(object):
  247. def __init__(self, store, grafts={}, shallows=[]):
  248. self.store = store
  249. self.grafts = grafts
  250. self.shallows = set(shallows)
  251. def get_parents(self, commit_id, commit=None):
  252. try:
  253. return self.grafts[commit_id]
  254. except KeyError:
  255. pass
  256. if commit_id in self.shallows:
  257. return []
  258. if commit is None:
  259. commit = self.store[commit_id]
  260. return commit.parents
  261. class BaseRepo(object):
  262. """Base class for a git repository.
  263. :ivar object_store: Dictionary-like object for accessing
  264. the objects
  265. :ivar refs: Dictionary-like object with the refs in this
  266. repository
  267. """
  268. def __init__(self, object_store: BaseObjectStore, refs: RefsContainer):
  269. """Open a repository.
  270. This shouldn't be called directly, but rather through one of the
  271. base classes, such as MemoryRepo or Repo.
  272. Args:
  273. object_store: Object store to use
  274. refs: Refs container to use
  275. """
  276. self.object_store = object_store
  277. self.refs = refs
  278. self._graftpoints = {} # type: Dict[bytes, List[bytes]]
  279. self.hooks = {} # type: Dict[str, Hook]
  280. def _determine_file_mode(self) -> bool:
  281. """Probe the file-system to determine whether permissions can be trusted.
  282. Returns: True if permissions can be trusted, False otherwise.
  283. """
  284. raise NotImplementedError(self._determine_file_mode)
  285. def _init_files(self, bare: bool) -> None:
  286. """Initialize a default set of named files."""
  287. from dulwich.config import ConfigFile
  288. self._put_named_file("description", b"Unnamed repository")
  289. f = BytesIO()
  290. cf = ConfigFile()
  291. cf.set("core", "repositoryformatversion", "0")
  292. if self._determine_file_mode():
  293. cf.set("core", "filemode", True)
  294. else:
  295. cf.set("core", "filemode", False)
  296. cf.set("core", "bare", bare)
  297. cf.set("core", "logallrefupdates", True)
  298. cf.write_to_file(f)
  299. self._put_named_file("config", f.getvalue())
  300. self._put_named_file(os.path.join("info", "exclude"), b"")
  301. def get_named_file(self, path):
  302. """Get a file from the control dir with a specific name.
  303. Although the filename should be interpreted as a filename relative to
  304. the control dir in a disk-based Repo, the object returned need not be
  305. pointing to a file in that location.
  306. Args:
  307. path: The path to the file, relative to the control dir.
  308. Returns: An open file object, or None if the file does not exist.
  309. """
  310. raise NotImplementedError(self.get_named_file)
  311. def _put_named_file(self, path, contents):
  312. """Write a file to the control dir with the given name and contents.
  313. Args:
  314. path: The path to the file, relative to the control dir.
  315. contents: A string to write to the file.
  316. """
  317. raise NotImplementedError(self._put_named_file)
  318. def _del_named_file(self, path):
  319. """Delete a file in the contrl directory with the given name."""
  320. raise NotImplementedError(self._del_named_file)
  321. def open_index(self):
  322. """Open the index for this repository.
  323. Raises:
  324. NoIndexPresent: If no index is present
  325. Returns: The matching `Index`
  326. """
  327. raise NotImplementedError(self.open_index)
  328. def fetch(self, target, determine_wants=None, progress=None, depth=None):
  329. """Fetch objects into another repository.
  330. Args:
  331. target: The target repository
  332. determine_wants: Optional function to determine what refs to
  333. fetch.
  334. progress: Optional progress function
  335. depth: Optional shallow fetch depth
  336. Returns: The local refs
  337. """
  338. if determine_wants is None:
  339. determine_wants = target.object_store.determine_wants_all
  340. count, pack_data = self.fetch_pack_data(
  341. determine_wants,
  342. target.get_graph_walker(),
  343. progress=progress,
  344. depth=depth,
  345. )
  346. target.object_store.add_pack_data(count, pack_data, progress)
  347. return self.get_refs()
  348. def fetch_pack_data(
  349. self,
  350. determine_wants,
  351. graph_walker,
  352. progress,
  353. get_tagged=None,
  354. depth=None,
  355. ):
  356. """Fetch the pack data required for a set of revisions.
  357. Args:
  358. determine_wants: Function that takes a dictionary with heads
  359. and returns the list of heads to fetch.
  360. graph_walker: Object that can iterate over the list of revisions
  361. to fetch and has an "ack" method that will be called to acknowledge
  362. that a revision is present.
  363. progress: Simple progress function that will be called with
  364. updated progress strings.
  365. get_tagged: Function that returns a dict of pointed-to sha ->
  366. tag sha for including tags.
  367. depth: Shallow fetch depth
  368. Returns: count and iterator over pack data
  369. """
  370. # TODO(jelmer): Fetch pack data directly, don't create objects first.
  371. objects = self.fetch_objects(
  372. determine_wants, graph_walker, progress, get_tagged, depth=depth
  373. )
  374. return pack_objects_to_data(objects)
  375. def fetch_objects(
  376. self,
  377. determine_wants,
  378. graph_walker,
  379. progress,
  380. get_tagged=None,
  381. depth=None,
  382. ):
  383. """Fetch the missing objects required for a set of revisions.
  384. Args:
  385. determine_wants: Function that takes a dictionary with heads
  386. and returns the list of heads to fetch.
  387. graph_walker: Object that can iterate over the list of revisions
  388. to fetch and has an "ack" method that will be called to acknowledge
  389. that a revision is present.
  390. progress: Simple progress function that will be called with
  391. updated progress strings.
  392. get_tagged: Function that returns a dict of pointed-to sha ->
  393. tag sha for including tags.
  394. depth: Shallow fetch depth
  395. Returns: iterator over objects, with __len__ implemented
  396. """
  397. if depth not in (None, 0):
  398. raise NotImplementedError("depth not supported yet")
  399. refs = {}
  400. for ref, sha in self.get_refs().items():
  401. try:
  402. obj = self.object_store[sha]
  403. except KeyError:
  404. warnings.warn(
  405. "ref %s points at non-present sha %s"
  406. % (ref.decode("utf-8", "replace"), sha.decode("ascii")),
  407. UserWarning,
  408. )
  409. continue
  410. else:
  411. if isinstance(obj, Tag):
  412. refs[ref + ANNOTATED_TAG_SUFFIX] = obj.object[1]
  413. refs[ref] = sha
  414. wants = determine_wants(refs)
  415. if not isinstance(wants, list):
  416. raise TypeError("determine_wants() did not return a list")
  417. shallows = getattr(graph_walker, "shallow", frozenset())
  418. unshallows = getattr(graph_walker, "unshallow", frozenset())
  419. if wants == []:
  420. # TODO(dborowitz): find a way to short-circuit that doesn't change
  421. # this interface.
  422. if shallows or unshallows:
  423. # Do not send a pack in shallow short-circuit path
  424. return None
  425. return []
  426. # If the graph walker is set up with an implementation that can
  427. # ACK/NAK to the wire, it will write data to the client through
  428. # this call as a side-effect.
  429. haves = self.object_store.find_common_revisions(graph_walker)
  430. # Deal with shallow requests separately because the haves do
  431. # not reflect what objects are missing
  432. if shallows or unshallows:
  433. # TODO: filter the haves commits from iter_shas. the specific
  434. # commits aren't missing.
  435. haves = []
  436. parents_provider = ParentsProvider(self.object_store, shallows=shallows)
  437. def get_parents(commit):
  438. return parents_provider.get_parents(commit.id, commit)
  439. return self.object_store.iter_shas(
  440. self.object_store.find_missing_objects(
  441. haves,
  442. wants,
  443. self.get_shallow(),
  444. progress,
  445. get_tagged,
  446. get_parents=get_parents,
  447. )
  448. )
  449. def generate_pack_data(self, have, want, progress=None, ofs_delta=None):
  450. """Generate pack data objects for a set of wants/haves.
  451. Args:
  452. have: List of SHA1s of objects that should not be sent
  453. want: List of SHA1s of objects that should be sent
  454. ofs_delta: Whether OFS deltas can be included
  455. progress: Optional progress reporting method
  456. """
  457. return self.object_store.generate_pack_data(
  458. have,
  459. want,
  460. shallow=self.get_shallow(),
  461. progress=progress,
  462. ofs_delta=ofs_delta,
  463. )
  464. def get_graph_walker(self, heads=None):
  465. """Retrieve a graph walker.
  466. A graph walker is used by a remote repository (or proxy)
  467. to find out which objects are present in this repository.
  468. Args:
  469. heads: Repository heads to use (optional)
  470. Returns: A graph walker object
  471. """
  472. if heads is None:
  473. heads = [
  474. sha
  475. for sha in self.refs.as_dict(b"refs/heads").values()
  476. if sha in self.object_store
  477. ]
  478. parents_provider = ParentsProvider(self.object_store)
  479. return ObjectStoreGraphWalker(
  480. heads, parents_provider.get_parents, shallow=self.get_shallow()
  481. )
  482. def get_refs(self) -> Dict[bytes, bytes]:
  483. """Get dictionary with all refs.
  484. Returns: A ``dict`` mapping ref names to SHA1s
  485. """
  486. return self.refs.as_dict()
  487. def head(self) -> bytes:
  488. """Return the SHA1 pointed at by HEAD."""
  489. return self.refs[b"HEAD"]
  490. def _get_object(self, sha, cls):
  491. assert len(sha) in (20, 40)
  492. ret = self.get_object(sha)
  493. if not isinstance(ret, cls):
  494. if cls is Commit:
  495. raise NotCommitError(ret)
  496. elif cls is Blob:
  497. raise NotBlobError(ret)
  498. elif cls is Tree:
  499. raise NotTreeError(ret)
  500. elif cls is Tag:
  501. raise NotTagError(ret)
  502. else:
  503. raise Exception(
  504. "Type invalid: %r != %r" % (ret.type_name, cls.type_name)
  505. )
  506. return ret
  507. def get_object(self, sha: bytes) -> ShaFile:
  508. """Retrieve the object with the specified SHA.
  509. Args:
  510. sha: SHA to retrieve
  511. Returns: A ShaFile object
  512. Raises:
  513. KeyError: when the object can not be found
  514. """
  515. return self.object_store[sha]
  516. def parents_provider(self):
  517. return ParentsProvider(
  518. self.object_store,
  519. grafts=self._graftpoints,
  520. shallows=self.get_shallow(),
  521. )
  522. def get_parents(self, sha: bytes, commit: Commit = None) -> List[bytes]:
  523. """Retrieve the parents of a specific commit.
  524. If the specific commit is a graftpoint, the graft parents
  525. will be returned instead.
  526. Args:
  527. sha: SHA of the commit for which to retrieve the parents
  528. commit: Optional commit matching the sha
  529. Returns: List of parents
  530. """
  531. return self.parents_provider().get_parents(sha, commit)
  532. def get_config(self):
  533. """Retrieve the config object.
  534. Returns: `ConfigFile` object for the ``.git/config`` file.
  535. """
  536. raise NotImplementedError(self.get_config)
  537. def get_description(self):
  538. """Retrieve the description for this repository.
  539. Returns: String with the description of the repository
  540. as set by the user.
  541. """
  542. raise NotImplementedError(self.get_description)
  543. def set_description(self, description):
  544. """Set the description for this repository.
  545. Args:
  546. description: Text to set as description for this repository.
  547. """
  548. raise NotImplementedError(self.set_description)
  549. def get_config_stack(self) -> "StackedConfig":
  550. """Return a config stack for this repository.
  551. This stack accesses the configuration for both this repository
  552. itself (.git/config) and the global configuration, which usually
  553. lives in ~/.gitconfig.
  554. Returns: `Config` instance for this repository
  555. """
  556. from dulwich.config import StackedConfig
  557. backends = [self.get_config()] + StackedConfig.default_backends()
  558. return StackedConfig(backends, writable=backends[0])
  559. def get_shallow(self):
  560. """Get the set of shallow commits.
  561. Returns: Set of shallow commits.
  562. """
  563. f = self.get_named_file("shallow")
  564. if f is None:
  565. return set()
  566. with f:
  567. return {line.strip() for line in f}
  568. def update_shallow(self, new_shallow, new_unshallow):
  569. """Update the list of shallow objects.
  570. Args:
  571. new_shallow: Newly shallow objects
  572. new_unshallow: Newly no longer shallow objects
  573. """
  574. shallow = self.get_shallow()
  575. if new_shallow:
  576. shallow.update(new_shallow)
  577. if new_unshallow:
  578. shallow.difference_update(new_unshallow)
  579. if shallow:
  580. self._put_named_file(
  581. "shallow", b"".join([sha + b"\n" for sha in shallow])
  582. )
  583. else:
  584. self._del_named_file("shallow")
  585. def get_peeled(self, ref):
  586. """Get the peeled value of a ref.
  587. Args:
  588. ref: The refname to peel.
  589. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  590. intermediate tags; if the original ref does not point to a tag,
  591. this will equal the original SHA1.
  592. """
  593. cached = self.refs.get_peeled(ref)
  594. if cached is not None:
  595. return cached
  596. return self.object_store.peel_sha(self.refs[ref]).id
  597. def get_walker(self, include=None, *args, **kwargs):
  598. """Obtain a walker for this repository.
  599. Args:
  600. include: Iterable of SHAs of commits to include along with their
  601. ancestors. Defaults to [HEAD]
  602. exclude: Iterable of SHAs of commits to exclude along with their
  603. ancestors, overriding includes.
  604. order: ORDER_* constant specifying the order of results.
  605. Anything other than ORDER_DATE may result in O(n) memory usage.
  606. reverse: If True, reverse the order of output, requiring O(n)
  607. memory.
  608. max_entries: The maximum number of entries to yield, or None for
  609. no limit.
  610. paths: Iterable of file or subtree paths to show entries for.
  611. rename_detector: diff.RenameDetector object for detecting
  612. renames.
  613. follow: If True, follow path across renames/copies. Forces a
  614. default rename_detector.
  615. since: Timestamp to list commits after.
  616. until: Timestamp to list commits before.
  617. queue_cls: A class to use for a queue of commits, supporting the
  618. iterator protocol. The constructor takes a single argument, the
  619. Walker.
  620. Returns: A `Walker` object
  621. """
  622. from dulwich.walk import Walker
  623. if include is None:
  624. include = [self.head()]
  625. if isinstance(include, str):
  626. include = [include]
  627. kwargs["get_parents"] = lambda commit: self.get_parents(commit.id, commit)
  628. return Walker(self.object_store, include, *args, **kwargs)
  629. def __getitem__(self, name):
  630. """Retrieve a Git object by SHA1 or ref.
  631. Args:
  632. name: A Git object SHA1 or a ref name
  633. Returns: A `ShaFile` object, such as a Commit or Blob
  634. Raises:
  635. KeyError: when the specified ref or object does not exist
  636. """
  637. if not isinstance(name, bytes):
  638. raise TypeError(
  639. "'name' must be bytestring, not %.80s" % type(name).__name__
  640. )
  641. if len(name) in (20, 40):
  642. try:
  643. return self.object_store[name]
  644. except (KeyError, ValueError):
  645. pass
  646. try:
  647. return self.object_store[self.refs[name]]
  648. except RefFormatError:
  649. raise KeyError(name)
  650. def __contains__(self, name: bytes) -> bool:
  651. """Check if a specific Git object or ref is present.
  652. Args:
  653. name: Git object SHA1 or ref name
  654. """
  655. if len(name) == 20 or (len(name) == 40 and valid_hexsha(name)):
  656. return name in self.object_store or name in self.refs
  657. else:
  658. return name in self.refs
  659. def __setitem__(self, name: bytes, value: Union[ShaFile, bytes]):
  660. """Set a ref.
  661. Args:
  662. name: ref name
  663. value: Ref value - either a ShaFile object, or a hex sha
  664. """
  665. if name.startswith(b"refs/") or name == b"HEAD":
  666. if isinstance(value, ShaFile):
  667. self.refs[name] = value.id
  668. elif isinstance(value, bytes):
  669. self.refs[name] = value
  670. else:
  671. raise TypeError(value)
  672. else:
  673. raise ValueError(name)
  674. def __delitem__(self, name: bytes):
  675. """Remove a ref.
  676. Args:
  677. name: Name of the ref to remove
  678. """
  679. if name.startswith(b"refs/") or name == b"HEAD":
  680. del self.refs[name]
  681. else:
  682. raise ValueError(name)
  683. def _get_user_identity(self, config: "StackedConfig", kind: str = None) -> bytes:
  684. """Determine the identity to use for new commits."""
  685. # TODO(jelmer): Deprecate this function in favor of get_user_identity
  686. return get_user_identity(config)
  687. def _add_graftpoints(self, updated_graftpoints: Dict[bytes, List[bytes]]):
  688. """Add or modify graftpoints
  689. Args:
  690. updated_graftpoints: Dict of commit shas to list of parent shas
  691. """
  692. # Simple validation
  693. for commit, parents in updated_graftpoints.items():
  694. for sha in [commit] + parents:
  695. check_hexsha(sha, "Invalid graftpoint")
  696. self._graftpoints.update(updated_graftpoints)
  697. def _remove_graftpoints(self, to_remove: List[bytes] = []) -> None:
  698. """Remove graftpoints
  699. Args:
  700. to_remove: List of commit shas
  701. """
  702. for sha in to_remove:
  703. del self._graftpoints[sha]
  704. def _read_heads(self, name):
  705. f = self.get_named_file(name)
  706. if f is None:
  707. return []
  708. with f:
  709. return [line.strip() for line in f.readlines() if line.strip()]
  710. def do_commit( # noqa: C901
  711. self,
  712. message=None,
  713. committer=None,
  714. author=None,
  715. commit_timestamp=None,
  716. commit_timezone=None,
  717. author_timestamp=None,
  718. author_timezone=None,
  719. tree=None,
  720. encoding=None,
  721. ref=b"HEAD",
  722. merge_heads=None,
  723. no_verify=False,
  724. ):
  725. """Create a new commit.
  726. If not specified, `committer` and `author` default to
  727. get_user_identity(..., 'COMMITTER')
  728. and get_user_identity(..., 'AUTHOR') respectively.
  729. Args:
  730. message: Commit message
  731. committer: Committer fullname
  732. author: Author fullname
  733. commit_timestamp: Commit timestamp (defaults to now)
  734. commit_timezone: Commit timestamp timezone (defaults to GMT)
  735. author_timestamp: Author timestamp (defaults to commit
  736. timestamp)
  737. author_timezone: Author timestamp timezone
  738. (defaults to commit timestamp timezone)
  739. tree: SHA1 of the tree root to use (if not specified the
  740. current index will be committed).
  741. encoding: Encoding
  742. ref: Optional ref to commit to (defaults to current branch)
  743. merge_heads: Merge heads (defaults to .git/MERGE_HEAD)
  744. no_verify: Skip pre-commit and commit-msg hooks
  745. Returns:
  746. New commit SHA1
  747. """
  748. c = Commit()
  749. if tree is None:
  750. index = self.open_index()
  751. c.tree = index.commit(self.object_store)
  752. else:
  753. if len(tree) != 40:
  754. raise ValueError("tree must be a 40-byte hex sha string")
  755. c.tree = tree
  756. try:
  757. if not no_verify:
  758. self.hooks["pre-commit"].execute()
  759. except HookError as e:
  760. raise CommitError(e)
  761. except KeyError: # no hook defined, silent fallthrough
  762. pass
  763. config = self.get_config_stack()
  764. if merge_heads is None:
  765. merge_heads = self._read_heads("MERGE_HEAD")
  766. if committer is None:
  767. committer = get_user_identity(config, kind="COMMITTER")
  768. check_user_identity(committer)
  769. c.committer = committer
  770. if commit_timestamp is None:
  771. # FIXME: Support GIT_COMMITTER_DATE environment variable
  772. commit_timestamp = time.time()
  773. c.commit_time = int(commit_timestamp)
  774. if commit_timezone is None:
  775. # FIXME: Use current user timezone rather than UTC
  776. commit_timezone = 0
  777. c.commit_timezone = commit_timezone
  778. if author is None:
  779. author = get_user_identity(config, kind="AUTHOR")
  780. c.author = author
  781. check_user_identity(author)
  782. if author_timestamp is None:
  783. # FIXME: Support GIT_AUTHOR_DATE environment variable
  784. author_timestamp = commit_timestamp
  785. c.author_time = int(author_timestamp)
  786. if author_timezone is None:
  787. author_timezone = commit_timezone
  788. c.author_timezone = author_timezone
  789. if encoding is None:
  790. try:
  791. encoding = config.get(("i18n",), "commitEncoding")
  792. except KeyError:
  793. pass # No dice
  794. if encoding is not None:
  795. c.encoding = encoding
  796. if message is None:
  797. # FIXME: Try to read commit message from .git/MERGE_MSG
  798. raise ValueError("No commit message specified")
  799. try:
  800. if no_verify:
  801. c.message = message
  802. else:
  803. c.message = self.hooks["commit-msg"].execute(message)
  804. if c.message is None:
  805. c.message = message
  806. except HookError as e:
  807. raise CommitError(e)
  808. except KeyError: # no hook defined, message not modified
  809. c.message = message
  810. if ref is None:
  811. # Create a dangling commit
  812. c.parents = merge_heads
  813. self.object_store.add_object(c)
  814. else:
  815. try:
  816. old_head = self.refs[ref]
  817. c.parents = [old_head] + merge_heads
  818. self.object_store.add_object(c)
  819. ok = self.refs.set_if_equals(
  820. ref,
  821. old_head,
  822. c.id,
  823. message=b"commit: " + message,
  824. committer=committer,
  825. timestamp=commit_timestamp,
  826. timezone=commit_timezone,
  827. )
  828. except KeyError:
  829. c.parents = merge_heads
  830. self.object_store.add_object(c)
  831. ok = self.refs.add_if_new(
  832. ref,
  833. c.id,
  834. message=b"commit: " + message,
  835. committer=committer,
  836. timestamp=commit_timestamp,
  837. timezone=commit_timezone,
  838. )
  839. if not ok:
  840. # Fail if the atomic compare-and-swap failed, leaving the
  841. # commit and all its objects as garbage.
  842. raise CommitError("%s changed during commit" % (ref,))
  843. self._del_named_file("MERGE_HEAD")
  844. try:
  845. self.hooks["post-commit"].execute()
  846. except HookError as e: # silent failure
  847. warnings.warn("post-commit hook failed: %s" % e, UserWarning)
  848. except KeyError: # no hook defined, silent fallthrough
  849. pass
  850. return c.id
  851. def read_gitfile(f):
  852. """Read a ``.git`` file.
  853. The first line of the file should start with "gitdir: "
  854. Args:
  855. f: File-like object to read from
  856. Returns: A path
  857. """
  858. cs = f.read()
  859. if not cs.startswith("gitdir: "):
  860. raise ValueError("Expected file to start with 'gitdir: '")
  861. return cs[len("gitdir: ") :].rstrip("\n")
  862. class UnsupportedVersion(Exception):
  863. """Unsupported repository version."""
  864. def __init__(self, version):
  865. self.version = version
  866. class Repo(BaseRepo):
  867. """A git repository backed by local disk.
  868. To open an existing repository, call the contructor with
  869. the path of the repository.
  870. To create a new repository, use the Repo.init class method.
  871. """
  872. def __init__(self, root, object_store=None, bare=None):
  873. hidden_path = os.path.join(root, CONTROLDIR)
  874. if bare is None:
  875. if (os.path.isfile(hidden_path) or
  876. os.path.isdir(os.path.join(hidden_path, OBJECTDIR))):
  877. bare = False
  878. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  879. os.path.isdir(os.path.join(root, REFSDIR))):
  880. bare = True
  881. else:
  882. raise NotGitRepository(
  883. "No git repository was found at %(path)s" % dict(path=root)
  884. )
  885. self.bare = bare
  886. if bare is False:
  887. if os.path.isfile(hidden_path):
  888. with open(hidden_path, "r") as f:
  889. path = read_gitfile(f)
  890. self.bare = False
  891. self._controldir = os.path.join(root, path)
  892. else:
  893. self._controldir = hidden_path
  894. else:
  895. self._controldir = root
  896. commondir = self.get_named_file(COMMONDIR)
  897. if commondir is not None:
  898. with commondir:
  899. self._commondir = os.path.join(
  900. self.controldir(),
  901. os.fsdecode(commondir.read().rstrip(b"\r\n")),
  902. )
  903. else:
  904. self._commondir = self._controldir
  905. self.path = root
  906. config = self.get_config()
  907. try:
  908. format_version = int(config.get("core", "repositoryformatversion"))
  909. except KeyError:
  910. format_version = 0
  911. if format_version != 0:
  912. raise UnsupportedVersion(format_version)
  913. if object_store is None:
  914. object_store = DiskObjectStore.from_config(
  915. os.path.join(self.commondir(), OBJECTDIR), config
  916. )
  917. refs = DiskRefsContainer(
  918. self.commondir(), self._controldir, logger=self._write_reflog
  919. )
  920. BaseRepo.__init__(self, object_store, refs)
  921. self._graftpoints = {}
  922. graft_file = self.get_named_file(
  923. os.path.join("info", "grafts"), basedir=self.commondir()
  924. )
  925. if graft_file:
  926. with graft_file:
  927. self._graftpoints.update(parse_graftpoints(graft_file))
  928. graft_file = self.get_named_file("shallow", basedir=self.commondir())
  929. if graft_file:
  930. with graft_file:
  931. self._graftpoints.update(parse_graftpoints(graft_file))
  932. self.hooks["pre-commit"] = PreCommitShellHook(self.controldir())
  933. self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir())
  934. self.hooks["post-commit"] = PostCommitShellHook(self.controldir())
  935. self.hooks["post-receive"] = PostReceiveShellHook(self.controldir())
  936. def _write_reflog(
  937. self, ref, old_sha, new_sha, committer, timestamp, timezone, message
  938. ):
  939. from .reflog import format_reflog_line
  940. path = os.path.join(self.controldir(), "logs", os.fsdecode(ref))
  941. try:
  942. os.makedirs(os.path.dirname(path))
  943. except FileExistsError:
  944. pass
  945. if committer is None:
  946. config = self.get_config_stack()
  947. committer = self._get_user_identity(config)
  948. check_user_identity(committer)
  949. if timestamp is None:
  950. timestamp = int(time.time())
  951. if timezone is None:
  952. timezone = 0 # FIXME
  953. with open(path, "ab") as f:
  954. f.write(
  955. format_reflog_line(
  956. old_sha, new_sha, committer, timestamp, timezone, message
  957. )
  958. + b"\n"
  959. )
  960. @classmethod
  961. def discover(cls, start="."):
  962. """Iterate parent directories to discover a repository
  963. Return a Repo object for the first parent directory that looks like a
  964. Git repository.
  965. Args:
  966. start: The directory to start discovery from (defaults to '.')
  967. """
  968. remaining = True
  969. path = os.path.abspath(start)
  970. while remaining:
  971. try:
  972. return cls(path)
  973. except NotGitRepository:
  974. path, remaining = os.path.split(path)
  975. raise NotGitRepository(
  976. "No git repository was found at %(path)s" % dict(path=start)
  977. )
  978. def controldir(self):
  979. """Return the path of the control directory."""
  980. return self._controldir
  981. def commondir(self):
  982. """Return the path of the common directory.
  983. For a main working tree, it is identical to controldir().
  984. For a linked working tree, it is the control directory of the
  985. main working tree."""
  986. return self._commondir
  987. def _determine_file_mode(self):
  988. """Probe the file-system to determine whether permissions can be trusted.
  989. Returns: True if permissions can be trusted, False otherwise.
  990. """
  991. fname = os.path.join(self.path, ".probe-permissions")
  992. with open(fname, "w") as f:
  993. f.write("")
  994. st1 = os.lstat(fname)
  995. try:
  996. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  997. except PermissionError:
  998. return False
  999. st2 = os.lstat(fname)
  1000. os.unlink(fname)
  1001. mode_differs = st1.st_mode != st2.st_mode
  1002. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  1003. return mode_differs and st2_has_exec
  1004. def _put_named_file(self, path, contents):
  1005. """Write a file to the control dir with the given name and contents.
  1006. Args:
  1007. path: The path to the file, relative to the control dir.
  1008. contents: A string to write to the file.
  1009. """
  1010. path = path.lstrip(os.path.sep)
  1011. with GitFile(os.path.join(self.controldir(), path), "wb") as f:
  1012. f.write(contents)
  1013. def _del_named_file(self, path):
  1014. try:
  1015. os.unlink(os.path.join(self.controldir(), path))
  1016. except FileNotFoundError:
  1017. return
  1018. def get_named_file(self, path, basedir=None):
  1019. """Get a file from the control dir with a specific name.
  1020. Although the filename should be interpreted as a filename relative to
  1021. the control dir in a disk-based Repo, the object returned need not be
  1022. pointing to a file in that location.
  1023. Args:
  1024. path: The path to the file, relative to the control dir.
  1025. basedir: Optional argument that specifies an alternative to the
  1026. control dir.
  1027. Returns: An open file object, or None if the file does not exist.
  1028. """
  1029. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1030. # the dumb web serving code.
  1031. if basedir is None:
  1032. basedir = self.controldir()
  1033. path = path.lstrip(os.path.sep)
  1034. try:
  1035. return open(os.path.join(basedir, path), "rb")
  1036. except FileNotFoundError:
  1037. return None
  1038. def index_path(self):
  1039. """Return path to the index file."""
  1040. return os.path.join(self.controldir(), INDEX_FILENAME)
  1041. def open_index(self) -> "Index":
  1042. """Open the index for this repository.
  1043. Raises:
  1044. NoIndexPresent: If no index is present
  1045. Returns: The matching `Index`
  1046. """
  1047. from dulwich.index import Index
  1048. if not self.has_index():
  1049. raise NoIndexPresent()
  1050. return Index(self.index_path())
  1051. def has_index(self):
  1052. """Check if an index is present."""
  1053. # Bare repos must never have index files; non-bare repos may have a
  1054. # missing index file, which is treated as empty.
  1055. return not self.bare
  1056. def stage(self, fs_paths):
  1057. """Stage a set of paths.
  1058. Args:
  1059. fs_paths: List of paths, relative to the repository path
  1060. """
  1061. root_path_bytes = os.fsencode(self.path)
  1062. if isinstance(fs_paths, str):
  1063. fs_paths = [fs_paths]
  1064. fs_paths = list(fs_paths)
  1065. from dulwich.index import (
  1066. blob_from_path_and_stat,
  1067. index_entry_from_stat,
  1068. _fs_to_tree_path,
  1069. )
  1070. index = self.open_index()
  1071. blob_normalizer = self.get_blob_normalizer()
  1072. for fs_path in fs_paths:
  1073. if not isinstance(fs_path, bytes):
  1074. fs_path = os.fsencode(fs_path)
  1075. if os.path.isabs(fs_path):
  1076. raise ValueError(
  1077. "path %r should be relative to "
  1078. "repository root, not absolute" % fs_path
  1079. )
  1080. tree_path = _fs_to_tree_path(fs_path)
  1081. full_path = os.path.join(root_path_bytes, fs_path)
  1082. try:
  1083. st = os.lstat(full_path)
  1084. except OSError:
  1085. # File no longer exists
  1086. try:
  1087. del index[tree_path]
  1088. except KeyError:
  1089. pass # already removed
  1090. else:
  1091. if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  1092. try:
  1093. del index[tree_path]
  1094. except KeyError:
  1095. pass
  1096. else:
  1097. blob = blob_from_path_and_stat(full_path, st)
  1098. blob = blob_normalizer.checkin_normalize(blob, fs_path)
  1099. self.object_store.add_object(blob)
  1100. index[tree_path] = index_entry_from_stat(st, blob.id, 0)
  1101. index.write()
  1102. def clone(
  1103. self,
  1104. target_path,
  1105. mkdir=True,
  1106. bare=False,
  1107. origin=b"origin",
  1108. checkout=None,
  1109. ):
  1110. """Clone this repository.
  1111. Args:
  1112. target_path: Target path
  1113. mkdir: Create the target directory
  1114. bare: Whether to create a bare repository
  1115. origin: Base name for refs in target repository
  1116. cloned from this repository
  1117. Returns: Created repository as `Repo`
  1118. """
  1119. if not bare:
  1120. target = self.init(target_path, mkdir=mkdir)
  1121. else:
  1122. if checkout:
  1123. raise ValueError("checkout and bare are incompatible")
  1124. target = self.init_bare(target_path, mkdir=mkdir)
  1125. self.fetch(target)
  1126. encoded_path = self.path
  1127. if not isinstance(encoded_path, bytes):
  1128. encoded_path = os.fsencode(encoded_path)
  1129. ref_message = b"clone: from " + encoded_path
  1130. target.refs.import_refs(
  1131. b"refs/remotes/" + origin,
  1132. self.refs.as_dict(b"refs/heads"),
  1133. message=ref_message,
  1134. )
  1135. target.refs.import_refs(
  1136. b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message
  1137. )
  1138. try:
  1139. target.refs.add_if_new(
  1140. DEFAULT_REF, self.refs[DEFAULT_REF], message=ref_message
  1141. )
  1142. except KeyError:
  1143. pass
  1144. target_config = target.get_config()
  1145. target_config.set(("remote", "origin"), "url", encoded_path)
  1146. target_config.set(
  1147. ("remote", "origin"),
  1148. "fetch",
  1149. "+refs/heads/*:refs/remotes/origin/*",
  1150. )
  1151. target_config.write_to_path()
  1152. # Update target head
  1153. head_chain, head_sha = self.refs.follow(b"HEAD")
  1154. if head_chain and head_sha is not None:
  1155. target.refs.set_symbolic_ref(b"HEAD", head_chain[-1], message=ref_message)
  1156. target[b"HEAD"] = head_sha
  1157. if checkout is None:
  1158. checkout = not bare
  1159. if checkout:
  1160. # Checkout HEAD to target dir
  1161. target.reset_index()
  1162. return target
  1163. def reset_index(self, tree=None):
  1164. """Reset the index back to a specific tree.
  1165. Args:
  1166. tree: Tree SHA to reset to, None for current HEAD tree.
  1167. """
  1168. from dulwich.index import (
  1169. build_index_from_tree,
  1170. validate_path_element_default,
  1171. validate_path_element_ntfs,
  1172. )
  1173. if tree is None:
  1174. tree = self[b"HEAD"].tree
  1175. config = self.get_config()
  1176. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  1177. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  1178. validate_path_element = validate_path_element_ntfs
  1179. else:
  1180. validate_path_element = validate_path_element_default
  1181. return build_index_from_tree(
  1182. self.path,
  1183. self.index_path(),
  1184. self.object_store,
  1185. tree,
  1186. honor_filemode=honor_filemode,
  1187. validate_path_element=validate_path_element,
  1188. )
  1189. def get_config(self) -> "ConfigFile":
  1190. """Retrieve the config object.
  1191. Returns: `ConfigFile` object for the ``.git/config`` file.
  1192. """
  1193. from dulwich.config import ConfigFile
  1194. path = os.path.join(self._controldir, "config")
  1195. try:
  1196. return ConfigFile.from_path(path)
  1197. except FileNotFoundError:
  1198. ret = ConfigFile()
  1199. ret.path = path
  1200. return ret
  1201. def get_description(self):
  1202. """Retrieve the description of this repository.
  1203. Returns: A string describing the repository or None.
  1204. """
  1205. path = os.path.join(self._controldir, "description")
  1206. try:
  1207. with GitFile(path, "rb") as f:
  1208. return f.read()
  1209. except FileNotFoundError:
  1210. return None
  1211. def __repr__(self):
  1212. return "<Repo at %r>" % self.path
  1213. def set_description(self, description):
  1214. """Set the description for this repository.
  1215. Args:
  1216. description: Text to set as description for this repository.
  1217. """
  1218. self._put_named_file("description", description)
  1219. @classmethod
  1220. def _init_maybe_bare(cls, path, controldir, bare, object_store=None):
  1221. for d in BASE_DIRECTORIES:
  1222. os.mkdir(os.path.join(controldir, *d))
  1223. if object_store is None:
  1224. object_store = DiskObjectStore.init(os.path.join(controldir, OBJECTDIR))
  1225. ret = cls(path, bare=bare, object_store=object_store)
  1226. ret.refs.set_symbolic_ref(b"HEAD", DEFAULT_REF)
  1227. ret._init_files(bare)
  1228. return ret
  1229. @classmethod
  1230. def init(cls, path, mkdir=False):
  1231. """Create a new repository.
  1232. Args:
  1233. path: Path in which to create the repository
  1234. mkdir: Whether to create the directory
  1235. Returns: `Repo` instance
  1236. """
  1237. if mkdir:
  1238. os.mkdir(path)
  1239. controldir = os.path.join(path, CONTROLDIR)
  1240. os.mkdir(controldir)
  1241. _set_filesystem_hidden(controldir)
  1242. return cls._init_maybe_bare(path, controldir, False)
  1243. @classmethod
  1244. def _init_new_working_directory(cls, path, main_repo, identifier=None, mkdir=False):
  1245. """Create a new working directory linked to a repository.
  1246. Args:
  1247. path: Path in which to create the working tree.
  1248. main_repo: Main repository to reference
  1249. identifier: Worktree identifier
  1250. mkdir: Whether to create the directory
  1251. Returns: `Repo` instance
  1252. """
  1253. if mkdir:
  1254. os.mkdir(path)
  1255. if identifier is None:
  1256. identifier = os.path.basename(path)
  1257. main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES)
  1258. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1259. gitdirfile = os.path.join(path, CONTROLDIR)
  1260. with open(gitdirfile, "wb") as f:
  1261. f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n")
  1262. try:
  1263. os.mkdir(main_worktreesdir)
  1264. except FileExistsError:
  1265. pass
  1266. try:
  1267. os.mkdir(worktree_controldir)
  1268. except FileExistsError:
  1269. pass
  1270. with open(os.path.join(worktree_controldir, GITDIR), "wb") as f:
  1271. f.write(os.fsencode(gitdirfile) + b"\n")
  1272. with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f:
  1273. f.write(b"../..\n")
  1274. with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f:
  1275. f.write(main_repo.head() + b"\n")
  1276. r = cls(path)
  1277. r.reset_index()
  1278. return r
  1279. @classmethod
  1280. def init_bare(cls, path, mkdir=False, object_store=None):
  1281. """Create a new bare repository.
  1282. ``path`` should already exist and be an empty directory.
  1283. Args:
  1284. path: Path to create bare repository in
  1285. Returns: a `Repo` instance
  1286. """
  1287. if mkdir:
  1288. os.mkdir(path)
  1289. return cls._init_maybe_bare(path, path, True, object_store=object_store)
  1290. create = init_bare
  1291. def close(self):
  1292. """Close any files opened by this repository."""
  1293. self.object_store.close()
  1294. def __enter__(self):
  1295. return self
  1296. def __exit__(self, exc_type, exc_val, exc_tb):
  1297. self.close()
  1298. def get_blob_normalizer(self):
  1299. """Return a BlobNormalizer object"""
  1300. # TODO Parse the git attributes files
  1301. git_attributes = {}
  1302. config_stack = self.get_config_stack()
  1303. try:
  1304. tree = self.object_store[self.refs[b"HEAD"]].tree
  1305. return TreeBlobNormalizer(
  1306. config_stack,
  1307. git_attributes,
  1308. self.object_store,
  1309. tree,
  1310. )
  1311. except KeyError:
  1312. return BlobNormalizer(config_stack, git_attributes)
  1313. class MemoryRepo(BaseRepo):
  1314. """Repo that stores refs, objects, and named files in memory.
  1315. MemoryRepos are always bare: they have no working tree and no index, since
  1316. those have a stronger dependency on the filesystem.
  1317. """
  1318. def __init__(self):
  1319. from dulwich.config import ConfigFile
  1320. self._reflog = []
  1321. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1322. BaseRepo.__init__(self, MemoryObjectStore(), refs_container)
  1323. self._named_files = {}
  1324. self.bare = True
  1325. self._config = ConfigFile()
  1326. self._description = None
  1327. def _append_reflog(self, *args):
  1328. self._reflog.append(args)
  1329. def set_description(self, description):
  1330. self._description = description
  1331. def get_description(self):
  1332. return self._description
  1333. def _determine_file_mode(self):
  1334. """Probe the file-system to determine whether permissions can be trusted.
  1335. Returns: True if permissions can be trusted, False otherwise.
  1336. """
  1337. return sys.platform != "win32"
  1338. def _put_named_file(self, path, contents):
  1339. """Write a file to the control dir with the given name and contents.
  1340. Args:
  1341. path: The path to the file, relative to the control dir.
  1342. contents: A string to write to the file.
  1343. """
  1344. self._named_files[path] = contents
  1345. def _del_named_file(self, path):
  1346. try:
  1347. del self._named_files[path]
  1348. except KeyError:
  1349. pass
  1350. def get_named_file(self, path, basedir=None):
  1351. """Get a file from the control dir with a specific name.
  1352. Although the filename should be interpreted as a filename relative to
  1353. the control dir in a disk-baked Repo, the object returned need not be
  1354. pointing to a file in that location.
  1355. Args:
  1356. path: The path to the file, relative to the control dir.
  1357. Returns: An open file object, or None if the file does not exist.
  1358. """
  1359. contents = self._named_files.get(path, None)
  1360. if contents is None:
  1361. return None
  1362. return BytesIO(contents)
  1363. def open_index(self):
  1364. """Fail to open index for this repo, since it is bare.
  1365. Raises:
  1366. NoIndexPresent: Raised when no index is present
  1367. """
  1368. raise NoIndexPresent()
  1369. def get_config(self):
  1370. """Retrieve the config object.
  1371. Returns: `ConfigFile` object.
  1372. """
  1373. return self._config
  1374. @classmethod
  1375. def init_bare(cls, objects, refs):
  1376. """Create a new bare repository in memory.
  1377. Args:
  1378. objects: Objects for the new repository,
  1379. as iterable
  1380. refs: Refs as dictionary, mapping names
  1381. to object SHA1s
  1382. """
  1383. ret = cls()
  1384. for obj in objects:
  1385. ret.object_store.add_object(obj)
  1386. for refname, sha in refs.items():
  1387. ret.refs.add_if_new(refname, sha)
  1388. ret._init_files(bare=True)
  1389. return ret