repo.py 49 KB

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