44"""
55__all__ = ('FileProxy' ,)
66
7- from typing import List , Union , Optional , overload
7+ from typing import List , Union , Iterator , Optional , overload
88from typing_extensions import Literal
99import os
10+ import contextlib
1011import shlex
12+ import logging
1113import tempfile
1214import subprocess
1315
1618from .shell import ShellProxy
1719from ..exceptions import RozzyException
1820
21+ logger : logging .Logger = logging .getLogger (__name__ )
22+ logger .setLevel (logging .DEBUG )
23+
1924
2025class 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 )
0 commit comments