1"""
2The temp module provides a NamedTemporaryFile that can be reopened in the same
3process on any platform. Most platforms use the standard Python
4tempfile.NamedTemporaryFile class, but Windows users are given a custom class.
5
6This is needed because the Python implementation of NamedTemporaryFile uses the
7O_TEMPORARY flag under Windows, which prevents the file from being reopened
8if the same flag is not provided [1][2]. Note that this does not address the
9more general issue of opening a file for writing and reading in multiple
10processes in a manner that works across platforms.
11
12The custom version of NamedTemporaryFile doesn't support the same keyword
13arguments available in tempfile.NamedTemporaryFile.
14
151: https://mail.python.org/pipermail/python-list/2005-December/336957.html
162: https://bugs.python.org/issue14243
17"""
18
19import os
20import tempfile
21from collections.abc import Callable
22from types import TracebackType
23from typing import Self
24
25from plain.internal.files.utils import FileProxyMixin
26
27if os.name == "nt":
28
29 class TemporaryFile(FileProxyMixin):
30 """
31 Temporary file object constructor that supports reopening of the
32 temporary file in Windows.
33
34 Unlike tempfile.NamedTemporaryFile from the standard library,
35 __init__() doesn't support the 'delete', 'buffering', 'encoding', or
36 'newline' keyword arguments.
37 """
38
39 def __init__(
40 self,
41 mode: str = "w+b",
42 bufsize: int = -1,
43 suffix: str = "",
44 prefix: str = "",
45 dir: str | None = None,
46 ) -> None:
47 fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
48 self.name = name
49 self.file = os.fdopen(fd, mode, bufsize)
50 self.close_called = False
51
52 # Because close can be called during shutdown
53 # we need to cache os.unlink and access it
54 # as self.unlink only
55 unlink: Callable[[str], None] = os.unlink
56
57 def close(self) -> None:
58 if not self.close_called:
59 self.close_called = True
60 try:
61 self.file.close()
62 except OSError:
63 pass
64 try:
65 self.unlink(self.name)
66 except OSError:
67 pass
68
69 def __del__(self) -> None:
70 self.close()
71
72 def __enter__(self) -> Self:
73 self.file.__enter__()
74 return self
75
76 def __exit__(
77 self,
78 exc: type[BaseException] | None,
79 value: BaseException | None,
80 tb: TracebackType | None,
81 ) -> None:
82 self.file.__exit__(exc, value, tb)
83
84 NamedTemporaryFile = TemporaryFile
85else:
86 NamedTemporaryFile = tempfile.NamedTemporaryFile
87
88gettempdir = tempfile.gettempdir