Skip to content

Commit

Permalink
Reduce use of tempfile (fix #25)
Browse files Browse the repository at this point in the history
  • Loading branch information
rec committed Sep 8, 2024
1 parent bedb6ec commit 84955c7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
6 changes: 4 additions & 2 deletions safer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,14 +657,16 @@ def __init__(
self.target_file = target_file
self.dry_run = dry_run
self.is_binary = is_binary
if temp_file is True:
parent, file = os.path.split(target_file)
temp_file = os.path.join(parent, f'.{file}.tmp-safer')

super().__init__(temp_file, delete_failures, parent)

def _success(self):
if not self.dry_run:
if os.path.exists(self.target_file):
shutil.copymode(self.target_file, self.temp_file)
else:
os.chmod(self.temp_file, 0o100644)
os.replace(self.temp_file, self.target_file)

elif callable(self.dry_run):
Expand Down
21 changes: 17 additions & 4 deletions test/test_open.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,18 @@ def test_two_errors(self, safer_open):
fp.write('OK!')
if uses_files:
after = set(os.listdir('.'))
assert len(before) + 2 == len(after)
assert len(after.difference(before)) == 2
assert len(before) + 1 == len(after)
assert len(after.difference(before)) == 1

assert len(before) + 1 == len(after)
assert len(after.difference(before)) == 1

assert FILENAME.read_text() == 'OK!'

if uses_files:
after = set(os.listdir('.'))
assert len(before) + 1 == len(after)
assert len(after.difference(before)) == 1
assert len(before) == len(after)
assert len(after.difference(before)) == 0

def test_error_with_copy(self, safer_open):
FILENAME.write_text('hello')
Expand Down Expand Up @@ -214,3 +217,13 @@ def test_file_exists_error(self, safer_open):
with safer_open(FILENAME, 'wt') as fp:
fp.write('goodbye')
assert FILENAME.read_text() == 'goodbye'

def test_tempfile_perms(self, safer_open):
temp_files = False, True, 'three.tmp'
perms = []
for i, temp_file in enumerate(temp_files):
with safer_open(str(i), 'w', temp_file=temp_file):
pass
perms.append(oct(os.stat(str(i)).st_mode))

assert perms == [perms[0]] * len(perms)

0 comments on commit 84955c7

Please sign in to comment.