blob: 68327af9eedb0a9f1844544e109080560e700cd5 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
# Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com>
# This file is part of the "cmake-common" project.
# For details, see https://github.com/egor-tensin/cmake-common.
# Distributed under the MIT License.
from contextlib import contextmanager
import logging
import os.path
import subprocess
import tempfile
def normalize_path(s):
return os.path.abspath(os.path.normpath(s))
@contextmanager
def setup_logging():
logging.basicConfig(
format='%(asctime)s | %(levelname)s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO)
try:
yield
except Exception as e:
logging.exception(e)
raise
@contextmanager
def cd(path):
cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cwd)
def run(cmd_line):
logging.info('Running executable: %s', cmd_line)
return subprocess.run(cmd_line, check=True)
@contextmanager
def delete_on_error(path):
try:
yield
except:
logging.info('Removing temporary file: %s', path)
os.remove(path)
raise
@contextmanager
def delete(path):
try:
yield
finally:
logging.info('Removing temporary file: %s', path)
os.remove(path)
@contextmanager
def temp_file(contents, **kwargs):
'''Make NamedTemporaryFile usable on Windows.
It can't be opened a second time on Windows, hence this silliness.
'''
tmp = tempfile.NamedTemporaryFile(delete=False, **kwargs)
with tmp as file, delete_on_error(file.name):
path = file.name
logging.info('Writing temporary file: %s', path)
file.write(contents)
with delete(path):
yield path
|