Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/tools/tempfiles.py
4128 views
1
# Copyright 2013 The Emscripten Authors. All rights reserved.
2
# Emscripten is available under two separate licenses, the MIT license and the
3
# University of Illinois/NCSA Open Source License. Both these licenses can be
4
# found in the LICENSE file.
5
6
import tempfile
7
import atexit
8
import sys
9
10
from . import utils
11
12
13
class TempFiles:
14
def __init__(self, tmpdir, save_debug_files):
15
self.tmpdir = tmpdir
16
self.save_debug_files = save_debug_files
17
self.to_clean = []
18
19
atexit.register(self.clean)
20
21
def note(self, filename):
22
self.to_clean.append(filename)
23
24
def get(self, suffix, prefix=None):
25
"""Returns a named temp file with the given prefix."""
26
named_file = tempfile.NamedTemporaryFile(dir=self.tmpdir, suffix=suffix, prefix=prefix, delete=False)
27
self.note(named_file.name)
28
return named_file
29
30
def get_file(self, suffix):
31
"""Returns an object representing a RAII-like access to a temp file
32
that has convenient pythonesque semantics for being used via a construct
33
'with TempFiles.get_file(..) as filename:'.
34
The file will be deleted immediately once the 'with' block is exited.
35
"""
36
class TempFileObject:
37
def __enter__(self_):
38
self_.file = tempfile.NamedTemporaryFile(dir=self.tmpdir, suffix=suffix, delete=False)
39
self_.file.close() # NamedTemporaryFile passes out open file handles, but callers prefer filenames (and open their own handles manually if needed)
40
return self_.file.name
41
42
def __exit__(self_, _type, _value, _traceback):
43
if not self.save_debug_files:
44
utils.delete_file(self_.file.name)
45
return TempFileObject()
46
47
def get_dir(self):
48
"""Returns a named temp directory with the given prefix."""
49
directory = tempfile.mkdtemp(dir=self.tmpdir)
50
self.note(directory)
51
return directory
52
53
def clean(self):
54
if self.save_debug_files:
55
print(f'not cleaning up temp files since in debug-save mode, see them in {self.tmpdir}', file=sys.stderr)
56
return
57
for filename in self.to_clean:
58
utils.delete_file(filename)
59
self.to_clean = []
60
61