-
Notifications
You must be signed in to change notification settings - Fork 0
/
impulse_paths.py
260 lines (198 loc) · 7.19 KB
/
impulse_paths.py
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import os
import re
from impulse.args import args
from impulse.core import exceptions
EXPORT_DIR = 'GENERATED'
NOT_A_BUILD_TARGET = object()
class Environ():
def __getattr__(self, attr):
return os.environ[attr]
def __getitem__(self, item):
return os.environ[item]
ENV = Environ()
def root():
if 'impulse_root' not in os.environ:
config = f'{ENV.HOME}/.config/impulse/config'
if os.path.exists(config):
with open(config, 'r') as f:
os.environ['impulse_root'] = f.read()
else:
raise LookupError('Impulse has not been initialized.')
return os.environ['impulse_root']
def relative_pwd():
impulse_root = root()
pwd = os.getcwd()
if not pwd:
raise ValueError('Unable to determine current directory')
if pwd.startswith(impulse_root):
return '/' + pwd[len(impulse_root):]
raise ValueError(
f'Impulse must be run inside {impulse_root}\nbut you are in {pwd}')
def output_directory():
return os.path.join(root(), EXPORT_DIR)
class PathException(Exception):
def __init__(self, path, included_from=None):
if included_from:
self._path = f'Invalid Target: {path} Included From: {included_from}'
else:
self._path = f'Invalid Target: {path}'
super(PathException, self).__init__(self._path)
def __repr__(self):
return 'Invalid Target: ' + self._path
class LoggerEnv(dict):
def __init__(self, called_as='module', push_up=None):
self._calls = []
self._called_as = called_as
self._push_up = push_up
def __getitem__(self, value):
return LoggerEnv(called_as=value, push_up=self)
def __call__(self, *args, **kwargs):
kwargs['called_as'] = kwargs.get('called_as', [])
kwargs['called_as'].append(self._called_as)
if self._push_up:
self._push_up(*args, **kwargs)
else:
self._calls.append((args, kwargs))
return []
def __iter__(self):
for call in self._calls:
yield call
class RuleSpec(object):
def __init__(self, target, callspec):
self.type = callspec[1].get('called_as')[0]
self.name = callspec[1].get('name')
output_type = 'BINARIES'
if self.type == 'container':
output_type = 'PACKAGES'
self.output = os.path.join(
output_directory(), output_type, target.target_path[2:], self.name)
class ParsedTarget(object):
def __init__(self, target_name, target_path):
self.target_name = target_name
self.target_path = target_path
def ParseFile(self, _, parser):
parser(self.GetBuildFileForTarget())
def GetBuildFileForTarget(self):
try:
return expand_fully_qualified_path(os.path.join(self.target_path, 'BUILD'))
except exceptions.InvalidPathException as ipe:
raise exceptions.BuildTargetMissing(f'Missing rule: {self.GetFullyQualifiedRulePath()}')
def GetFullyQualifiedRulePath(self):
return self.target_path + ':' + self.target_name
def GetPackagePkgFile(self):
return os.path.join(self.GetPackagePathDirOnly(), self.target_name) + '.zip'
def GetPackagePathDirOnly(self):
return self.target_path[2:]
def GetRuleInfo(self):
build_file = self.GetBuildFileForTarget()
with open(build_file) as f:
compiled = compile(f.read(), build_file, 'exec')
logger = LoggerEnv()
exec(compiled, logger)
for call in logger:
if call[1].get('name', None) == self.target_name:
return RuleSpec(self, call)
def startswith(self, chunk):
return self.GetFullyQualifiedRulePath().startswith(chunk)
def __hash__(self):
return hash(self.GetFullyQualifiedRulePath())
def __eq__(self, other):
if isinstance(other, ParsedTarget):
return self.GetFullyQualifiedRulePath() == other.GetFullyQualifiedRulePath()
return False
def __repr__(self):
return self.GetFullyQualifiedRulePath()
def convert_name_to_build_target(name, loaded_from_dir):
return ParsedTarget(name, loaded_from_dir)
def convert_to_build_target(target, loaded_from_dir, quit_on_err=False):
if isinstance(target, ParsedTarget):
return target
if is_relative_path(target):
return ParsedTarget(target[1:], loaded_from_dir)
if is_fully_qualified_path(target):
_target = target.split(':')
if len(_target) <= 1:
raise PathException(target)
return ParsedTarget(_target[1], _target[0])
if quit_on_err:
raise PathException(target)
return NOT_A_BUILD_TARGET
def expand_fully_qualified_path(path):
if not is_fully_qualified_path(path):
raise exceptions.InvalidPathException(path,
'Path is not repository-relative (missing starting //)')
return os.path.join(root(), path[2:])
def is_fully_qualified_path(path):
return path.startswith('//')
def is_relative_path(path):
return path.startswith(':')
def get_qualified_build_file_dir(build_file_path):
build = re.compile(os.path.join(root(), '(.*)/BUILD'))
defs = re.compile(os.path.join(root(), '(.*)/build_defs.py'))
build = build.match(build_file_path)
defs = defs.match(build_file_path)
if build:
return '//' + build.group(1)
if defs:
return '//' + defs.group(1)
raise exceptions.InvalidPathException(
'targets must be defined in BUILD files or in build_defs.py macros',
build_file_path)
class Platform():
def __init__(self, **kwargs):
self._values = kwargs
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError(attr)
if attr not in self._values:
raise exceptions.PlatformKeyAbsentError(
self._values['platform_target'], attr)
return self._values[attr]
class BuildTarget(args.ArgComplete):
@classmethod
def get_completion_list(cls, stub):
if not stub:
for value in cls._parse_from_local_build_file():
yield ':' + value
elif stub.startswith(':'):
for value in cls._parse_from_local_build_file():
if value.startswith(stub[1:]):
yield value
elif stub.startswith('//'):
yield from cls._parse_partial_target(stub[2:])
elif stub == '/':
yield from cls._parse_partial_target(stub[1:])
@classmethod
def _parse_from_local_build_file(cls):
build_path = os.path.join(os.environ['PWD'], 'BUILD')
if os.path.exists(build_path):
for value in cls._parse_from_build_file(build_path):
yield value
@classmethod
def _parse_from_build_file(cls, path_exists):
with open(path_exists) as f:
compiled = compile(f.read(), path_exists, 'exec')
logger = LoggerEnv()
exec(compiled, logger)
for call in logger:
if 'name' in call[1]:
yield call[1]['name']
@classmethod
def _parse_targets_in_file(cls, path, target_stub):
build_file = os.path.join(path, 'BUILD')
if os.path.exists(build_file):
for target in cls._parse_from_build_file(build_file):
if target.startswith(target_stub):
yield target
@classmethod
def _parse_partial_target(cls, path):
build_root = root()
path = os.path.join(build_root, path)
if ':' in path:
yield from cls._parse_targets_in_file(*path.split(':'))
if ':' not in path:
for directory in args.Directory.get_completion_list(path):
if not directory.endswith('/'):
for entry in cls._parse_targets_in_file(directory, ''):
yield '//' + directory[len(build_root)+1:] + ':' + entry
yield '//' + directory[len(build_root)+1:]