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