repo.py 48 KB

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