repo.py 47 KB

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