Debian Codegraph @

src/auditwheel/tmpdirs.py

raw
1 """Contexts for *with* statement providing temporary directories"""
2
3 from __future__ import annotations
4
5 import os
6 from pathlib import Path
7 from tempfile import TemporaryDirectory
8 from typing import TYPE_CHECKING
9
10 if TYPE_CHECKING:
11 from types import TracebackType
12
13
14 class InTemporaryDirectory:
15 """Create, return, and change directory to a temporary directory
16
17 Examples
18 --------
19 >>> from pathlib import Path
20 >>> my_cwd = Path.cwd()
21 >>> with InTemporaryDirectory() as tmpdir:
22 ... _ = open('test.txt', 'wt').write('some text')
23 ... assert os.path.isfile('test.txt')
24 ... assert tmpdir.joinpath('test.txt').is_file()
25 >>> tmpdir.exists()
26 False
27 >>> Path.cwd() == my_cwd
28 True
29
30 """
31
32 def __init__(self) -> None:
33 self._tmpdir = TemporaryDirectory()
34 self._name = Path(self._tmpdir.name).resolve(strict=True)
35
36 @property
37 def name(self) -> Path:
38 return self._name
39
40 def __enter__(self) -> Path:
41 self._pwd = Path.cwd()
42 os.chdir(self._name)
43 self._tmpdir.__enter__()
44 return self._name
45
46 def __exit__(
47 self,
48 exc: type[BaseException] | None,
49 value: BaseException | None,
50 tb: TracebackType | None,
51 ) -> None:
52 os.chdir(self._pwd)
53 self._tmpdir.__exit__(exc, value, tb)
54
55
56 class InGivenDirectory:
57 """Change directory to given directory for duration of ``with`` block
58
59 Useful when you want to use `InTemporaryDirectory` for the final test, but
60 you are still debugging. For example, you may want to do this in the end:
61
62 >>> with InTemporaryDirectory() as tmpdir:
63 ... # do something complicated which might break
64 ... pass
65
66 But indeed the complicated thing does break, and meanwhile the
67 ``InTemporaryDirectory`` context manager wiped out the directory with the
68 temporary files that you wanted for debugging. So, while debugging, you
69 replace with something like:
70
71 >>> with InGivenDirectory() as tmpdir: # Use working directory by default
72 ... # do something complicated which might break
73 ... pass
74
75 You can then look at the temporary file outputs to debug what is happening,
76 fix, and finally replace ``InGivenDirectory`` with ``InTemporaryDirectory``
77 again.
78 """
79
80 def __init__(self, path: Path | None = None) -> None:
81 """Initialize directory context manager
82
83 Parameters
84 ----------
85 path : None or Path, optional
86 path to change directory to, for duration of ``with`` block.
87 Defaults to ``Path.cwd()`` if None
88
89 """
90 if path is None:
91 path = Path.cwd()
92 self.name = path.absolute()
93
94 def __enter__(self) -> Path:
95 self._pwd = Path.cwd()
96 if not self.name.is_dir():
97 self.name.mkdir()
98 os.chdir(self.name)
99 return self.name
100
101 def __exit__(
102 self,
103 exc: type[BaseException] | None,
104 value: BaseException | None,
105 tb: TracebackType | None,
106 ) -> None:
107 os.chdir(self._pwd)