repo.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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
  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 set(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. self._put_named_file("shallow", b"".join([sha + b"\n" for sha in shallow]))
  580. def get_peeled(self, ref):
  581. """Get the peeled value of a ref.
  582. Args:
  583. ref: The refname to peel.
  584. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  585. intermediate tags; if the original ref does not point to a tag,
  586. this will equal the original SHA1.
  587. """
  588. cached = self.refs.get_peeled(ref)
  589. if cached is not None:
  590. return cached
  591. return self.object_store.peel_sha(self.refs[ref]).id
  592. def get_walker(self, include=None, *args, **kwargs):
  593. """Obtain a walker for this repository.
  594. Args:
  595. include: Iterable of SHAs of commits to include along with their
  596. ancestors. Defaults to [HEAD]
  597. exclude: Iterable of SHAs of commits to exclude along with their
  598. ancestors, overriding includes.
  599. order: ORDER_* constant specifying the order of results.
  600. Anything other than ORDER_DATE may result in O(n) memory usage.
  601. reverse: If True, reverse the order of output, requiring O(n)
  602. memory.
  603. max_entries: The maximum number of entries to yield, or None for
  604. no limit.
  605. paths: Iterable of file or subtree paths to show entries for.
  606. rename_detector: diff.RenameDetector object for detecting
  607. renames.
  608. follow: If True, follow path across renames/copies. Forces a
  609. default rename_detector.
  610. since: Timestamp to list commits after.
  611. until: Timestamp to list commits before.
  612. queue_cls: A class to use for a queue of commits, supporting the
  613. iterator protocol. The constructor takes a single argument, the
  614. Walker.
  615. Returns: A `Walker` object
  616. """
  617. from dulwich.walk import Walker
  618. if include is None:
  619. include = [self.head()]
  620. if isinstance(include, str):
  621. include = [include]
  622. kwargs["get_parents"] = lambda commit: self.get_parents(commit.id, commit)
  623. return Walker(self.object_store, include, *args, **kwargs)
  624. def __getitem__(self, name):
  625. """Retrieve a Git object by SHA1 or ref.
  626. Args:
  627. name: A Git object SHA1 or a ref name
  628. Returns: A `ShaFile` object, such as a Commit or Blob
  629. Raises:
  630. KeyError: when the specified ref or object does not exist
  631. """
  632. if not isinstance(name, bytes):
  633. raise TypeError(
  634. "'name' must be bytestring, not %.80s" % type(name).__name__
  635. )
  636. if len(name) in (20, 40):
  637. try:
  638. return self.object_store[name]
  639. except (KeyError, ValueError):
  640. pass
  641. try:
  642. return self.object_store[self.refs[name]]
  643. except RefFormatError:
  644. raise KeyError(name)
  645. def __contains__(self, name: bytes) -> bool:
  646. """Check if a specific Git object or ref is present.
  647. Args:
  648. name: Git object SHA1 or ref name
  649. """
  650. if len(name) == 20 or (len(name) == 40 and valid_hexsha(name)):
  651. return name in self.object_store or name in self.refs
  652. else:
  653. return name in self.refs
  654. def __setitem__(self, name: bytes, value: Union[ShaFile, bytes]):
  655. """Set a ref.
  656. Args:
  657. name: ref name
  658. value: Ref value - either a ShaFile object, or a hex sha
  659. """
  660. if name.startswith(b"refs/") or name == b"HEAD":
  661. if isinstance(value, ShaFile):
  662. self.refs[name] = value.id
  663. elif isinstance(value, bytes):
  664. self.refs[name] = value
  665. else:
  666. raise TypeError(value)
  667. else:
  668. raise ValueError(name)
  669. def __delitem__(self, name: bytes):
  670. """Remove a ref.
  671. Args:
  672. name: Name of the ref to remove
  673. """
  674. if name.startswith(b"refs/") or name == b"HEAD":
  675. del self.refs[name]
  676. else:
  677. raise ValueError(name)
  678. def _get_user_identity(self, config: "StackedConfig", kind: str = None) -> bytes:
  679. """Determine the identity to use for new commits."""
  680. # TODO(jelmer): Deprecate this function in favor of get_user_identity
  681. return get_user_identity(config)
  682. def _add_graftpoints(self, updated_graftpoints: Dict[bytes, List[bytes]]):
  683. """Add or modify graftpoints
  684. Args:
  685. updated_graftpoints: Dict of commit shas to list of parent shas
  686. """
  687. # Simple validation
  688. for commit, parents in updated_graftpoints.items():
  689. for sha in [commit] + parents:
  690. check_hexsha(sha, "Invalid graftpoint")
  691. self._graftpoints.update(updated_graftpoints)
  692. def _remove_graftpoints(self, to_remove: List[bytes] = []) -> None:
  693. """Remove graftpoints
  694. Args:
  695. to_remove: List of commit shas
  696. """
  697. for sha in to_remove:
  698. del self._graftpoints[sha]
  699. def _read_heads(self, name):
  700. f = self.get_named_file(name)
  701. if f is None:
  702. return []
  703. with f:
  704. return [line.strip() for line in f.readlines() if line.strip()]
  705. def do_commit( # noqa: C901
  706. self,
  707. message=None,
  708. committer=None,
  709. author=None,
  710. commit_timestamp=None,
  711. commit_timezone=None,
  712. author_timestamp=None,
  713. author_timezone=None,
  714. tree=None,
  715. encoding=None,
  716. ref=b"HEAD",
  717. merge_heads=None,
  718. no_verify=False,
  719. ):
  720. """Create a new commit.
  721. If not specified, `committer` and `author` default to
  722. get_user_identity(..., 'COMMITTER')
  723. and get_user_identity(..., 'AUTHOR') respectively.
  724. Args:
  725. message: Commit message
  726. committer: Committer fullname
  727. author: Author fullname
  728. commit_timestamp: Commit timestamp (defaults to now)
  729. commit_timezone: Commit timestamp timezone (defaults to GMT)
  730. author_timestamp: Author timestamp (defaults to commit
  731. timestamp)
  732. author_timezone: Author timestamp timezone
  733. (defaults to commit timestamp timezone)
  734. tree: SHA1 of the tree root to use (if not specified the
  735. current index will be committed).
  736. encoding: Encoding
  737. ref: Optional ref to commit to (defaults to current branch)
  738. merge_heads: Merge heads (defaults to .git/MERGE_HEADS)
  739. no_verify: Skip pre-commit and commit-msg hooks
  740. Returns:
  741. New commit SHA1
  742. """
  743. import time
  744. c = Commit()
  745. if tree is None:
  746. index = self.open_index()
  747. c.tree = index.commit(self.object_store)
  748. else:
  749. if len(tree) != 40:
  750. raise ValueError("tree must be a 40-byte hex sha string")
  751. c.tree = tree
  752. try:
  753. if not no_verify:
  754. self.hooks["pre-commit"].execute()
  755. except HookError as e:
  756. raise CommitError(e)
  757. except KeyError: # no hook defined, silent fallthrough
  758. pass
  759. config = self.get_config_stack()
  760. if merge_heads is None:
  761. merge_heads = self._read_heads("MERGE_HEADS")
  762. if committer is None:
  763. committer = get_user_identity(config, kind="COMMITTER")
  764. check_user_identity(committer)
  765. c.committer = committer
  766. if commit_timestamp is None:
  767. # FIXME: Support GIT_COMMITTER_DATE environment variable
  768. commit_timestamp = time.time()
  769. c.commit_time = int(commit_timestamp)
  770. if commit_timezone is None:
  771. # FIXME: Use current user timezone rather than UTC
  772. commit_timezone = 0
  773. c.commit_timezone = commit_timezone
  774. if author is None:
  775. author = get_user_identity(config, kind="AUTHOR")
  776. c.author = author
  777. check_user_identity(author)
  778. if author_timestamp is None:
  779. # FIXME: Support GIT_AUTHOR_DATE environment variable
  780. author_timestamp = commit_timestamp
  781. c.author_time = int(author_timestamp)
  782. if author_timezone is None:
  783. author_timezone = commit_timezone
  784. c.author_timezone = author_timezone
  785. if encoding is None:
  786. try:
  787. encoding = config.get(("i18n",), "commitEncoding")
  788. except KeyError:
  789. pass # No dice
  790. if encoding is not None:
  791. c.encoding = encoding
  792. if message is None:
  793. # FIXME: Try to read commit message from .git/MERGE_MSG
  794. raise ValueError("No commit message specified")
  795. try:
  796. if no_verify:
  797. c.message = message
  798. else:
  799. c.message = self.hooks["commit-msg"].execute(message)
  800. if c.message is None:
  801. c.message = message
  802. except HookError as e:
  803. raise CommitError(e)
  804. except KeyError: # no hook defined, message not modified
  805. c.message = message
  806. if ref is None:
  807. # Create a dangling commit
  808. c.parents = merge_heads
  809. self.object_store.add_object(c)
  810. else:
  811. try:
  812. old_head = self.refs[ref]
  813. c.parents = [old_head] + merge_heads
  814. self.object_store.add_object(c)
  815. ok = self.refs.set_if_equals(
  816. ref,
  817. old_head,
  818. c.id,
  819. message=b"commit: " + message,
  820. committer=committer,
  821. timestamp=commit_timestamp,
  822. timezone=commit_timezone,
  823. )
  824. except KeyError:
  825. c.parents = merge_heads
  826. self.object_store.add_object(c)
  827. ok = self.refs.add_if_new(
  828. ref,
  829. c.id,
  830. message=b"commit: " + message,
  831. committer=committer,
  832. timestamp=commit_timestamp,
  833. timezone=commit_timezone,
  834. )
  835. if not ok:
  836. # Fail if the atomic compare-and-swap failed, leaving the
  837. # commit and all its objects as garbage.
  838. raise CommitError("%s changed during commit" % (ref,))
  839. self._del_named_file("MERGE_HEADS")
  840. try:
  841. self.hooks["post-commit"].execute()
  842. except HookError as e: # silent failure
  843. warnings.warn("post-commit hook failed: %s" % e, UserWarning)
  844. except KeyError: # no hook defined, silent fallthrough
  845. pass
  846. return c.id
  847. def read_gitfile(f):
  848. """Read a ``.git`` file.
  849. The first line of the file should start with "gitdir: "
  850. Args:
  851. f: File-like object to read from
  852. Returns: A path
  853. """
  854. cs = f.read()
  855. if not cs.startswith("gitdir: "):
  856. raise ValueError("Expected file to start with 'gitdir: '")
  857. return cs[len("gitdir: ") :].rstrip("\n")
  858. class UnsupportedVersion(Exception):
  859. """Unsupported repository version."""
  860. def __init__(self, version):
  861. self.version = version
  862. class Repo(BaseRepo):
  863. """A git repository backed by local disk.
  864. To open an existing repository, call the contructor with
  865. the path of the repository.
  866. To create a new repository, use the Repo.init class method.
  867. """
  868. def __init__(self, root):
  869. hidden_path = os.path.join(root, CONTROLDIR)
  870. if os.path.isdir(os.path.join(hidden_path, OBJECTDIR)):
  871. self.bare = False
  872. self._controldir = hidden_path
  873. elif os.path.isdir(os.path.join(root, OBJECTDIR)) and os.path.isdir(
  874. os.path.join(root, REFSDIR)
  875. ):
  876. self.bare = True
  877. self._controldir = root
  878. elif os.path.isfile(hidden_path):
  879. self.bare = False
  880. with open(hidden_path, "r") as f:
  881. path = read_gitfile(f)
  882. self.bare = False
  883. self._controldir = os.path.join(root, path)
  884. else:
  885. raise NotGitRepository(
  886. "No git repository was found at %(path)s" % dict(path=root)
  887. )
  888. commondir = self.get_named_file(COMMONDIR)
  889. if commondir is not None:
  890. with commondir:
  891. self._commondir = os.path.join(
  892. self.controldir(),
  893. os.fsdecode(commondir.read().rstrip(b"\r\n")),
  894. )
  895. else:
  896. self._commondir = self._controldir
  897. self.path = root
  898. config = self.get_config()
  899. try:
  900. format_version = int(config.get("core", "repositoryformatversion"))
  901. except KeyError:
  902. format_version = 0
  903. if format_version != 0:
  904. raise UnsupportedVersion(format_version)
  905. object_store = DiskObjectStore.from_config(
  906. os.path.join(self.commondir(), OBJECTDIR), config
  907. )
  908. refs = DiskRefsContainer(
  909. self.commondir(), self._controldir, logger=self._write_reflog
  910. )
  911. BaseRepo.__init__(self, object_store, refs)
  912. self._graftpoints = {}
  913. graft_file = self.get_named_file(
  914. os.path.join("info", "grafts"), basedir=self.commondir()
  915. )
  916. if graft_file:
  917. with graft_file:
  918. self._graftpoints.update(parse_graftpoints(graft_file))
  919. graft_file = self.get_named_file("shallow", basedir=self.commondir())
  920. if graft_file:
  921. with graft_file:
  922. self._graftpoints.update(parse_graftpoints(graft_file))
  923. self.hooks["pre-commit"] = PreCommitShellHook(self.controldir())
  924. self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir())
  925. self.hooks["post-commit"] = PostCommitShellHook(self.controldir())
  926. self.hooks["post-receive"] = PostReceiveShellHook(self.controldir())
  927. def _write_reflog(
  928. self, ref, old_sha, new_sha, committer, timestamp, timezone, message
  929. ):
  930. from .reflog import format_reflog_line
  931. path = os.path.join(self.controldir(), "logs", os.fsdecode(ref))
  932. try:
  933. os.makedirs(os.path.dirname(path))
  934. except FileExistsError:
  935. pass
  936. if committer is None:
  937. config = self.get_config_stack()
  938. committer = self._get_user_identity(config)
  939. check_user_identity(committer)
  940. if timestamp is None:
  941. timestamp = int(time.time())
  942. if timezone is None:
  943. timezone = 0 # FIXME
  944. with open(path, "ab") as f:
  945. f.write(
  946. format_reflog_line(
  947. old_sha, new_sha, committer, timestamp, timezone, message
  948. )
  949. + b"\n"
  950. )
  951. @classmethod
  952. def discover(cls, start="."):
  953. """Iterate parent directories to discover a repository
  954. Return a Repo object for the first parent directory that looks like a
  955. Git repository.
  956. Args:
  957. start: The directory to start discovery from (defaults to '.')
  958. """
  959. remaining = True
  960. path = os.path.abspath(start)
  961. while remaining:
  962. try:
  963. return cls(path)
  964. except NotGitRepository:
  965. path, remaining = os.path.split(path)
  966. raise NotGitRepository(
  967. "No git repository was found at %(path)s" % dict(path=start)
  968. )
  969. def controldir(self):
  970. """Return the path of the control directory."""
  971. return self._controldir
  972. def commondir(self):
  973. """Return the path of the common directory.
  974. For a main working tree, it is identical to controldir().
  975. For a linked working tree, it is the control directory of the
  976. main working tree."""
  977. return self._commondir
  978. def _determine_file_mode(self):
  979. """Probe the file-system to determine whether permissions can be trusted.
  980. Returns: True if permissions can be trusted, False otherwise.
  981. """
  982. fname = os.path.join(self.path, ".probe-permissions")
  983. with open(fname, "w") as f:
  984. f.write("")
  985. st1 = os.lstat(fname)
  986. try:
  987. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  988. except PermissionError:
  989. return False
  990. st2 = os.lstat(fname)
  991. os.unlink(fname)
  992. mode_differs = st1.st_mode != st2.st_mode
  993. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  994. return mode_differs and st2_has_exec
  995. def _put_named_file(self, path, contents):
  996. """Write a file to the control dir with the given name and contents.
  997. Args:
  998. path: The path to the file, relative to the control dir.
  999. contents: A string to write to the file.
  1000. """
  1001. path = path.lstrip(os.path.sep)
  1002. with GitFile(os.path.join(self.controldir(), path), "wb") as f:
  1003. f.write(contents)
  1004. def _del_named_file(self, path):
  1005. try:
  1006. os.unlink(os.path.join(self.controldir(), path))
  1007. except FileNotFoundError:
  1008. return
  1009. def get_named_file(self, path, basedir=None):
  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-based Repo, the object returned need not be
  1013. pointing to a file in that location.
  1014. Args:
  1015. path: The path to the file, relative to the control dir.
  1016. basedir: Optional argument that specifies an alternative to the
  1017. control dir.
  1018. Returns: An open file object, or None if the file does not exist.
  1019. """
  1020. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1021. # the dumb web serving code.
  1022. if basedir is None:
  1023. basedir = self.controldir()
  1024. path = path.lstrip(os.path.sep)
  1025. try:
  1026. return open(os.path.join(basedir, path), "rb")
  1027. except FileNotFoundError:
  1028. return None
  1029. def index_path(self):
  1030. """Return path to the index file."""
  1031. return os.path.join(self.controldir(), INDEX_FILENAME)
  1032. def open_index(self) -> "Index":
  1033. """Open the index for this repository.
  1034. Raises:
  1035. NoIndexPresent: If no index is present
  1036. Returns: The matching `Index`
  1037. """
  1038. from dulwich.index import Index
  1039. if not self.has_index():
  1040. raise NoIndexPresent()
  1041. return Index(self.index_path())
  1042. def has_index(self):
  1043. """Check if an index is present."""
  1044. # Bare repos must never have index files; non-bare repos may have a
  1045. # missing index file, which is treated as empty.
  1046. return not self.bare
  1047. def stage(self, fs_paths):
  1048. """Stage a set of paths.
  1049. Args:
  1050. fs_paths: List of paths, relative to the repository path
  1051. """
  1052. root_path_bytes = os.fsencode(self.path)
  1053. if not isinstance(fs_paths, list):
  1054. fs_paths = [fs_paths]
  1055. from dulwich.index import (
  1056. blob_from_path_and_stat,
  1057. index_entry_from_stat,
  1058. _fs_to_tree_path,
  1059. )
  1060. index = self.open_index()
  1061. blob_normalizer = self.get_blob_normalizer()
  1062. for fs_path in fs_paths:
  1063. if not isinstance(fs_path, bytes):
  1064. fs_path = os.fsencode(fs_path)
  1065. if os.path.isabs(fs_path):
  1066. raise ValueError(
  1067. "path %r should be relative to "
  1068. "repository root, not absolute" % fs_path
  1069. )
  1070. tree_path = _fs_to_tree_path(fs_path)
  1071. full_path = os.path.join(root_path_bytes, fs_path)
  1072. try:
  1073. st = os.lstat(full_path)
  1074. except OSError:
  1075. # File no longer exists
  1076. try:
  1077. del index[tree_path]
  1078. except KeyError:
  1079. pass # already removed
  1080. else:
  1081. if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  1082. try:
  1083. del index[tree_path]
  1084. except KeyError:
  1085. pass
  1086. else:
  1087. blob = blob_from_path_and_stat(full_path, st)
  1088. blob = blob_normalizer.checkin_normalize(blob, fs_path)
  1089. self.object_store.add_object(blob)
  1090. index[tree_path] = index_entry_from_stat(st, blob.id, 0)
  1091. index.write()
  1092. def clone(
  1093. self,
  1094. target_path,
  1095. mkdir=True,
  1096. bare=False,
  1097. origin=b"origin",
  1098. checkout=None,
  1099. ):
  1100. """Clone this repository.
  1101. Args:
  1102. target_path: Target path
  1103. mkdir: Create the target directory
  1104. bare: Whether to create a bare repository
  1105. origin: Base name for refs in target repository
  1106. cloned from this repository
  1107. Returns: Created repository as `Repo`
  1108. """
  1109. if not bare:
  1110. target = self.init(target_path, mkdir=mkdir)
  1111. else:
  1112. if checkout:
  1113. raise ValueError("checkout and bare are incompatible")
  1114. target = self.init_bare(target_path, mkdir=mkdir)
  1115. self.fetch(target)
  1116. encoded_path = self.path
  1117. if not isinstance(encoded_path, bytes):
  1118. encoded_path = os.fsencode(encoded_path)
  1119. ref_message = b"clone: from " + encoded_path
  1120. target.refs.import_refs(
  1121. b"refs/remotes/" + origin,
  1122. self.refs.as_dict(b"refs/heads"),
  1123. message=ref_message,
  1124. )
  1125. target.refs.import_refs(
  1126. b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message
  1127. )
  1128. try:
  1129. target.refs.add_if_new(
  1130. DEFAULT_REF, self.refs[DEFAULT_REF], message=ref_message
  1131. )
  1132. except KeyError:
  1133. pass
  1134. target_config = target.get_config()
  1135. target_config.set(("remote", "origin"), "url", encoded_path)
  1136. target_config.set(
  1137. ("remote", "origin"),
  1138. "fetch",
  1139. "+refs/heads/*:refs/remotes/origin/*",
  1140. )
  1141. target_config.write_to_path()
  1142. # Update target head
  1143. head_chain, head_sha = self.refs.follow(b"HEAD")
  1144. if head_chain and head_sha is not None:
  1145. target.refs.set_symbolic_ref(b"HEAD", head_chain[-1], message=ref_message)
  1146. target[b"HEAD"] = head_sha
  1147. if checkout is None:
  1148. checkout = not bare
  1149. if checkout:
  1150. # Checkout HEAD to target dir
  1151. target.reset_index()
  1152. return target
  1153. def reset_index(self, tree=None):
  1154. """Reset the index back to a specific tree.
  1155. Args:
  1156. tree: Tree SHA to reset to, None for current HEAD tree.
  1157. """
  1158. from dulwich.index import (
  1159. build_index_from_tree,
  1160. validate_path_element_default,
  1161. validate_path_element_ntfs,
  1162. )
  1163. if tree is None:
  1164. tree = self[b"HEAD"].tree
  1165. config = self.get_config()
  1166. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  1167. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  1168. validate_path_element = validate_path_element_ntfs
  1169. else:
  1170. validate_path_element = validate_path_element_default
  1171. return build_index_from_tree(
  1172. self.path,
  1173. self.index_path(),
  1174. self.object_store,
  1175. tree,
  1176. honor_filemode=honor_filemode,
  1177. validate_path_element=validate_path_element,
  1178. )
  1179. def get_config(self) -> "ConfigFile":
  1180. """Retrieve the config object.
  1181. Returns: `ConfigFile` object for the ``.git/config`` file.
  1182. """
  1183. from dulwich.config import ConfigFile
  1184. path = os.path.join(self._controldir, "config")
  1185. try:
  1186. return ConfigFile.from_path(path)
  1187. except FileNotFoundError:
  1188. ret = ConfigFile()
  1189. ret.path = path
  1190. return ret
  1191. def get_description(self):
  1192. """Retrieve the description of this repository.
  1193. Returns: A string describing the repository or None.
  1194. """
  1195. path = os.path.join(self._controldir, "description")
  1196. try:
  1197. with GitFile(path, "rb") as f:
  1198. return f.read()
  1199. except FileNotFoundError:
  1200. return None
  1201. def __repr__(self):
  1202. return "<Repo at %r>" % self.path
  1203. def set_description(self, description):
  1204. """Set the description for this repository.
  1205. Args:
  1206. description: Text to set as description for this repository.
  1207. """
  1208. self._put_named_file("description", description)
  1209. @classmethod
  1210. def _init_maybe_bare(cls, path, bare):
  1211. for d in BASE_DIRECTORIES:
  1212. os.mkdir(os.path.join(path, *d))
  1213. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  1214. ret = cls(path)
  1215. ret.refs.set_symbolic_ref(b"HEAD", DEFAULT_REF)
  1216. ret._init_files(bare)
  1217. return ret
  1218. @classmethod
  1219. def init(cls, path, mkdir=False):
  1220. """Create a new repository.
  1221. Args:
  1222. path: Path in which to create the repository
  1223. mkdir: Whether to create the directory
  1224. Returns: `Repo` instance
  1225. """
  1226. if mkdir:
  1227. os.mkdir(path)
  1228. controldir = os.path.join(path, CONTROLDIR)
  1229. os.mkdir(controldir)
  1230. _set_filesystem_hidden(controldir)
  1231. cls._init_maybe_bare(controldir, False)
  1232. return cls(path)
  1233. @classmethod
  1234. def _init_new_working_directory(cls, path, main_repo, identifier=None, mkdir=False):
  1235. """Create a new working directory linked to a repository.
  1236. Args:
  1237. path: Path in which to create the working tree.
  1238. main_repo: Main repository to reference
  1239. identifier: Worktree identifier
  1240. mkdir: Whether to create the directory
  1241. Returns: `Repo` instance
  1242. """
  1243. if mkdir:
  1244. os.mkdir(path)
  1245. if identifier is None:
  1246. identifier = os.path.basename(path)
  1247. main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES)
  1248. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1249. gitdirfile = os.path.join(path, CONTROLDIR)
  1250. with open(gitdirfile, "wb") as f:
  1251. f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n")
  1252. try:
  1253. os.mkdir(main_worktreesdir)
  1254. except FileExistsError:
  1255. pass
  1256. try:
  1257. os.mkdir(worktree_controldir)
  1258. except FileExistsError:
  1259. pass
  1260. with open(os.path.join(worktree_controldir, GITDIR), "wb") as f:
  1261. f.write(os.fsencode(gitdirfile) + b"\n")
  1262. with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f:
  1263. f.write(b"../..\n")
  1264. with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f:
  1265. f.write(main_repo.head() + b"\n")
  1266. r = cls(path)
  1267. r.reset_index()
  1268. return r
  1269. @classmethod
  1270. def init_bare(cls, path, mkdir=False):
  1271. """Create a new bare repository.
  1272. ``path`` should already exist and be an empty directory.
  1273. Args:
  1274. path: Path to create bare repository in
  1275. Returns: a `Repo` instance
  1276. """
  1277. if mkdir:
  1278. os.mkdir(path)
  1279. return cls._init_maybe_bare(path, True)
  1280. create = init_bare
  1281. def close(self):
  1282. """Close any files opened by this repository."""
  1283. self.object_store.close()
  1284. def __enter__(self):
  1285. return self
  1286. def __exit__(self, exc_type, exc_val, exc_tb):
  1287. self.close()
  1288. def get_blob_normalizer(self):
  1289. """Return a BlobNormalizer object"""
  1290. # TODO Parse the git attributes files
  1291. git_attributes = {}
  1292. return BlobNormalizer(self.get_config_stack(), git_attributes)
  1293. class MemoryRepo(BaseRepo):
  1294. """Repo that stores refs, objects, and named files in memory.
  1295. MemoryRepos are always bare: they have no working tree and no index, since
  1296. those have a stronger dependency on the filesystem.
  1297. """
  1298. def __init__(self):
  1299. from dulwich.config import ConfigFile
  1300. self._reflog = []
  1301. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1302. BaseRepo.__init__(self, MemoryObjectStore(), refs_container)
  1303. self._named_files = {}
  1304. self.bare = True
  1305. self._config = ConfigFile()
  1306. self._description = None
  1307. def _append_reflog(self, *args):
  1308. self._reflog.append(args)
  1309. def set_description(self, description):
  1310. self._description = description
  1311. def get_description(self):
  1312. return self._description
  1313. def _determine_file_mode(self):
  1314. """Probe the file-system to determine whether permissions can be trusted.
  1315. Returns: True if permissions can be trusted, False otherwise.
  1316. """
  1317. return sys.platform != "win32"
  1318. def _put_named_file(self, path, contents):
  1319. """Write a file to the control dir with the given name and contents.
  1320. Args:
  1321. path: The path to the file, relative to the control dir.
  1322. contents: A string to write to the file.
  1323. """
  1324. self._named_files[path] = contents
  1325. def _del_named_file(self, path):
  1326. try:
  1327. del self._named_files[path]
  1328. except KeyError:
  1329. pass
  1330. def get_named_file(self, path, basedir=None):
  1331. """Get a file from the control dir with a specific name.
  1332. Although the filename should be interpreted as a filename relative to
  1333. the control dir in a disk-baked Repo, the object returned need not be
  1334. pointing to a file in that location.
  1335. Args:
  1336. path: The path to the file, relative to the control dir.
  1337. Returns: An open file object, or None if the file does not exist.
  1338. """
  1339. contents = self._named_files.get(path, None)
  1340. if contents is None:
  1341. return None
  1342. return BytesIO(contents)
  1343. def open_index(self):
  1344. """Fail to open index for this repo, since it is bare.
  1345. Raises:
  1346. NoIndexPresent: Raised when no index is present
  1347. """
  1348. raise NoIndexPresent()
  1349. def get_config(self):
  1350. """Retrieve the config object.
  1351. Returns: `ConfigFile` object.
  1352. """
  1353. return self._config
  1354. @classmethod
  1355. def init_bare(cls, objects, refs):
  1356. """Create a new bare repository in memory.
  1357. Args:
  1358. objects: Objects for the new repository,
  1359. as iterable
  1360. refs: Refs as dictionary, mapping names
  1361. to object SHA1s
  1362. """
  1363. ret = cls()
  1364. for obj in objects:
  1365. ret.object_store.add_object(obj)
  1366. for refname, sha in refs.items():
  1367. ret.refs.add_if_new(refname, sha)
  1368. ret._init_files(bare=True)
  1369. return ret