Skip to content

Commit

Permalink
feat: add explicit activate context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
vberlier committed Feb 18, 2021
1 parent 35ace13 commit 1e21f66
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
32 changes: 18 additions & 14 deletions beet/toolchain/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@


import sys
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Optional, Tuple, TypeVar
Expand Down Expand Up @@ -73,22 +74,25 @@ def inject(self, cls: Callable[["Context"], InjectedType]) -> InjectedType:
"""Retrieve the instance provided by the specified service factory."""
return self._container[cls]

def __enter__(self) -> "Context":
@contextmanager
def activate(self):
sys.path.append(self._path_entry)
return self

def __exit__(self, *_):
sys.path.remove(self._path_entry)

imported_modules = [
name
for name, module in sys.modules.items()
if (filename := getattr(module, "__file__", None))
and filename.startswith(self._path_entry)
]

for name in imported_modules:
del sys.modules[name]
try:
with self.cache:
yield self.inject(Pipeline)
finally:
sys.path.remove(self._path_entry)

imported_modules = [
name
for name, module in sys.modules.items()
if (filename := getattr(module, "__file__", None))
and filename.startswith(self._path_entry)
]

for name in imported_modules:
del sys.modules[name]

@property
def packs(self) -> Tuple[ResourcePack, DataPack]:
Expand Down
8 changes: 4 additions & 4 deletions beet/toolchain/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from beet.core.watch import DirectoryWatcher, FileChanges

from .config import PackConfig, ProjectConfig, load_config, locate_config
from .context import Context, Pipeline, Plugin
from .context import Context, Plugin
from .pipeline import PipelineFallthroughException
from .template import TemplateManager
from .utils import locate_minecraft
Expand Down Expand Up @@ -211,9 +211,9 @@ def build(self) -> Context:
),
)

with ctx, ctx.cache:
ctx.require(self.bootstrap)
ctx.inject(Pipeline).run(
with ctx.activate() as pipeline:
pipeline.require(self.bootstrap)
pipeline.run(
(
item
if isinstance(item, str)
Expand Down

0 comments on commit 1e21f66

Please sign in to comment.