diff --git a/pydu/system.py b/pydu/system.py index 6ea9bfd..71ff950 100644 --- a/pydu/system.py +++ b/pydu/system.py @@ -255,3 +255,20 @@ else: except: if not ignore_errors: raise OSError('Link {} to {} error'.format(dst, src)) + + + def chmod(path, mode): + """ + Change the access permissions of a file or directory + + >>> chmod('/opt/sometest', 0o755) + >>> oct(os.stat('/opt/sometest').st_mode)[-3:] + 755 + """ + if os.path.isdir(path): + for root, _, files in os.walk(path): + os.chmod(root, mode) + for file_ in files: + os.chmod(os.path.join(root, file_), mode) + else: + os.chmod(path, mode) diff --git a/tests/test_system.py b/tests/test_system.py index 043f4b3..b20fc9e 100644 --- a/tests/test_system.py +++ b/tests/test_system.py @@ -1,12 +1,15 @@ import os import stat import time +import tempfile + import pytest + from pydu.platform import WINDOWS from pydu.system import makedirs, remove, removes, open_file, copy, touch, which if not WINDOWS: - from pydu.system import link, symlink + from pydu.system import link, symlink, chmod class TestMakeDirs: @@ -350,3 +353,22 @@ def test_chcp(): assert str(cp) == '' finally: windll.kernel32.SetConsoleOutputCP(origin_code) + + +@pytest.mark.skipif(WINDOWS, reason='Not support on windows') +class TestChmod: + def test_chmod_file(self): + _, t_file = tempfile.mkstemp() + chmod(t_file, 755) + assert oct(os.stat(t_file).st_mode)[-3:] == '755' + + def test_chmod_dir(self): + t_dir = tempfile.mkdtemp() + for _ in range(5): + tempfile.mkstemp(dir=t_dir) + chmod(t_dir, 755) + for root, _, files in os.walk(t_dir): + assert oct(os.stat(root).st_mode)[-3:] == '755' + for file_ in files: + assert oct(os.stat(os.path.join(root, file_)).st_mode)[-3:] == '755' +