Skip to content

Commit f28e2af

Browse files
Added tempfile context manager to FileProxy (fixes #123) (#126)
* added tempfile method * added test_tempfile
1 parent f31bb9a commit f28e2af

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/rozzy/proxy/file.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
"""
55
__all__ = ('FileProxy',)
66

7-
from typing import List, Union, Optional, overload
7+
from typing import List, Union, Iterator, Optional, overload
88
from typing_extensions import Literal
99
import os
10+
import contextlib
1011
import shlex
12+
import logging
1113
import tempfile
1214
import subprocess
1315

@@ -16,6 +18,9 @@
1618
from .shell import ShellProxy
1719
from ..exceptions import RozzyException
1820

21+
logger: logging.Logger = logging.getLogger(__name__)
22+
logger.setLevel(logging.DEBUG)
23+
1924

2025
class FileProxy:
2126
def __init__(self,
@@ -365,6 +370,11 @@ def mktemp(self,
365370
if specified directory does not exist.
366371
OSError:
367372
if the temporary file could not be constructed.
373+
374+
Returns
375+
-------
376+
str
377+
The absolute path of the temporary file.
368378
"""
369379
template = shlex.quote(f"{prefix if prefix else 'tmp'}.XXXXXXXXXX")
370380
cmd_parts = ['mktemp', template]
@@ -383,3 +393,31 @@ def mktemp(self,
383393
raise OSError(f"failed to create temporary directory")
384394

385395
return output
396+
397+
@contextlib.contextmanager
398+
def tempfile(self,
399+
suffix: Optional[str] = None,
400+
prefix: Optional[str] = None,
401+
dirname: Optional[str] = None
402+
) -> Iterator[str]:
403+
"""Creates a temporary file within a context.
404+
405+
Upon exiting the context, the temporary file will be destroyed.
406+
407+
See Also
408+
--------
409+
mktemp: Uses the same arguments to create a temporary file.
410+
411+
Yields
412+
------
413+
str
414+
The absolute path of the temporary file.
415+
"""
416+
fn = self.mktemp(suffix=suffix, prefix=prefix, dirname=dirname)
417+
logger.debug("created temporary file: %s", fn)
418+
yield fn
419+
logger.debug("destroying temporary file: %s", fn)
420+
try:
421+
self.remove(fn)
422+
except FileNotFoundError:
423+
logger.debug("temporary file already destroyed: %s", fn)

test/test_file.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,3 +352,11 @@ def test_mktemp():
352352
fn = files.mktemp(prefix='foo')
353353
assert os.path.basename(fn).startswith('foo')
354354
assert files.isfile(fn)
355+
356+
357+
def test_tempfile():
358+
with build_file_proxy() as files:
359+
fn: str
360+
with files.tempfile() as fn:
361+
assert files.isfile(fn)
362+
assert not files.exists(fn)

0 commit comments

Comments
 (0)