[master 1/5] Add a function to open a file with specific permission bits
dashea
installerbot-noreply at redhat.com
Tue Jul 14 21:56:33 UTC 2015
From: David Shea <dshea at redhat.com>
This uses the "opener" argument to open to pass extra arguments through
to os.open.
---
pyanaconda/iutil.py | 16 ++++++++++++++++
tests/pyanaconda_tests/iutil_test.py | 20 ++++++++++++++++++++
2 files changed, 36 insertions(+)
diff --git a/pyanaconda/iutil.py b/pyanaconda/iutil.py
index 84bc44a..858c9b1 100644
--- a/pyanaconda/iutil.py
+++ b/pyanaconda/iutil.py
@@ -1343,3 +1343,19 @@ def open(*args, **kwargs): # pylint: disable=redefined-builtin
high-level languages handle this for you, like C's fopen.
"""
return eintr_retry_call(_open, *args, **kwargs)
+
+def open_with_perm(path, mode='r', perm=0o777, **kwargs):
+ """Open a file with the given permission bits.
+
+ This is more or less the same as using os.open(path, flags, perm), but
+ with the builtin open() semantics and return type instead of a file
+ descriptor.
+
+ :param str path: The path of the file to be opened
+ :param str mode: The same thing as the mode argument to open()
+ :param int perm: What permission bits to use if creating a new file
+ """
+ def _opener(path, open_flags):
+ return eintr_retry_call(os.open, path, open_flags, perm)
+
+ return open(path, mode, opener=_opener, **kwargs)
diff --git a/tests/pyanaconda_tests/iutil_test.py b/tests/pyanaconda_tests/iutil_test.py
index 090d84a..9f19455 100644
--- a/tests/pyanaconda_tests/iutil_test.py
+++ b/tests/pyanaconda_tests/iutil_test.py
@@ -771,3 +771,23 @@ def parent_dir_test(self):
for d, r in dirs:
self.assertEquals(iutil.parent_dir(d), r)
+
+ def open_with_perm_test(self):
+ """Test the open_with_perm function"""
+ # Create a directory for test files
+ test_dir = tempfile.mkdtemp()
+ try:
+ # Reset the umask
+ old_umask = os.umask(0)
+ try:
+ # Create a file with mode 0777
+ iutil.open_with_perm('test1', 'w', 0o777)
+ self.assertEqual(os.stat('test1').st_mode & 0o777, 0o777)
+
+ # Create a file with mode 0600
+ iutil.open_with_perm('test2', 'w', 0o600)
+ self.assertEqual(os.stat('test2').st_mode & 0o777, 0o600)
+ finally:
+ os.umask(old_umask)
+ finally:
+ shutil.rmtree(test_dir)
--
To view this commit on github, visit https://github.com/rhinstaller/anaconda/commit/6c927447c96eec7b887f206dd217f010e1f31aa1
More information about the anaconda-patches
mailing list