From 2142a7b85e2d955d2dcd30a3c381ec5dffdfd081 Mon Sep 17 00:00:00 2001 From: Andy Kipp Date: Wed, 10 Jul 2024 22:49:57 +0200 Subject: [PATCH] tools: added ``mkdir`` to ``xonsh.tools.chdir`` (#5589) * mkdir chdir * mkdir chdir * mkdir chdir * mkdir chdir * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: a <1@1.1> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- news/chdir_mkdir.rst | 23 +++++++++++++++++++++++ tests/test_dirstack.py | 10 ++++++++++ xonsh/tools.py | 4 +++- 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 news/chdir_mkdir.rst diff --git a/news/chdir_mkdir.rst b/news/chdir_mkdir.rst new file mode 100644 index 000000000..ff3ab0c97 --- /dev/null +++ b/news/chdir_mkdir.rst @@ -0,0 +1,23 @@ +**Added:** + +* tools: added ``mkdir`` to ``xonsh.tools.chdir`` e.g. ``with chdir('/tmp/new', mkdir=True): pass``. + +**Changed:** + +* + +**Deprecated:** + +* + +**Removed:** + +* + +**Fixed:** + +* + +**Security:** + +* diff --git a/tests/test_dirstack.py b/tests/test_dirstack.py index c106061d6..e70d10c8a 100644 --- a/tests/test_dirstack.py +++ b/tests/test_dirstack.py @@ -19,6 +19,16 @@ def test_simple(xession): assert os.getcwd() == HERE +def test_chdir_mkdir(tmpdir): + d = str(tmpdir.join("chdir_mkdir")) + with chdir(d, mkdir=True): + assert os.getcwd() == d + assert os.getcwd() != d + with chdir(d, mkdir=True): + # Repeat to check there is no error for existing dir. + assert os.getcwd() == d + + def test_cdpath_simple(xession): xession.env.update(dict(CDPATH=PARENT, PWD=HERE)) with chdir(os.path.normpath("/")): diff --git a/xonsh/tools.py b/xonsh/tools.py index ebb7b7c62..1001b1301 100644 --- a/xonsh/tools.py +++ b/xonsh/tools.py @@ -57,8 +57,10 @@ from xonsh.platform import ( @contextmanager -def chdir(adir): +def chdir(adir, mkdir=False): old_dir = os.getcwd() + if mkdir: + os.makedirs(adir, exist_ok=True) os.chdir(adir) try: yield