-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
210 lines (160 loc) · 5.59 KB
/
common.py
File metadata and controls
210 lines (160 loc) · 5.59 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Copyright (c) 2022 Daumantas Kavolis
buildtools is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
buildtools is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with buildtools. If not, see <http: //www.gnu.org/licenses/>.
"""
from __future__ import annotations
import argparse
import contextlib
import logging
import json
import os
import re
import xml.etree.ElementTree as ET
from typing import Any, Dict, Mapping, Optional, TypeVar
import pathlib
from buildtools.datatypes import PathLike, Config
VAR_PATTERN = re.compile(r"\$\(([\w\_\-\:\d]+)\)")
SILENT_VARS = {
"Configuration",
}
K = TypeVar("K")
V = TypeVar("V")
logger = logging.getLogger(__name__)
def recursive_update(left: Dict[K, V], right: Dict[K, V]) -> None:
for k, v in right.items():
lv = left.get(k, None) # type: ignore
if isinstance(lv, dict):
recursive_update(lv, v) # type: ignore
else:
left[k] = v
def load_config(filename: PathLike) -> Config:
filename = pathlib.Path(filename).absolute()
with open(filename) as file:
data: Dict[str, Any] = json.load(file)
user_file = filename.with_suffix(filename.suffix + ".user")
if user_file.exists():
with open(user_file) as file:
user_data = json.load(file)
recursive_update(data, user_data)
file_dir = filename.parent
if "root" in data:
root = data["root"]
if not os.path.isabs(root):
root = file_dir / root
else:
root = file_dir
data["root"] = root
if "build_props" in data:
data["build_props"] = root / data["build_props"]
data.setdefault("variables", {}).update(
load_variables(root, data.get("build_props", None))
)
for name, value in data["variables"].items():
if not isinstance(value, str):
continue
data["variables"][name] = replace_variables(value, data["variables"])
return Config(**data)
def find_solution_dir(root: Optional[PathLike] = None) -> pathlib.Path:
if root is None:
root = pathlib.Path.cwd()
else:
root = pathlib.Path(root)
counter = 0
while not root.glob("*.sln"):
root = root.parent
if counter > 20:
raise FileNotFoundError("Could not find .sln file")
else:
counter += 1
return root
def get_solution_vars(
root: Optional[PathLike] = None,
) -> Dict[str, str]:
sol_dir = find_solution_dir(root)
data: Dict[str, str] = {"SolutionDir": str(sol_dir)}
sol_files = list(sol_dir.glob("*.sln"))
if sol_files:
sol_file = sol_files[0]
data["SolutionFileName"] = sol_file.name
data["SolutionName"] = sol_file.stem
return data
def load_build_props(filename: PathLike) -> Dict[str, str]:
filename = pathlib.Path(filename)
tree = ET.parse(filename)
root = tree.getroot()
data: Dict[str, str] = {}
for section in root:
if section.tag == "Import" and "Project" in section.attrib:
project = pathlib.Path(section.attrib["Project"])
if not project.is_absolute():
project = filename.parent / project
if project.exists():
data.update(load_build_props(project))
elif section.tag == "PropertyGroup":
for item in section:
if item.text is None:
continue
data[item.tag] = item.text
return data
def load_variables(
root: Optional[PathLike] = None, filename: Optional[PathLike] = None
) -> Dict[str, str]:
data = get_solution_vars(root)
if filename is not None:
data.update(load_build_props(filename))
for key, value in data.items():
data[key] = replace_variables(value, data)
return data
def replace_variables(string: str, var_map: Mapping[str, Any]) -> str:
def _re_sub(matchobj: re.Match[str]):
identifier = matchobj.group(1)
value: Any = None
if identifier.startswith("env:"):
value = os.environ.get(identifier[4:], None)
else:
value = var_map.get(identifier, None)
if value is None:
if identifier not in SILENT_VARS:
logger.warn("Variable %s not found!", identifier)
return ""
return str(value)
newstr, subs = re.subn(VAR_PATTERN, _re_sub, string)
while subs > 0:
newstr, subs = re.subn(VAR_PATTERN, _re_sub, newstr)
return newstr
def resolve(string: str, config: Config) -> str:
return replace_variables(string, config.variables)
def resolve_path(string: PathLike, config: Config) -> pathlib.Path:
return pathlib.Path(resolve(str(string), config))
@contextlib.contextmanager
def chdir(dirname: PathLike):
old = os.getcwd()
try:
os.chdir(dirname)
yield
finally:
os.chdir(old)
def add_config_option(parser: argparse.ArgumentParser):
parser.add_argument(
"-f",
"--file",
help="Path to configuration file",
dest="config",
default="config.json",
)
def main():
config = load_config("config.json")
print("config: ", config)
if __name__ == "__main__":
main()