Skip to content

Commit

Permalink
util: add ensure_dir_exists parameter to write_file (#443)
Browse files Browse the repository at this point in the history
This allows us to disable the `ensure_dir` call when it isn't
appropriate.
  • Loading branch information
OddBloke authored Jun 19, 2020
1 parent d083a03 commit 40e7286
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
16 changes: 14 additions & 2 deletions cloudinit/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1800,7 +1800,15 @@ def chmod(path, mode):
os.chmod(path, real_mode)


def write_file(filename, content, mode=0o644, omode="wb", preserve_mode=False):
def write_file(
filename,
content,
mode=0o644,
omode="wb",
preserve_mode=False,
*,
ensure_dir_exists=True
):
"""
Writes a file with the given content and sets the file mode as specified.
Restores the SELinux context if possible.
Expand All @@ -1811,6 +1819,9 @@ def write_file(filename, content, mode=0o644, omode="wb", preserve_mode=False):
@param omode: The open mode used when opening the file (w, wb, a, etc.)
@param preserve_mode: If True and `filename` exists, preserve `filename`s
current mode instead of applying `mode`.
@param ensure_dir_exists: If True (the default), ensure that the directory
containing `filename` exists before writing to
the file.
"""

if preserve_mode:
Expand All @@ -1820,7 +1831,8 @@ def write_file(filename, content, mode=0o644, omode="wb", preserve_mode=False):
except OSError:
pass

ensure_dir(os.path.dirname(filename))
if ensure_dir_exists:
ensure_dir(os.path.dirname(filename))
if 'b' in omode.lower():
content = encode_text(content)
write_type = 'bytes'
Expand Down
11 changes: 11 additions & 0 deletions tests/unittests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@ def test_dir_is_created_if_required(self):
self.assertTrue(os.path.isdir(dirname))
self.assertTrue(os.path.isfile(path))

def test_dir_is_not_created_if_ensure_dir_false(self):
"""Verify directories are not created if ensure_dir_exists is False."""
dirname = os.path.join(self.tmp, "subdir")
path = os.path.join(dirname, "NewFile.txt")
contents = "Hey there"

with self.assertRaises(FileNotFoundError):
util.write_file(path, contents, ensure_dir_exists=False)

self.assertFalse(os.path.isdir(dirname))

def test_explicit_mode(self):
"""Verify explicit file mode works properly."""
path = os.path.join(self.tmp, "NewFile.txt")
Expand Down

0 comments on commit 40e7286

Please sign in to comment.