|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +This file implements a proxy for accessing container file systems. |
| 4 | +""" |
1 | 5 | __all__ = ('FileProxy',) |
2 | 6 |
|
3 | | -from typing import List, Union, overload |
| 7 | +from typing import List, Union, Optional, overload |
4 | 8 | from typing_extensions import Literal |
5 | 9 | import os |
6 | 10 | import shlex |
@@ -337,3 +341,45 @@ def rmtree(self, d: str) -> None: |
337 | 341 | code, output, duration = self.__shell.execute(cmd) |
338 | 342 | if code != 0: |
339 | 343 | raise OSError(f"failed to remove directory tree: {d}") |
| 344 | + |
| 345 | + def mktemp(self, |
| 346 | + suffix: Optional[str] = None, |
| 347 | + prefix: Optional[str] = None, |
| 348 | + dirname: Optional[str] = None |
| 349 | + ) -> str: |
| 350 | + """Creates a temporary file. |
| 351 | +
|
| 352 | + Parameters |
| 353 | + ---------- |
| 354 | + suffix: str, optional |
| 355 | + an optional suffix for the filename. |
| 356 | + prefix: str, optional |
| 357 | + an optional prefix for the filename. |
| 358 | + dirname: str, optional |
| 359 | + if specified, the temporary file will be created in the given |
| 360 | + directory. |
| 361 | +
|
| 362 | + Raises |
| 363 | + ------ |
| 364 | + FileNotFoundError: |
| 365 | + if specified directory does not exist. |
| 366 | + OSError: |
| 367 | + if the temporary file could not be constructed. |
| 368 | + """ |
| 369 | + template = shlex.quote(f"{prefix if prefix else 'tmp'}.XXXXXXXXXX") |
| 370 | + cmd_parts = ['mktemp', template] |
| 371 | + if suffix: |
| 372 | + cmd_parts += ['--suffix', shlex.quote(suffix)] |
| 373 | + if dirname: |
| 374 | + cmd_parts += ['-p', shlex.quote(dirname)] |
| 375 | + if not self.isdir(dirname): |
| 376 | + m = f'directory does not exist: {dirname}' |
| 377 | + raise FileNotFoundError(m) |
| 378 | + cmd = ' '.join(cmd_parts) |
| 379 | + |
| 380 | + code, output, duration = self.__shell.execute(cmd) |
| 381 | + # TODO capture context |
| 382 | + if code != 0: |
| 383 | + raise OSError(f"failed to create temporary directory") |
| 384 | + |
| 385 | + return output |
0 commit comments