Skip to content

Commit

Permalink
rf: add patched_env contextm manager
Browse files Browse the repository at this point in the history
  • Loading branch information
christian-monch committed Jan 7, 2025
1 parent 124ae4d commit 4e7a646
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
10 changes: 2 additions & 8 deletions datalad_remake/commands/provision_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
from datalad_remake.commands.make_cmd import read_list
from datalad_remake.utils.chdir import chdir
from datalad_remake.utils.glob import glob
from datalad_remake.utils.patched_env import patched_env

if TYPE_CHECKING:
from collections.abc import Generator, Iterable
Expand Down Expand Up @@ -390,15 +391,8 @@ def install_subdataset(
absolute_path.as_uri(),
]
call_git_lines(args)
stored_environ = dict(os.environ)
try:
for key in ('GIT_DIR', 'GIT_WORK_TREE'):
if key in os.environ:
del os.environ[key]
with patched_env(remove=['GIT_DIR', 'GIT_WORK_TREE']):
worktree.get(str(subdataset_path), get_data=False, result_renderer='disabled')
finally:
os.environ.clear()
os.environ.update(stored_environ)
uninstalled_subdatasets.remove(subdataset_path)
uninstalled_subdatasets.update(get_uninstalled_subdatasets(worktree))

Expand Down
41 changes: 41 additions & 0 deletions datalad_remake/utils/patched_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from __future__ import annotations

from contextlib import contextmanager


@contextmanager
def patched_env(
add: dict | None = None,
remove: list[str] | None = None,
):
"""
Patch the environment for the duration of the context manager.
Parameters
----------
add : dict
The environment variables to add.
remove : list[str]
The environment variables to remove.
Yields
-------
None
"""
import os

# Store the original environment
original_env = dict(os.environ)

# Update the environment
os.environ.update(add or {})
for var in remove or []:
if var in os.environ:
del os.environ[var]

try:
yield
finally:
# Restore the original environment
os.environ.clear()
os.environ.update(original_env)

0 comments on commit 4e7a646

Please sign in to comment.