Merge pull request #2724 from CJ-Wright/rmtree

Rmtree
This commit is contained in:
Anthony Scopatz 2018-07-19 17:47:33 -04:00 committed by GitHub
commit f0a97b2a90
Failed to generate hash of commit
3 changed files with 57 additions and 1 deletions

14
news/rmtree.rst Normal file
View file

@ -0,0 +1,14 @@
**Added:**
* ``xonsh.lib.os.rmtree()`` an rmtree which works on windows properly (even with
git)
**Changed:** None
**Deprecated:** None
**Removed:** None
**Fixed:** None
**Security:** None

View file

@ -1,6 +1,6 @@
import os
import tempfile
from xonsh.lib.os import indir
from xonsh.lib.os import indir, rmtree
def test_indir():
@ -9,3 +9,20 @@ def test_indir():
with indir(tmpdir):
assert ![pwd].output.strip() == tmpdir
assert ![pwd].output.strip() != tmpdir
def test_rmtree():
with tempfile.TemporaryDirectory() as tmpdir:
with indir(tmpdir):
mkdir rmtree_test
pushd rmtree_test
git init
touch thing.txt
git add thing
git commit -am "add thing"
popd
assert os.path.exists('rmtree_test')
assert os.path.exists('rmtree_test/thing.txt')
rmtree('rmtree_test')
assert not os.path.exists('rmtree_test')
assert not os.path.exists('rmtree_test/thing.txt')

View file

@ -1,6 +1,7 @@
"""Xonsh extension of the standard library os module, using xonsh for
subprocess calls"""
from contextlib import contextmanager
import sys
@contextmanager
@ -9,3 +10,27 @@ def indir(d):
![pushd @(d)]
yield
![popd]
def rmtree(dirname, force=False):
"""Remove a directory, even if it has read-only files (Windows).
Git creates read-only files that must be removed on teardown. See
https://stackoverflow.com/questions/2656322 for more info.
Parameters
----------
dirname : str
Directory to be removed
force : bool
If True force removal, defaults to False
"""
cmd_args = '-r'
if force:
cmd_args += 'f'
try:
rm @(cmd_args) @(dirname)
except PermissionError:
if sys.platform == "win32":
del /F/S/Q @(dirname)
else:
raise