repo.py 51 KB

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