diff --git a/news/tools_chdir.rst b/news/tools_chdir.rst new file mode 100644 index 0000000000..ef96590c2b --- /dev/null +++ b/news/tools_chdir.rst @@ -0,0 +1,23 @@ +**Added:** + +* Added ``chdir`` to ``xonsh.tools``. This allows to use ``with chdir("dir"):`` to run commands block in the certain directory without manually cd-ing. + +**Changed:** + +* + +**Deprecated:** + +* + +**Removed:** + +* + +**Fixed:** + +* + +**Security:** + +* diff --git a/tests/test_dirstack.py b/tests/test_dirstack.py index 10d59a3e7d..3f9a0f8c1d 100644 --- a/tests/test_dirstack.py +++ b/tests/test_dirstack.py @@ -1,24 +1,16 @@ """Testing dirstack""" import os -from contextlib import contextmanager import pytest # noqa F401 from xonsh import dirstack +from xonsh.tools import chdir HERE = os.path.abspath(os.path.dirname(__file__)) PARENT = os.path.dirname(HERE) -@contextmanager -def chdir(adir): - old_dir = os.getcwd() - os.chdir(adir) - yield - os.chdir(old_dir) - - def test_simple(xession): xession.env.update(dict(CDPATH=PARENT, PWD=PARENT)) with chdir(PARENT): diff --git a/xonsh/tools.py b/xonsh/tools.py index 25bc51c1c0..53406e233b 100644 --- a/xonsh/tools.py +++ b/xonsh/tools.py @@ -37,6 +37,7 @@ import traceback import typing as tp import warnings +from contextlib import contextmanager # adding imports from further xonsh modules is discouraged to avoid circular # dependencies @@ -53,6 +54,14 @@ ) +@contextmanager +def chdir(adir): + old_dir = os.getcwd() + os.chdir(adir) + yield + os.chdir(old_dir) + + @functools.lru_cache(1) def is_superuser(): if ON_WINDOWS: