Skip to content

Commit

Permalink
Fixed DP-003
Browse files Browse the repository at this point in the history
  • Loading branch information
roll committed Sep 25, 2024
1 parent 7be561a commit 4ad70e7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
13 changes: 10 additions & 3 deletions dplib/helpers/__spec__/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,15 @@
from dplib.helpers.file import write_file


def test_write_file_permissions_dp_002(tmpdir: Path):
def test_write_file_implicit_permissions_dp_002(tmpdir: Path):
path = str(tmpdir / "test.txt")
write_file(path, "Hello, World!")
mode = oct(stat.S_IMODE(os.stat(path).st_mode))
assert mode == "0o600"
permissions = oct(stat.S_IMODE(os.stat(path).st_mode))
assert permissions == "0o600"


def test_write_file_explicit_permissions_dp_003(tmpdir: Path):
path = str(tmpdir / "test.txt")
write_file(path, "Hello, World!", permissions=0o644)
permissions = oct(stat.S_IMODE(os.stat(path).st_mode))
assert permissions == "0o644"
15 changes: 11 additions & 4 deletions dplib/helpers/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,28 @@ def read_file(
raise Error(f'Cannot read file "{path}"')


def write_file(path: str, body: Any, *, mode: str = "wt", encoding: str = "utf-8"):
def write_file(
path: str,
body: Any,
*,
mode: str = "wt",
encoding: str = "utf-8",
permissions: int = 0o600,
):
try:
eff_enc = encoding if mode == "wt" else None
with tempfile.NamedTemporaryFile(mode, delete=False, encoding=eff_enc) as file:
file.write(body)
file.flush()
move_file(file.name, path)
move_file(file.name, path, permissions=permissions)
except Exception:
raise Error(f'Cannot write file "{path}"')


def move_file(source: str, target: str, *, mode: int = 0o600):
def move_file(source: str, target: str, *, permissions: int = 0o600):
try:
Path(target).parent.mkdir(parents=True, exist_ok=True)
shutil.move(source, target)
os.chmod(target, mode)
os.chmod(target, permissions)
except Exception:
raise Error(f'Cannot move file "{source}:{target}"')

0 comments on commit 4ad70e7

Please sign in to comment.