0
|
1 |
#
|
|
2 |
# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
|
|
3 |
# All rights reserved.
|
|
4 |
# This component and the accompanying materials are made available
|
|
5 |
# under the terms of "Eclipse Public License v1.0"
|
|
6 |
# which accompanies this distribution, and is available
|
|
7 |
# at the URL "http://www.eclipse.org/legal/epl-v10.html".
|
|
8 |
#
|
|
9 |
# Initial Contributors:
|
|
10 |
# Nokia Corporation - initial contribution.
|
|
11 |
#
|
|
12 |
# Contributors:
|
|
13 |
#
|
|
14 |
# Description:
|
|
15 |
#
|
|
16 |
##
|
|
17 |
# @author Teemu Rytkonen
|
|
18 |
|
|
19 |
import sys
|
|
20 |
import os
|
|
21 |
import logging
|
|
22 |
import inspect
|
3
|
23 |
import re
|
|
24 |
import codecs
|
0
|
25 |
|
3
|
26 |
from cone.public import exceptions, utils, api, settings, rules, parsecontext
|
0
|
27 |
import _plugin_reader
|
4
|
28 |
from cone.public.exceptions import NotFound
|
|
29 |
|
0
|
30 |
|
|
31 |
debug = 0
|
|
32 |
"""
|
|
33 |
Implementation specific settings can be overriden in the global impl_settings variable
|
|
34 |
"""
|
|
35 |
|
|
36 |
AUTOCONFIG_CONFML = "autodata.confml"
|
|
37 |
|
|
38 |
def get_autoconfig(configuration):
|
|
39 |
"""
|
|
40 |
Return the "automatic" configuration for storing temporary run-time ConfML
|
|
41 |
features and values.
|
|
42 |
"""
|
|
43 |
lastconfig = configuration.get_last_configuration()
|
|
44 |
if lastconfig.get_path() != AUTOCONFIG_CONFML:
|
|
45 |
logging.getLogger('cone').debug('Adding autodata configuration %s' % AUTOCONFIG_CONFML)
|
|
46 |
configuration.create_configuration(AUTOCONFIG_CONFML)
|
|
47 |
|
|
48 |
lastconfig = configuration.get_last_configuration()
|
|
49 |
assert lastconfig.get_path() == AUTOCONFIG_CONFML
|
|
50 |
return lastconfig
|
|
51 |
|
|
52 |
def get_supported_file_extensions():
|
|
53 |
"""
|
|
54 |
Return a list of all supported ImplML file extension.
|
|
55 |
|
|
56 |
Implementations are only attempted to be read from files with these
|
|
57 |
extensions.
|
|
58 |
"""
|
|
59 |
return ImplFactory.get_supported_file_extensions()
|
|
60 |
|
|
61 |
def get_supported_namespaces():
|
|
62 |
"""
|
|
63 |
Returns a list of all supported ImplML namespaces.
|
|
64 |
"""
|
|
65 |
return ImplFactory.get_reader_dict().keys()
|
|
66 |
|
|
67 |
def is_temp_feature(feature):
|
|
68 |
"""
|
|
69 |
Return whether the given feature is a temporary feature.
|
|
70 |
"""
|
|
71 |
return hasattr(feature, _plugin_reader.TEMP_FEATURE_MARKER_VARNAME)
|
|
72 |
|
3
|
73 |
def uses_ref(refs, impl_refs):
|
|
74 |
"""
|
|
75 |
Compare two lists of setting references and return whether any of the
|
|
76 |
references in ``refs`` is used in ``impl_refs``.
|
|
77 |
"""
|
|
78 |
for ref in refs:
|
|
79 |
for impl_ref in impl_refs:
|
|
80 |
if ref.startswith(impl_ref):
|
|
81 |
if len(ref) == len(impl_ref):
|
|
82 |
return True
|
|
83 |
elif ref[len(impl_ref)] == '.':
|
|
84 |
return True
|
|
85 |
return False
|
|
86 |
|
|
87 |
class GenerationContext(rules.DefaultContext):
|
0
|
88 |
"""
|
|
89 |
Context object that can be used for passing generation-scope
|
|
90 |
data to implementation instances.
|
|
91 |
"""
|
|
92 |
|
3
|
93 |
def __init__(self, **kwargs):
|
0
|
94 |
#: The tags used in this generation context
|
|
95 |
#: (i.e. the tags passed from command line)
|
3
|
96 |
self.tags = kwargs.get('tags', {})
|
0
|
97 |
|
|
98 |
#: The tags policy used in this generation context
|
3
|
99 |
self.tags_policy = kwargs.get('tags_policy', "OR")
|
0
|
100 |
|
|
101 |
#: A dictionary that implementation instances can use to
|
|
102 |
#: pass any data between each other
|
|
103 |
self.impl_data_dict = {}
|
|
104 |
|
3
|
105 |
#: A string for the phase of the generation.
|
|
106 |
#: If None, no filtering based on phase is done when
|
|
107 |
#: running the implementations
|
|
108 |
self.phase = kwargs.get('phase', None)
|
0
|
109 |
|
|
110 |
#: a list of rule results
|
|
111 |
self.results = []
|
|
112 |
|
|
113 |
#: a pointer to the configuration
|
3
|
114 |
self.configuration = kwargs.get('configuration', None)
|
|
115 |
|
|
116 |
#: If True, then all implementation filtering done by
|
|
117 |
#: should_run() is disabled, and it always returns True.
|
|
118 |
self.filtering_disabled = False
|
|
119 |
|
|
120 |
#: if True, then the execution flow should normal except
|
|
121 |
#: no output files are actually generated
|
|
122 |
self.dry_run= kwargs.get('dry_run', None)
|
|
123 |
|
|
124 |
#: the output folder for generation
|
|
125 |
#: ensure already here that the output exists
|
|
126 |
self.output= kwargs.get('output', 'output')
|
|
127 |
|
|
128 |
#: List of references of the settings that have been modified in
|
|
129 |
#: listed layers and should trigger an implementation to be executed.
|
|
130 |
#: None if ref filtering is not used
|
|
131 |
self.changed_refs = kwargs.get('changed_refs', None)
|
|
132 |
|
|
133 |
|
|
134 |
#: A boolean flag to determine whether to use ref filtering or not
|
|
135 |
self.filter_by_refs = kwargs.get('filter_by_refs', False)
|
|
136 |
|
|
137 |
#: Temp features
|
|
138 |
self.temp_features = kwargs.get('temp_features', [])
|
|
139 |
|
|
140 |
#: Executed implementation objects. This is a set so that a
|
|
141 |
#: implementation would exist only once in it. Even if it executed
|
|
142 |
#: more than once. The generation_output will show the actual
|
|
143 |
#: output several times if a implementation is executed several times.
|
|
144 |
self.executed = set()
|
|
145 |
|
|
146 |
#: Set of all implementation objects in the configuration context
|
|
147 |
self.impl_set = kwargs.get('impl_set', ImplSet())
|
|
148 |
|
|
149 |
#: Generation output elements as a list
|
|
150 |
self.generation_output = []
|
0
|
151 |
|
4
|
152 |
#: possible log element
|
3
|
153 |
self.log = []
|
|
154 |
self.log_file = ""
|
4
|
155 |
|
3
|
156 |
def __getstate__(self):
|
4
|
157 |
state = self.__dict__.copy()
|
3
|
158 |
state['impl_data_dict'] = {}
|
|
159 |
return state
|
|
160 |
|
|
161 |
def eval(self, ast, expression, value, **kwargs):
|
0
|
162 |
"""
|
|
163 |
eval for rule evaluation against the context
|
|
164 |
"""
|
|
165 |
pass
|
|
166 |
|
|
167 |
def handle_terminal(self, expression):
|
|
168 |
"""
|
|
169 |
Handle a terminal object
|
|
170 |
"""
|
|
171 |
try:
|
3
|
172 |
if isinstance(expression, basestring):
|
|
173 |
try:
|
|
174 |
dview = self.configuration.get_default_view()
|
|
175 |
return dview.get_feature(expression).value
|
|
176 |
except Exception, e:
|
|
177 |
logging.getLogger('cone').error("Could not dereference feature %s. Exception %s" % (expression, e))
|
|
178 |
raise e
|
0
|
179 |
except Exception,e:
|
|
180 |
logging.getLogger('cone').error("Exception with expression %s: %s" % (expression, e))
|
|
181 |
raise e
|
3
|
182 |
|
|
183 |
def convert_value(self, value):
|
|
184 |
try:
|
|
185 |
# Handle some special literals
|
|
186 |
if value == 'true': return True
|
|
187 |
if value == 'false': return False
|
|
188 |
if value == 'none': return None
|
|
189 |
|
|
190 |
# Values can be any Python literals, so eval() the string to
|
|
191 |
# get the value
|
|
192 |
return eval(value)
|
|
193 |
except Exception:
|
|
194 |
ref_regex = re.compile('^[\w\.\*]*$', re.UNICODE)
|
|
195 |
if ref_regex.match(value) is None:
|
|
196 |
raise RuntimeError("Could not evaluate '%s'" % value)
|
|
197 |
else:
|
|
198 |
raise RuntimeError("Could not evaluate '%s'. Did you mean a setting reference and forgot to use ${}?" % value)
|
|
199 |
|
|
200 |
def set(self, expression, value, **kwargs):
|
|
201 |
log = logging.getLogger('cone.ruleml')
|
|
202 |
try:
|
|
203 |
feature = self.configuration.get_default_view().get_feature(expression)
|
|
204 |
feature.set_value(value)
|
|
205 |
|
|
206 |
relation = kwargs.get('relation')
|
|
207 |
if relation:
|
|
208 |
log.info("Set %s = %r from %r" % (expression, value, relation))
|
|
209 |
else:
|
|
210 |
log.info("Set %s = %r" % (expression, value))
|
|
211 |
|
|
212 |
refs = [feature.fqr]
|
|
213 |
if feature.is_sequence():
|
|
214 |
refs = ["%s.%s" % (feature.fqr,subref) for subref in feature.list_features()]
|
|
215 |
|
|
216 |
self.add_changed_refs(refs, relation)
|
0
|
217 |
|
3
|
218 |
if relation:
|
|
219 |
self.generation_output.append(GenerationOutput(expression,
|
|
220 |
relation,
|
|
221 |
type='ref'))
|
|
222 |
return True
|
|
223 |
except exceptions.NotFound,e:
|
|
224 |
log.error('Set operation for %s failed, because feature with that reference was not found! Exception %s', expression, e)
|
|
225 |
raise e
|
|
226 |
|
|
227 |
def should_run(self, impl, log_debug_message=True):
|
|
228 |
"""
|
|
229 |
Return True if the given implementation should be run (generated).
|
|
230 |
|
|
231 |
Also optionally log a message that the implementation is
|
|
232 |
filtered out based on phase, tags or setting references.
|
|
233 |
|
|
234 |
Calling this method also affects the output of executed_impls. Every
|
|
235 |
implementation for which a call to this method has returned True
|
|
236 |
will also be in that list.
|
|
237 |
|
|
238 |
@param impl: The implementation to check.
|
|
239 |
@param log_debug_message: If True, a debug message will be logged
|
|
240 |
if the implementation is filtered out based on phase, tags
|
|
241 |
or setting references.
|
|
242 |
"""
|
|
243 |
if self.filtering_disabled:
|
|
244 |
return True
|
|
245 |
|
|
246 |
if isinstance(impl, ImplContainer):
|
|
247 |
# Don't perform any filtering on containers
|
|
248 |
return True
|
|
249 |
|
|
250 |
impl_phases = impl.invocation_phase()
|
|
251 |
if isinstance(impl_phases, basestring):
|
|
252 |
impl_phases = [impl_phases]
|
|
253 |
|
|
254 |
if self.phase is not None and self.phase not in impl_phases:
|
|
255 |
# Don't log a debug message for phase-based filtering to
|
|
256 |
# avoid unnecessary spamming (uncomment if necessary
|
|
257 |
# during development)
|
|
258 |
#logging.getLogger('cone').debug('Filtered out based on phase: %r (%r not in %r)' % (impl, self.phase, impl_phases))
|
|
259 |
return False
|
|
260 |
if self.tags and not impl.has_tag(self.tags, self.tags_policy):
|
|
261 |
if log_debug_message:
|
|
262 |
logging.getLogger('cone').debug('Filtered out based on tags: %r' % impl)
|
|
263 |
return False
|
|
264 |
if self.filter_by_refs and self.changed_refs and impl.has_ref(self.changed_refs) == False:
|
|
265 |
if log_debug_message:
|
|
266 |
logging.getLogger('cone').debug('Filtered out based on refs: %r' % impl)
|
|
267 |
return False
|
|
268 |
|
|
269 |
# Assumption is that when a implementation should be run it is added to the executed pile
|
|
270 |
self.executed.add(impl)
|
|
271 |
return True
|
|
272 |
|
|
273 |
def have_run(self, impl):
|
|
274 |
"""
|
|
275 |
This function will add the given implementation
|
|
276 |
outputs to the list of generation_outputs.
|
|
277 |
"""
|
|
278 |
# Add outputs only from actual leaf implementations
|
|
279 |
# not from ImplContainers
|
|
280 |
if not isinstance(impl, ImplContainer):
|
|
281 |
self.generation_output += impl.get_outputs()
|
|
282 |
|
|
283 |
def create_file(self, filename, **kwargs):
|
|
284 |
"""
|
|
285 |
Create a file handle under the output folder. Also adds the output file to the generation outputs list.
|
|
286 |
@param filename: the filename with path, that is created under the output folder of the generation context.
|
|
287 |
@param **kwargs: the keyword arguments that can provide essential information for the GenerationOutput
|
|
288 |
object creation. They should at least contain the implementation argument for the GenerationObject.
|
|
289 |
@param **kwargs implementation: the implementation object that created this output
|
|
290 |
@param **kwargs mode: the mode of the output file created
|
|
291 |
@param **kwargs encoding: the possible encoding of the output file. When this parameter is given the create_file will
|
|
292 |
use codecs.open method to create the file.
|
|
293 |
@return: the filehandle of the new file.
|
|
294 |
"""
|
|
295 |
|
|
296 |
implml = kwargs.get('implementation', None)
|
|
297 |
mode = kwargs.get('mode', 'wb')
|
|
298 |
encoding = kwargs.get('encoding', None)
|
|
299 |
targetfile = os.path.normpath(os.path.join(self.output, filename))
|
|
300 |
|
|
301 |
if not os.path.exists(os.path.dirname(targetfile)):
|
|
302 |
os.makedirs(os.path.dirname(targetfile))
|
|
303 |
|
|
304 |
if not encoding:
|
|
305 |
outfile = open(targetfile, mode)
|
|
306 |
else:
|
|
307 |
outfile = codecs.open(targetfile, mode, encoding)
|
|
308 |
# Add the generation output
|
|
309 |
self.generation_output.append(GenerationOutput(utils.resourceref.norm(targetfile),
|
|
310 |
implml,
|
|
311 |
phase=self.phase,
|
|
312 |
type='file',
|
|
313 |
output=self.output))
|
|
314 |
return outfile
|
|
315 |
|
|
316 |
def add_file(self, filename, **kwargs):
|
|
317 |
"""
|
|
318 |
Add a file to the generation outputs list.
|
|
319 |
@param filename: the filename with path, that is added. If the path is a relative path
|
|
320 |
the path is added under the output folder of the generation context. Absolute path is added as such and not manipulated.
|
|
321 |
@param **kwargs: the keyword arguments that can provide essential information for the GenerationOutput
|
|
322 |
object creation. They should at least contain the implementation argument for the GenerationObject.
|
|
323 |
@return: None
|
|
324 |
"""
|
|
325 |
if not os.path.isabs(filename):
|
|
326 |
targetfile = os.path.join(self.output, filename)
|
|
327 |
else:
|
|
328 |
targetfile = filename
|
|
329 |
# Add the generation output
|
|
330 |
self.generation_output.append(GenerationOutput(utils.resourceref.norm(targetfile),
|
|
331 |
kwargs.get('implementation'),
|
|
332 |
phase=self.phase,
|
|
333 |
type='file',
|
|
334 |
output=self.output))
|
|
335 |
|
|
336 |
def get_output(self, **kwargs):
|
|
337 |
"""
|
|
338 |
Get a output object from the generation_output list.
|
|
339 |
@param **kwargs: the keyword arguments.
|
|
340 |
@param implml_type: a filter for generation outputs to filter generation outputs only with given implementation type.
|
|
341 |
@return: list of generation output objects
|
|
342 |
"""
|
|
343 |
filters = []
|
|
344 |
if kwargs.get('implml_type'):
|
|
345 |
filters.append(lambda x: x.implementation and x.implementation.IMPL_TYPE_ID == kwargs.get('implml_type'))
|
|
346 |
|
|
347 |
outputs = []
|
|
348 |
# go through all the generation_output items with all provided filters
|
|
349 |
# if the item passes all filters add it to the outputs list
|
|
350 |
for item in self.generation_output:
|
|
351 |
passed = True
|
|
352 |
for filter in filters:
|
|
353 |
if not filter(item):
|
|
354 |
passed = False
|
|
355 |
continue
|
|
356 |
if passed:
|
|
357 |
outputs.append(item)
|
|
358 |
return outputs
|
|
359 |
|
|
360 |
def add_changed_refs(self, refs, implml=None):
|
|
361 |
"""
|
|
362 |
Add changed refs to the current set of changed refs if necessary.
|
|
363 |
|
|
364 |
If there are new refs and they are added, log also a debug message.
|
|
365 |
"""
|
|
366 |
if self.changed_refs is None:
|
|
367 |
return
|
|
368 |
for ref in refs:
|
|
369 |
self.add_changed_ref(ref, implml)
|
|
370 |
|
|
371 |
def add_changed_ref(self, ref, implml=None):
|
|
372 |
"""
|
|
373 |
Add changed ref to the current set of changed refs if necessary.
|
|
374 |
|
|
375 |
If there are new refs and they are added, log also a debug message.
|
|
376 |
"""
|
|
377 |
if self.changed_refs is None:
|
|
378 |
return
|
|
379 |
|
|
380 |
if ref not in self.changed_refs:
|
|
381 |
self.changed_refs.append(ref)
|
|
382 |
logging.getLogger('cone').debug('Added ref %s from implml %s' % (ref, implml))
|
|
383 |
|
|
384 |
def get_refs_with_no_output(self, refs=None):
|
|
385 |
if not refs:
|
|
386 |
refs = self.changed_refs
|
|
387 |
if refs:
|
|
388 |
# create a set from the changed refs
|
|
389 |
# then remove the refs that have a generation output
|
|
390 |
# and return the remaining refs as a list
|
|
391 |
refsset = set(refs)
|
|
392 |
implrefs = set()
|
|
393 |
for output in self.generation_output:
|
|
394 |
if output.implementation:
|
|
395 |
implrefs |= set(output.implementation.get_refs() or [])
|
|
396 |
if output.type == 'ref':
|
|
397 |
implrefs.add(output.name)
|
|
398 |
# Add all sequence subfeatures to the list of implementation references
|
|
399 |
dview = self.configuration.get_default_view()
|
|
400 |
for fea in dview.get_features(list(implrefs)):
|
|
401 |
if fea.is_sequence():
|
|
402 |
seqfeas = ["%s.%s" % (fea.fqr,fearef) for fearef in fea.get_sequence_parent().list_features()]
|
|
403 |
implrefs |= set(seqfeas)
|
|
404 |
|
|
405 |
refsset = refsset - implrefs
|
|
406 |
return sorted(list(refsset))
|
|
407 |
else:
|
|
408 |
return []
|
|
409 |
|
|
410 |
def get_refs_with_no_implementation(self, refs=None):
|
|
411 |
if not refs:
|
|
412 |
refs = self.changed_refs
|
|
413 |
if refs:
|
|
414 |
# create a set from the changed refs
|
|
415 |
# then remove the refs that have a generation output
|
|
416 |
# and return the remaining refs as a list
|
|
417 |
refsset = set(refs)
|
|
418 |
implrefs = set(self.impl_set.get_implemented_refs())
|
|
419 |
logging.getLogger('cone').debug("changed_refs: %s" % refsset)
|
|
420 |
logging.getLogger('cone').debug("implrefs: %s" % implrefs)
|
|
421 |
# Add all sequence subfeatures to the list of implementation references
|
|
422 |
dview = self.configuration.get_default_view()
|
|
423 |
for fea in dview.get_features(list(implrefs)):
|
|
424 |
if fea.is_sequence():
|
|
425 |
seqfeas = ["%s.%s" % (fea.fqr,fearef) for fearef in fea.get_sequence_parent().list_features()]
|
|
426 |
implrefs |= set(seqfeas)
|
|
427 |
|
|
428 |
refsset = refsset - implrefs
|
|
429 |
return sorted(list(refsset))
|
|
430 |
else:
|
|
431 |
return []
|
|
432 |
|
|
433 |
@property
|
|
434 |
def executed_impls(self):
|
|
435 |
"""
|
|
436 |
List of all executed implementations (implementations for which
|
|
437 |
a call to should_run() has returned True).
|
|
438 |
"""
|
|
439 |
return list(self.executed)
|
|
440 |
|
|
441 |
@property
|
|
442 |
def features(self):
|
|
443 |
"""
|
|
444 |
return the default view of the context configuration to access all features of the configuration.
|
|
445 |
"""
|
|
446 |
return self.configuration.get_default_view()
|
|
447 |
|
|
448 |
def grep_log(self, entry):
|
|
449 |
"""
|
|
450 |
Grep the self.log entries for given entry and return a list of tuples with line (index, entry)
|
|
451 |
"""
|
|
452 |
return utils.grep_tuple(entry, self.log)
|
|
453 |
|
|
454 |
class MergedContext(GenerationContext):
|
|
455 |
def __init__(self, contexts):
|
|
456 |
self.contexts = contexts
|
|
457 |
self.configuration = None
|
|
458 |
self.changed_refs = []
|
|
459 |
self.temp_features = []
|
|
460 |
self.executed = set()
|
|
461 |
self.impl_set = ImplSet()
|
|
462 |
self.impl_dict = {}
|
|
463 |
self.generation_output = []
|
|
464 |
self.log = []
|
|
465 |
self.log_files = []
|
|
466 |
self.outputs = {}
|
|
467 |
for context in contexts:
|
|
468 |
self.changed_refs += context.changed_refs
|
|
469 |
self.temp_features += context.temp_features
|
|
470 |
self.configuration = context.configuration
|
|
471 |
self.executed |= context.executed
|
|
472 |
self.generation_output += context.generation_output
|
|
473 |
self.log += context.log
|
|
474 |
self.log_files.append(context.log_file)
|
|
475 |
for output in context.generation_output:
|
|
476 |
self.outputs[output.name] = output
|
|
477 |
for impl in context.impl_set:
|
|
478 |
self.impl_dict[impl.ref] = impl
|
|
479 |
self.impl_set = ImplSet(self.impl_dict.values())
|
|
480 |
|
|
481 |
def get_changed_refs(self, **kwargs):
|
|
482 |
changed_refs = set()
|
|
483 |
operation = kwargs.get('operation', 'union')
|
|
484 |
for context in self.contexts:
|
|
485 |
if not changed_refs:
|
|
486 |
# set the base set from the first context
|
|
487 |
changed_refs = set(context.changed_refs)
|
|
488 |
else:
|
|
489 |
if operation == 'union':
|
|
490 |
changed_refs |= set(context.changed_refs)
|
|
491 |
elif operation == 'intersection':
|
|
492 |
changed_refs &= set(context.changed_refs)
|
|
493 |
elif operation == 'difference':
|
|
494 |
changed_refs -= set(context.changed_refs)
|
|
495 |
elif operation == 'symmetric_difference':
|
|
496 |
changed_refs ^= set(context.changed_refs)
|
|
497 |
else:
|
|
498 |
raise exceptions.NotSupportedException('Illegal opration %s for get_changed_refs!' % operation)
|
|
499 |
#remove temp features
|
|
500 |
if kwargs.get('ignore_temps'):
|
|
501 |
changed_refs = changed_refs - set(self.temp_features)
|
|
502 |
return list(changed_refs)
|
|
503 |
|
|
504 |
class GenerationOutput(object):
|
|
505 |
"""
|
|
506 |
A GenerationOutput object that is intended to be part of GenerationContext.generation_outputs.
|
|
507 |
The data should hold information about
|
|
508 |
"""
|
|
509 |
TYPES = ['file', 'ref']
|
|
510 |
|
|
511 |
def __init__(self, name, implementation, **kwargs):
|
|
512 |
"""
|
|
513 |
@param name: the name of the output as string
|
|
514 |
@param implementation: the implementation object that generated this output
|
|
515 |
@param type: the type of the output that could be file|ref
|
|
516 |
"""
|
|
517 |
|
|
518 |
""" The name of the output """
|
|
519 |
self.name = name
|
|
520 |
|
|
521 |
""" The implementation object that generated the output """
|
|
522 |
self.implementation = implementation
|
|
523 |
|
|
524 |
""" The type of the output """
|
|
525 |
self.type = kwargs.get('type', None)
|
|
526 |
|
|
527 |
""" phase of the generation """
|
|
528 |
self.phase = kwargs.get('phase', None)
|
|
529 |
|
|
530 |
""" the context output path of the generation """
|
|
531 |
self.output = kwargs.get('output', None)
|
|
532 |
|
|
533 |
""" the possible exception """
|
|
534 |
self.exception = kwargs.get('exception', None)
|
|
535 |
|
|
536 |
def __str__(self):
|
|
537 |
return "%s(%s, %s)" % (self.__class__.__name__, self.name, self.implementation)
|
|
538 |
|
|
539 |
@property
|
|
540 |
def filename(self):
|
|
541 |
"""
|
|
542 |
return the filename part of the the output name. Valid only if the output name is a path.
|
|
543 |
"""
|
|
544 |
return os.path.basename(self.name)
|
|
545 |
|
|
546 |
@property
|
|
547 |
def relpath(self):
|
|
548 |
"""
|
|
549 |
return the relative name part of the the output name, with relation to the context output path.
|
|
550 |
"""
|
|
551 |
return utils.relpath(self.name, self.output)
|
|
552 |
|
|
553 |
@property
|
|
554 |
def abspath(self):
|
|
555 |
"""
|
|
556 |
return the relative name part of the the output name, with relation to the context output path.
|
|
557 |
"""
|
|
558 |
if os.path.isabs(self.name):
|
|
559 |
return os.path.normpath(self.name)
|
|
560 |
else:
|
|
561 |
return os.path.abspath(os.path.normpath(self.name))
|
0
|
562 |
|
|
563 |
class FlatComparisonResultEntry(object):
|
|
564 |
"""
|
|
565 |
Class representing a result entry for a flat implementation
|
|
566 |
comparison.
|
|
567 |
|
|
568 |
Contains the following members:
|
|
569 |
Member Description
|
|
570 |
file Implementation file
|
|
571 |
impl_type Implementation type (e.g. 'crml', 'gcfml')
|
|
572 |
id Entry ID (e.g. CRML repository UID)
|
|
573 |
sub_id Entry sub-ID if applicable (e.g. CRML key UID)
|
|
574 |
value_id Implementation-specific value identifier
|
|
575 |
source_value Value in the source implementation
|
|
576 |
target_value Value in the target implementation
|
|
577 |
|
|
578 |
data Any extra data (implementation-specific)
|
|
579 |
"""
|
|
580 |
|
|
581 |
VARNAMES = ['file', 'impl_type', 'id', 'sub_id', 'value_id', 'source_value', 'target_value']
|
|
582 |
|
|
583 |
def __init__(self, **kwargs):
|
|
584 |
for varname in self.VARNAMES:
|
|
585 |
setattr(self, varname, kwargs.get(varname))
|
|
586 |
self.data = kwargs.get('data')
|
|
587 |
|
|
588 |
def __repr__(self):
|
|
589 |
var_entries = []
|
|
590 |
for varname in self.VARNAMES:
|
|
591 |
var_entries.append('%s=%r' % (varname, getattr(self, varname)))
|
|
592 |
return "FlatComparisonResultEntry(%s)" % ', '.join(var_entries)
|
|
593 |
|
|
594 |
def __eq__(self, other):
|
|
595 |
if type(self) is not type(other):
|
|
596 |
return False
|
|
597 |
for varname in self.VARNAMES:
|
|
598 |
if getattr(self, varname) != getattr(other, varname):
|
|
599 |
return False
|
|
600 |
return True
|
|
601 |
|
|
602 |
def __ne__(self, other):
|
|
603 |
return not (self == other)
|
|
604 |
|
|
605 |
def __lt__(self, other):
|
|
606 |
for varname in self.VARNAMES:
|
|
607 |
self_val = getattr(self, varname)
|
|
608 |
other_val = getattr(other, varname)
|
|
609 |
if self_val < other_val: return True
|
|
610 |
elif self_val == other_val: pass
|
|
611 |
else: return False
|
|
612 |
return False
|
|
613 |
|
|
614 |
class DuplicateImplementationEntry(object):
|
|
615 |
"""
|
|
616 |
Class representing an entry of duplicate implementation instances
|
|
617 |
found in a comparison.
|
|
618 |
"""
|
|
619 |
VARNAMES = ['impl_type', 'id', 'files_in_source', 'files_in_target']
|
|
620 |
|
|
621 |
def __init__(self, **kwargs):
|
|
622 |
self.impl_type = kwargs.get('impl_type')
|
|
623 |
self.id = kwargs.get('id')
|
|
624 |
self.files_in_source = kwargs.get('files_in_source', [])
|
|
625 |
self.files_in_target = kwargs.get('files_in_target', [])
|
|
626 |
|
|
627 |
def __repr__(self):
|
|
628 |
var_entries = []
|
|
629 |
for varname in self.VARNAMES:
|
|
630 |
val = getattr(self, varname)
|
|
631 |
if isinstance(val, list): val = sorted(val)
|
|
632 |
var_entries.append('%s=%r' % (varname, val))
|
|
633 |
return "DuplicateImplementationEntry(%s)" % ', '.join(var_entries)
|
|
634 |
|
|
635 |
def __eq__(self, other):
|
|
636 |
if type(self) is not type(other):
|
|
637 |
return False
|
|
638 |
return self.impl_type == other.impl_type \
|
|
639 |
and self.impl_type == other.impl_type \
|
|
640 |
and sorted(self.files_in_source) == sorted(other.files_in_source) \
|
|
641 |
and sorted(self.files_in_target) == sorted(other.files_in_target)
|
|
642 |
|
|
643 |
def __ne__(self, other):
|
|
644 |
return not (self == other)
|
|
645 |
|
|
646 |
def __lt__(self, other):
|
|
647 |
for varname in self.VARNAMES:
|
|
648 |
self_val = getattr(self, varname)
|
|
649 |
other_val = getattr(other, varname)
|
|
650 |
if isinstance(self_val, list): self_val = sorted(self_val)
|
|
651 |
if isinstance(other_val, list): other_val = sorted(other_val)
|
|
652 |
if self_val < other_val: return True
|
|
653 |
elif self_val == other_val: pass
|
|
654 |
else: return False
|
|
655 |
return False
|
|
656 |
|
|
657 |
class FlatComparisonResult(object):
|
|
658 |
"""
|
|
659 |
Class representing a flat comparison result.
|
|
660 |
|
|
661 |
Each member is a list of FlatComparisonResultEntry
|
|
662 |
objects, except for 'duplicate', which contains
|
|
663 |
DuplicateImplementationEntry objects.
|
|
664 |
|
|
665 |
Note that the entry members 'value_id', 'source_value' and
|
|
666 |
'target_value' are irrelevant in the 'only_in_source' and
|
|
667 |
'only_in_target' lists, and will always be None.
|
|
668 |
"""
|
|
669 |
def __init__(self, **kwargs):
|
|
670 |
self.only_in_source = kwargs.get('only_in_source', [])
|
|
671 |
self.only_in_target = kwargs.get('only_in_target', [])
|
|
672 |
self.modified = kwargs.get('modified', [])
|
|
673 |
self.duplicate = kwargs.get('duplicate', [])
|
|
674 |
|
|
675 |
|
|
676 |
def extend(self, other):
|
|
677 |
"""
|
|
678 |
Extend this comparison result with another one.
|
|
679 |
"""
|
|
680 |
if not isinstance(other, FlatComparisonResult):
|
|
681 |
raise ValueError("Expected instance of %s" % FlatComparisonResult.__name__)
|
|
682 |
|
|
683 |
self.only_in_source.extend(other.only_in_source)
|
|
684 |
self.only_in_target.extend(other.only_in_target)
|
|
685 |
self.modified.extend(other.modified)
|
|
686 |
|
|
687 |
def __repr__(self):
|
|
688 |
data = ["FlatComparisonResult(\n"]
|
|
689 |
|
|
690 |
def get_list_data(lst):
|
|
691 |
if len(lst) == 0: return '[]'
|
|
692 |
|
|
693 |
temp = ['[\n']
|
|
694 |
for item in sorted(lst):
|
|
695 |
temp.append(" %r\n" % item)
|
|
696 |
temp.append(' ]')
|
|
697 |
return ''.join(temp)
|
|
698 |
|
|
699 |
entries = []
|
|
700 |
for varname in ('only_in_source', 'only_in_target', 'modified', 'duplicate'):
|
|
701 |
entry_text = ' %s = %s' % (varname, get_list_data(getattr(self, varname)))
|
|
702 |
entries.append(entry_text)
|
|
703 |
data.append(',\n'.join(entries))
|
|
704 |
|
|
705 |
data.append('\n)')
|
|
706 |
return ''.join(data)
|
|
707 |
|
|
708 |
def __len__(self):
|
|
709 |
return len(self.only_in_source) + len(self.only_in_target) + len(self.modified)
|
|
710 |
|
|
711 |
def __eq__(self, other):
|
|
712 |
if type(self) is not type(other):
|
|
713 |
return False
|
|
714 |
return sorted(self.only_in_source) == sorted(other.only_in_source) \
|
|
715 |
and sorted(self.only_in_target) == sorted(other.only_in_target) \
|
|
716 |
and sorted(self.modified) == sorted(other.modified) \
|
|
717 |
and sorted(self.duplicate) == sorted(other.duplicate)
|
|
718 |
|
|
719 |
def __ne__(self, other):
|
|
720 |
return not (self == other)
|
|
721 |
|
|
722 |
class ImplBase(object):
|
|
723 |
"""
|
|
724 |
Base class for any implementation class.
|
|
725 |
"""
|
|
726 |
|
|
727 |
#: Identifier for the implementation type, used e.g. in .cfg files.
|
|
728 |
#: Should be a string like e.g. 'someml'.
|
|
729 |
IMPL_TYPE_ID = None
|
|
730 |
|
|
731 |
#: Defines the default invocation phase for the implementation.
|
|
732 |
#: The default is used if the phase is not explicitly set in the
|
|
733 |
#: ImplML file or manually overridden by calling set_invocation_phase()
|
|
734 |
DEFAULT_INVOCATION_PHASE = None
|
|
735 |
|
|
736 |
def __init__(self, ref, configuration):
|
|
737 |
"""
|
|
738 |
Create a ImplBase object
|
|
739 |
@param ref : the ref to the Implml file resource.
|
|
740 |
@param configuration : the Configuration instance for the
|
|
741 |
configuration data.
|
|
742 |
"""
|
|
743 |
self._settings = None
|
|
744 |
self.ref = ref
|
|
745 |
self.index = None
|
3
|
746 |
self.lineno = None
|
0
|
747 |
self.configuration = configuration
|
3
|
748 |
self._output_root = self.settings.get('output_root','')
|
0
|
749 |
self.output_subdir = self.settings.get('output_subdir','')
|
|
750 |
self.plugin_output = self.settings.get('plugin_output','')
|
|
751 |
|
|
752 |
self.generation_context = None
|
|
753 |
self._tags = None
|
|
754 |
self._invocation_phase = None
|
|
755 |
self._tempvar_defs = []
|
|
756 |
self.condition = None
|
|
757 |
self._output_root_override = None
|
|
758 |
|
3
|
759 |
def __reduce_ex__(self, protocol_version):
|
|
760 |
config = self.configuration
|
|
761 |
if protocol_version == 2:
|
|
762 |
tpl = (read_impl_from_location,
|
|
763 |
(self.ref, config, self.lineno),
|
|
764 |
None,
|
|
765 |
None,
|
|
766 |
None)
|
|
767 |
return tpl
|
|
768 |
else:
|
|
769 |
return (read_impl_from_location,
|
|
770 |
(self.ref, config, self.lineno))
|
|
771 |
|
0
|
772 |
|
4
|
773 |
#def __getstate__(self):
|
|
774 |
#state = self.__dict__
|
|
775 |
#state['configuration'] = self.configuration.path
|
|
776 |
#return state
|
|
777 |
|
|
778 |
#def __setstate__(self, dict):
|
|
779 |
# path = dict['configuration']
|
|
780 |
# configuration = api.ConfigurationProxy(path)
|
|
781 |
# self.__dict__.update(dict)
|
|
782 |
# self.configuration = configuration
|
|
783 |
|
0
|
784 |
def _dereference(self, ref):
|
|
785 |
"""
|
|
786 |
Function for dereferencing a configuration ref to a value in the Implementation configuration context.
|
|
787 |
"""
|
3
|
788 |
return self.configuration.get_default_view().get_feature(ref).value
|
0
|
789 |
|
|
790 |
def _compare(self, other, dict_keys=None):
|
|
791 |
"""
|
|
792 |
The plugin instance against another plugin instance
|
|
793 |
"""
|
|
794 |
raise exceptions.NotSupportedException()
|
3
|
795 |
|
0
|
796 |
def generate(self, context=None):
|
|
797 |
"""
|
|
798 |
Generate the given implementation.
|
|
799 |
@param context: The generation context can be given as a parameter.
|
|
800 |
The context can contain generation specific parameters for the
|
|
801 |
implementation object itself or the implementation can store data to it
|
|
802 |
which is visible to other implementations.
|
|
803 |
@return:
|
|
804 |
"""
|
|
805 |
raise exceptions.NotSupportedException()
|
|
806 |
|
|
807 |
def post_generate(self, context=None):
|
|
808 |
"""
|
|
809 |
Called when all normal generation has been done.
|
|
810 |
|
|
811 |
@param context: The generation context can be given as a parameter.
|
|
812 |
The context can contain generation specific parameters for the
|
|
813 |
implementation object itself or the implementation can store data to it
|
|
814 |
which is visible to other implementations.
|
|
815 |
@attention: This is a temporary method used for implementing cenrep_rfs.txt generation.
|
|
816 |
"""
|
|
817 |
pass
|
|
818 |
|
|
819 |
def list_output_files(self):
|
|
820 |
"""
|
|
821 |
Return a list of output files as an array.
|
|
822 |
"""
|
|
823 |
return []
|
|
824 |
|
3
|
825 |
def get_outputs(self):
|
|
826 |
"""
|
|
827 |
Return a list of GenerationOutput objets as a list.
|
|
828 |
"""
|
|
829 |
outputs = []
|
|
830 |
phase = None
|
|
831 |
if self.generation_context: phase = self.generation_context.phase
|
|
832 |
for outfile in self.list_output_files():
|
|
833 |
outputs.append(GenerationOutput(outfile,self,type='file', phase=phase) )
|
|
834 |
return outputs
|
|
835 |
|
|
836 |
|
0
|
837 |
def get_refs(self):
|
|
838 |
"""
|
|
839 |
Return a list of all ConfML setting references that affect this
|
|
840 |
implementation. May also return None if references are not relevant
|
|
841 |
for the implementation.
|
|
842 |
"""
|
|
843 |
return None
|
|
844 |
|
|
845 |
def has_ref(self, refs):
|
|
846 |
"""
|
|
847 |
@param refs: a list of references to check against.
|
|
848 |
@returns True if the implementation uses the given refs as input value, return False if the ref is not found.
|
|
849 |
If refs are not relevant for the given plugin returns None.
|
|
850 |
"""
|
|
851 |
impl_refs = self.get_refs()
|
|
852 |
if impl_refs is None:
|
|
853 |
return None
|
|
854 |
|
|
855 |
if isinstance(refs, basestring):
|
|
856 |
refs = [refs]
|
|
857 |
|
3
|
858 |
return uses_ref(refs, impl_refs)
|
0
|
859 |
|
|
860 |
def flat_compare(self, other):
|
|
861 |
"""
|
|
862 |
Return a flat comparison result for two implementations.
|
|
863 |
@param other: The target implementation to compare against.
|
|
864 |
@return: A FlatComparisonResult object.
|
|
865 |
|
|
866 |
@raise exceptions.NotSupportedException(): The implementation class does not support
|
|
867 |
flat comparison.
|
|
868 |
"""
|
|
869 |
raise exceptions.NotSupportedException()
|
|
870 |
|
|
871 |
def get_flat_comparison_id(self):
|
|
872 |
"""
|
|
873 |
Return the ID used to uniquely identify this implementation instance for flat comparison.
|
|
874 |
|
|
875 |
@raise exceptions.NotSupportedException() if the implementation class does not support
|
|
876 |
flat comparison.
|
|
877 |
"""
|
|
878 |
raise exceptions.NotSupportedException()
|
|
879 |
|
|
880 |
def get_flat_comparison_extra_data(self):
|
|
881 |
"""
|
|
882 |
Return the extra data object for a flat comparison entry.
|
|
883 |
|
|
884 |
This method is called when an implementation container comparison finds an
|
|
885 |
implementation instance that is not in the other container.
|
|
886 |
|
|
887 |
@raise exceptions.NotSupportedException() if the implementation class does not support
|
|
888 |
flat comparison.
|
|
889 |
"""
|
|
890 |
raise exceptions.NotSupportedException()
|
|
891 |
|
|
892 |
@classmethod
|
|
893 |
def get_flat_comparison_impl_type_id(cls):
|
|
894 |
"""
|
|
895 |
Return the type ID used to uniquely identify the current implementation class in flat comparison.
|
|
896 |
|
|
897 |
@raise exceptions.NotSupportedException() if the implementation class does not support
|
|
898 |
flat comparison.
|
|
899 |
"""
|
|
900 |
raise exceptions.NotSupportedException()
|
|
901 |
|
|
902 |
@property
|
|
903 |
def settings(self):
|
3
|
904 |
"""
|
|
905 |
return the plugin specific settings object.
|
|
906 |
"""
|
0
|
907 |
if not self._settings:
|
|
908 |
parser = settings.SettingsFactory.cone_parser()
|
|
909 |
if self.IMPL_TYPE_ID is not None:
|
|
910 |
section = self.IMPL_TYPE_ID.upper()
|
|
911 |
else:
|
|
912 |
section = settings.DEFAULT_SECTION
|
|
913 |
self._settings = settings.ConeSettings(parser, section)
|
|
914 |
return self._settings
|
|
915 |
|
|
916 |
@property
|
|
917 |
def output(self):
|
3
|
918 |
"""
|
|
919 |
return the output folder for this plugin instance.
|
|
920 |
"""
|
0
|
921 |
vars = {'output_root': self.output_root,'output_subdir': self.output_subdir,'plugin_output': self.plugin_output}
|
|
922 |
default_format = '%(output_root)s/%(output_subdir)s/%(plugin_output)s'
|
3
|
923 |
output = utils.resourceref.remove_begin_slash(utils.resourceref.norm(self.settings.get('output',default_format,vars)))
|
|
924 |
if os.path.isabs(self.output_root):
|
|
925 |
output = utils.resourceref.insert_begin_slash(output)
|
|
926 |
return output
|
0
|
927 |
|
|
928 |
def _get_output_root(self):
|
|
929 |
if self._output_root_override is not None:
|
|
930 |
return self._output_root_override
|
|
931 |
else:
|
|
932 |
return self._output_root
|
|
933 |
|
|
934 |
def _set_output_root(self, value):
|
|
935 |
self._output_root = value
|
|
936 |
|
|
937 |
output_root = property(_get_output_root, _set_output_root, None,
|
|
938 |
"""
|
|
939 |
The output root directory.
|
|
940 |
|
|
941 |
Note that if set_output_root_override() has been called with a value
|
|
942 |
other than None, reading this property will always return that value.
|
|
943 |
Otherwise it works just like any other property.
|
|
944 |
""")
|
|
945 |
|
|
946 |
def get_tags(self):
|
|
947 |
if self._tags is not None:
|
|
948 |
tags = self._tags
|
|
949 |
else:
|
|
950 |
tags = eval(self.settings.get('plugin_tags','{}'))
|
|
951 |
|
|
952 |
# If we have a configuration, expand setting references in the tags
|
|
953 |
if self.configuration is not None:
|
|
954 |
dview = self.configuration.get_default_view()
|
|
955 |
expanded_tags = {}
|
|
956 |
for name, values in tags.iteritems():
|
|
957 |
exp_name = utils.expand_refs_by_default_view(name, dview)
|
|
958 |
exp_values = []
|
|
959 |
expanded_tags[exp_name] = exp_values
|
|
960 |
for value in values:
|
|
961 |
exp_value = utils.expand_refs_by_default_view(value, dview)
|
|
962 |
exp_values.append(exp_value)
|
|
963 |
return expanded_tags
|
|
964 |
else:
|
|
965 |
return tags.copy()
|
|
966 |
|
|
967 |
|
|
968 |
def set_tags(self, tags):
|
|
969 |
"""
|
|
970 |
Override the default implementation tags.
|
|
971 |
@param phase: The tag dictionary to set. If None, the implementation's
|
|
972 |
default tags will be used.
|
|
973 |
"""
|
|
974 |
self._tags = tags
|
|
975 |
|
|
976 |
def has_tag(self, tags, policy=None):
|
|
977 |
"""
|
|
978 |
@param tags: a dictionary of context : tags to check agains
|
|
979 |
@returns True if the implementation has a matching tag.
|
|
980 |
Otherwise return False.
|
|
981 |
"""
|
|
982 |
if (tags==None or len(tags)==0) and len(self.get_tags()) == 0:
|
|
983 |
return True
|
|
984 |
if (tags!=None and len(tags)!=0) and len(self.get_tags()) == 0:
|
|
985 |
return False
|
|
986 |
|
|
987 |
items = tags.iteritems()
|
|
988 |
self_tags = self.get_tags()
|
|
989 |
if policy == 'AND':
|
|
990 |
for (key,values) in items:
|
|
991 |
tagvals = self_tags.get(key, [])
|
|
992 |
for val in values:
|
|
993 |
if val not in tagvals:
|
|
994 |
return False
|
|
995 |
return True
|
|
996 |
else:
|
|
997 |
for (key,values) in items:
|
|
998 |
tagvals = self_tags.get(key, [])
|
|
999 |
for val in values:
|
|
1000 |
if val in tagvals:
|
|
1001 |
return True
|
|
1002 |
return False
|
|
1003 |
|
|
1004 |
return False
|
|
1005 |
|
|
1006 |
def set_output_root(self,output):
|
|
1007 |
"""
|
|
1008 |
Set the root directory for the output files. The output
|
|
1009 |
@param output : path to output dir.
|
|
1010 |
"""
|
|
1011 |
self.output_root = output
|
|
1012 |
|
|
1013 |
def get_output_root(self):
|
|
1014 |
"""
|
|
1015 |
Return the current output dir.
|
|
1016 |
"""
|
|
1017 |
return self.output_root
|
|
1018 |
|
|
1019 |
def set_output_root_override(self, output):
|
|
1020 |
"""
|
|
1021 |
Set the output root override.
|
|
1022 |
@param output: The override value. If None, the normal output root
|
|
1023 |
value is used.
|
|
1024 |
"""
|
|
1025 |
self._output_root_override = output
|
|
1026 |
|
|
1027 |
def invocation_phase(self):
|
|
1028 |
"""
|
|
1029 |
@return: the phase name in which the plugin wants to be executed.
|
|
1030 |
"""
|
|
1031 |
# 1. Check if overridden on implementation instance level
|
|
1032 |
if self._invocation_phase is not None:
|
|
1033 |
return self._invocation_phase
|
|
1034 |
# 2. Check if overridden on implementation class level
|
|
1035 |
elif self.DEFAULT_INVOCATION_PHASE is not None:
|
|
1036 |
return self.DEFAULT_INVOCATION_PHASE
|
|
1037 |
# 3. Get from settings (if all else fails fall back to 'normal'
|
|
1038 |
else:
|
|
1039 |
return self.settings.get('plugin_phase', 'normal')
|
|
1040 |
|
|
1041 |
def set_invocation_phase(self, phase):
|
|
1042 |
"""
|
|
1043 |
Override the default invocation phase.
|
|
1044 |
@param phase: The invocation phase to set. If None, the implementation's
|
|
1045 |
default phase will be used.
|
|
1046 |
"""
|
|
1047 |
self._invocation_phase = phase
|
|
1048 |
|
|
1049 |
def compare(self):
|
|
1050 |
"""
|
|
1051 |
@return: the phase name in which the plugin wants to be executed.
|
|
1052 |
"""
|
|
1053 |
return self.settings.get('plugin_phase','normal')
|
|
1054 |
|
|
1055 |
def get_temp_variable_definitions(self):
|
|
1056 |
return self._tempvar_defs
|
|
1057 |
|
|
1058 |
def get_relation_container(self):
|
|
1059 |
"""
|
|
1060 |
Return a relation container containing all relations from this
|
|
1061 |
implementation instance, or None.
|
|
1062 |
"""
|
|
1063 |
return None
|
|
1064 |
|
|
1065 |
def get_all_implementations(self):
|
|
1066 |
"""
|
|
1067 |
return a list of all actual implementation which is for ImplBase object self.
|
|
1068 |
"""
|
|
1069 |
return [self]
|
|
1070 |
|
|
1071 |
def __repr__(self):
|
3
|
1072 |
return "%s(ref=%r, type=%r, lineno=%r)" % (self.__class__.__name__, self.ref, self.IMPL_TYPE_ID, self.lineno)
|
|
1073 |
|
|
1074 |
@property
|
|
1075 |
def path(self):
|
|
1076 |
"""
|
|
1077 |
return path relative to the Configuration projec root
|
|
1078 |
"""
|
|
1079 |
return self.ref
|
0
|
1080 |
|
3
|
1081 |
@property
|
|
1082 |
def abspath(self):
|
|
1083 |
"""
|
|
1084 |
return absolute system path to the implementation
|
|
1085 |
"""
|
|
1086 |
return os.path.abspath(os.path.join(self.configuration.storage.path,self.ref))
|
|
1087 |
|
|
1088 |
def uses_layers(self, layers, context):
|
|
1089 |
"""
|
|
1090 |
Return whether this implementation uses any of the given layers
|
|
1091 |
in the given context, i.e., whether the layers contain anything that would
|
|
1092 |
affect generation output.
|
|
1093 |
"""
|
|
1094 |
# The default implementation checks against refs changed in the layers
|
|
1095 |
refs = []
|
|
1096 |
for l in layers: refs.extend(l.list_leaf_datas())
|
|
1097 |
return self.has_ref(refs)
|
0
|
1098 |
|
|
1099 |
class ImplContainer(ImplBase):
|
|
1100 |
"""
|
|
1101 |
Acts as a container object with list functionality.
|
|
1102 |
"""
|
|
1103 |
def __init__(self, ref, configuration):
|
|
1104 |
ImplBase.__init__(self, ref, configuration)
|
|
1105 |
self.impls = []
|
|
1106 |
|
|
1107 |
# The list functions
|
|
1108 |
def __getattr__(self, name):
|
|
1109 |
if hasattr(self.impls, name):
|
|
1110 |
return self.impls.__getattribute__(name)
|
|
1111 |
|
|
1112 |
def __getitem__(self, key):
|
|
1113 |
return self.impls[key]
|
|
1114 |
|
|
1115 |
def __setitem__(self, key, value):
|
|
1116 |
self.impls[key] = value
|
|
1117 |
|
|
1118 |
def __delitem__(self, key):
|
|
1119 |
del self.impls[key]
|
|
1120 |
|
|
1121 |
def __len__(self):
|
|
1122 |
return len(self.impls)
|
|
1123 |
|
|
1124 |
def __iter__(self):
|
|
1125 |
return iter(self.impls)
|
|
1126 |
|
|
1127 |
def generate(self, context=None):
|
|
1128 |
"""
|
|
1129 |
Generate function for container executes generate for all sub implementations.
|
|
1130 |
@param context: The generation context can be given as a parameter. The container
|
|
1131 |
passes the context to its sub implementations.
|
|
1132 |
|
|
1133 |
@return:
|
|
1134 |
"""
|
3
|
1135 |
log = logging.getLogger('cone')
|
|
1136 |
|
|
1137 |
if self.condition and not self.condition.eval(context):
|
|
1138 |
log.debug('Filtered out based on condition %s: %r' % (self.condition, self))
|
|
1139 |
return
|
|
1140 |
|
0
|
1141 |
# run generate on sub impls
|
|
1142 |
for impl in self.impls:
|
3
|
1143 |
if context:
|
|
1144 |
# 1. Check should the implementation be run from context
|
|
1145 |
# 2. Run ImplContainer if should
|
|
1146 |
# 3. run other ImplBase objects if this is not a dry_run
|
|
1147 |
if context.should_run(impl):
|
|
1148 |
if isinstance(impl, ImplContainer) or \
|
|
1149 |
not context.dry_run:
|
|
1150 |
impl.generate(context)
|
|
1151 |
# context.have_run(impl)
|
|
1152 |
else:
|
|
1153 |
impl.generate(context)
|
0
|
1154 |
|
|
1155 |
def get_refs(self):
|
3
|
1156 |
# Containers always return None, because the ref-based filtering
|
|
1157 |
# happens only on the actual implementations
|
|
1158 |
return None
|
|
1159 |
|
|
1160 |
def get_child_refs(self):
|
0
|
1161 |
"""
|
3
|
1162 |
ImplContainer always None with get_refs so it one wants to get the references from all
|
|
1163 |
leaf child objects, one can use this get_child_refs function
|
|
1164 |
@return: a list of references.
|
0
|
1165 |
"""
|
|
1166 |
refs = []
|
|
1167 |
for impl in self.impls:
|
3
|
1168 |
if isinstance(impl, ImplContainer):
|
|
1169 |
refs += impl.get_child_refs()
|
|
1170 |
else:
|
|
1171 |
refs += impl.get_refs() or []
|
|
1172 |
return utils.distinct_array(refs)
|
0
|
1173 |
|
3
|
1174 |
def has_tag(self, tags, policy=None):
|
|
1175 |
# Container always returns True
|
|
1176 |
return True
|
|
1177 |
|
0
|
1178 |
def get_tags(self):
|
3
|
1179 |
# Containers always return None, because the tag-based filtering
|
|
1180 |
# happens only on the actual implementations
|
|
1181 |
return None
|
|
1182 |
|
|
1183 |
def get_child_tags(self):
|
0
|
1184 |
"""
|
3
|
1185 |
ImplContainer always None with get_tags so it one wants to get the teags from all
|
|
1186 |
leaf child objects, one can use this get_child_tags function
|
|
1187 |
@return: a list of references.
|
0
|
1188 |
"""
|
3
|
1189 |
tags = {}
|
0
|
1190 |
for impl in self.impls:
|
3
|
1191 |
if isinstance(impl, ImplContainer):
|
|
1192 |
utils.update_dict(tags, impl.get_child_tags())
|
|
1193 |
else:
|
|
1194 |
utils.update_dict(tags, impl.get_tags())
|
0
|
1195 |
return tags
|
|
1196 |
|
|
1197 |
def list_output_files(self):
|
|
1198 |
"""
|
|
1199 |
Return a list of output files as an array.
|
|
1200 |
"""
|
|
1201 |
files = []
|
|
1202 |
for impl in self.impls:
|
|
1203 |
files += impl.list_output_files()
|
|
1204 |
return utils.distinct_array(files)
|
|
1205 |
|
3
|
1206 |
def get_outputs(self):
|
|
1207 |
"""
|
|
1208 |
Return a list of GenerationOutput objets as a list.
|
|
1209 |
"""
|
|
1210 |
outputs = []
|
|
1211 |
for impl in self.impls:
|
|
1212 |
outputs += impl.get_outputs()
|
|
1213 |
return outputs
|
|
1214 |
|
0
|
1215 |
def set_output_root(self,output):
|
|
1216 |
"""
|
|
1217 |
Set the root directory for the output files. The output
|
|
1218 |
@param output : path to output dir.
|
|
1219 |
"""
|
|
1220 |
self.output_root = output
|
|
1221 |
for impl in self.impls:
|
|
1222 |
impl.set_output_root(output)
|
|
1223 |
|
|
1224 |
def get_temp_variable_definitions(self):
|
|
1225 |
tempvars = self._tempvar_defs[:]
|
|
1226 |
for impl in self.impls:
|
|
1227 |
tempvars += impl.get_temp_variable_definitions()
|
|
1228 |
return tempvars
|
|
1229 |
|
|
1230 |
def get_relation_container(self):
|
|
1231 |
"""
|
|
1232 |
Return a relation container containing all relations from this
|
|
1233 |
container object instance, or empty relation container.
|
|
1234 |
"""
|
|
1235 |
container = RelationContainer([], '<root>')
|
|
1236 |
for impl in self.impls:
|
|
1237 |
c = impl.get_relation_container()
|
|
1238 |
if isinstance(c, RelationContainer):
|
|
1239 |
container.entries.append(c)
|
|
1240 |
return container
|
|
1241 |
|
|
1242 |
def get_all_implementations(self):
|
|
1243 |
"""
|
|
1244 |
return a list of all actual implementation under this container
|
|
1245 |
"""
|
|
1246 |
actual_impls = []
|
|
1247 |
for subimpl in self.impls:
|
|
1248 |
actual_impls += subimpl.get_all_implementations()
|
|
1249 |
return actual_impls
|
3
|
1250 |
|
|
1251 |
def uses_layers(self, layers, context):
|
|
1252 |
#log = logging.getLogger('uses_layers(%r)' % self)
|
|
1253 |
|
|
1254 |
# If no sub-implementation has matching tags, the implementations would
|
|
1255 |
# never be run in this context, so there's no need to go further in that case
|
|
1256 |
if not self._have_impls_matching_tags(context.tags, context.tags_policy):
|
|
1257 |
#log.debug("No impls have matching tags, returning False")
|
|
1258 |
return False
|
|
1259 |
|
|
1260 |
# If the container has a condition depending on any of the changed refs,
|
|
1261 |
# it means that the refs can affect generation output
|
|
1262 |
if self.condition:
|
|
1263 |
refs = []
|
|
1264 |
for l in layers: refs.extend(l.list_leaf_datas())
|
|
1265 |
if uses_ref(refs, self.condition.get_refs()):
|
|
1266 |
#log.debug("Refs affect condition, returning True")
|
|
1267 |
return True
|
|
1268 |
|
|
1269 |
# If the condition evaluates to False (and doesn't depend on the
|
|
1270 |
# changed refs), the implementations won't be run, and thus they
|
|
1271 |
# don't use the layers in this context
|
|
1272 |
if self.condition and not self.condition.eval(context):
|
|
1273 |
#log.debug("Condition evaluates to False, returning False")
|
|
1274 |
return False
|
|
1275 |
|
|
1276 |
for impl in self.impls:
|
|
1277 |
# Filter out based on tags if the implementation is not
|
|
1278 |
# a container (using ImplBase.has_tag() here since RuleML v2
|
|
1279 |
# overrides has_tag() to always return True)
|
|
1280 |
if not isinstance(impl, ImplContainer):
|
|
1281 |
if not ImplBase.has_tag(impl, context.tags, context.tags_policy):
|
|
1282 |
continue
|
|
1283 |
|
|
1284 |
if impl.uses_layers(layers, context):
|
|
1285 |
#log.debug("%r uses layer, returning True" % impl)
|
|
1286 |
return True
|
|
1287 |
|
|
1288 |
#log.debug("Returning False")
|
|
1289 |
return False
|
|
1290 |
|
|
1291 |
def _have_impls_matching_tags(self, tags, tags_policy):
|
|
1292 |
"""
|
|
1293 |
Return if any of the container's leaf implementations use the given tags.
|
|
1294 |
"""
|
|
1295 |
for impl in self.impls:
|
|
1296 |
if isinstance(impl, ImplContainer):
|
|
1297 |
if impl._have_impls_matching_tags(tags, tags_policy):
|
|
1298 |
return True
|
|
1299 |
elif ImplBase.has_tag(impl, tags, tags_policy):
|
|
1300 |
return True
|
|
1301 |
return False
|
|
1302 |
|
0
|
1303 |
class ReaderBase(object):
|
|
1304 |
"""
|
|
1305 |
Base class for implementation readers.
|
|
1306 |
|
|
1307 |
Each reader class supports one XML namespace, from which it reads an implementation
|
|
1308 |
instance.
|
|
1309 |
|
|
1310 |
The method for parsing an implementation (read_impl()) is given an ElementTree
|
|
1311 |
XML element as the root from which to parse the implementation. The plug-in
|
|
1312 |
machinery handles each XML file so that the correct reader class is used to read
|
|
1313 |
the implementations from XML elements based on the namespaces.
|
|
1314 |
"""
|
|
1315 |
|
|
1316 |
#: The XML namespace supported by the implementation reader.
|
|
1317 |
#: Should be something like "http://www.xyz.org/xml/1".
|
|
1318 |
#: Can also be None, in which case the reader will not be used
|
|
1319 |
#: (this can be useful for defining base classes for e.g. readers
|
|
1320 |
#: for different versions of an implementation).
|
|
1321 |
NAMESPACE = None
|
|
1322 |
|
3
|
1323 |
#: ID for the namespace used in the generated XML schema files.
|
|
1324 |
#: Must be unique, and something simple like 'someml'.
|
|
1325 |
NAMESPACE_ID = None
|
|
1326 |
|
|
1327 |
#: Sub-ID for schema problems for this ImplML namespace.
|
|
1328 |
#: This is used as part of the problem type for schema validation
|
|
1329 |
#: problems. E.g. if the sub-ID is 'someml', then a schema validation
|
|
1330 |
#: problem would have the problem type 'schema.implml.someml'.
|
|
1331 |
#: If this is not given, then the problem type will simply be
|
|
1332 |
#: 'schema.implml'.
|
|
1333 |
SCHEMA_PROBLEM_SUB_ID = None
|
|
1334 |
|
|
1335 |
#: The root element name of the implementation langauge supported by
|
|
1336 |
#: the reader. This is also used in the generate XML schema files, and
|
|
1337 |
#: must correspond to the root element name specified in the schema data.
|
|
1338 |
#: If get_schema_data() returns None, then this determines the name of
|
|
1339 |
#: the root element in the automatically generated default schema.
|
|
1340 |
ROOT_ELEMENT_NAME = None
|
|
1341 |
|
0
|
1342 |
#: Any extra XML namespaces that should be ignored by the
|
|
1343 |
#: implementation parsing machinery. This is useful for specifying
|
|
1344 |
#: namespaces that are not actual ImplML namespaces, but are used
|
|
1345 |
#: inside an implementation (e.g. XInclude)
|
|
1346 |
IGNORED_NAMESPACES = []
|
|
1347 |
|
|
1348 |
#: Supported implementation file extensions.
|
|
1349 |
#: Sub-classes can override this to add new supported file extensions
|
|
1350 |
#: if necessary. The file extensions simply control whether implementations
|
|
1351 |
#: are attempted to be read from a file or not.
|
|
1352 |
#: Note that the extensions are case-insensitive.
|
|
1353 |
FILE_EXTENSIONS = ['implml']
|
|
1354 |
|
|
1355 |
@classmethod
|
|
1356 |
def read_impl(cls, resource_ref, configuration, doc_root):
|
|
1357 |
"""
|
|
1358 |
Read an implementation instance from the given element tree.
|
|
1359 |
|
|
1360 |
@param resource_ref: Reference to the resource in the configuration in
|
|
1361 |
which the given document root resides.
|
|
1362 |
@param configuration: The configuration used.
|
|
1363 |
@param doc_root: The document root from which to parse the implementation.
|
|
1364 |
@return: The read implementation instance, or None.
|
|
1365 |
"""
|
|
1366 |
raise exceptions.NotSupportedException()
|
|
1367 |
|
|
1368 |
@classmethod
|
3
|
1369 |
def read_impl_from_location(cls, resource_ref, configuration, lineno):
|
|
1370 |
"""
|
|
1371 |
Read an implementation instance from the given resource at the given line number.
|
|
1372 |
|
|
1373 |
@param resource_ref: Reference to the resource in the configuration in
|
|
1374 |
which the given document root resides.
|
|
1375 |
@param configuration: The configuration used.
|
|
1376 |
@param lineno: the line number where the root node for this particular element is searched from.
|
|
1377 |
@return: The read implementation instance, or None.
|
|
1378 |
"""
|
|
1379 |
root = cls._read_xml_doc_from_resource(resource_ref, configuration)
|
|
1380 |
elemroot = utils.etree.get_elem_from_lineno(root, lineno)
|
|
1381 |
ns, tag = utils.xml.split_tag_namespace(elemroot.tag)
|
|
1382 |
reader = cls.get_reader_for_namespace(ns)
|
|
1383 |
implml = reader.read_impl(resource_ref, configuration, elemroot)
|
|
1384 |
implml.lineno = lineno
|
|
1385 |
return implml
|
|
1386 |
|
|
1387 |
@classmethod
|
|
1388 |
def get_reader_for_namespace(cls, namespace):
|
|
1389 |
return ImplFactory.get_reader_dict().get(namespace, None)
|
|
1390 |
|
|
1391 |
@classmethod
|
|
1392 |
def get_schema_data(cls):
|
|
1393 |
"""
|
|
1394 |
Return the XML schema data used for validating the ImplML supported by this reader.
|
|
1395 |
@return: The schema data as a string, or None if not available.
|
|
1396 |
"""
|
|
1397 |
return None
|
|
1398 |
|
|
1399 |
@classmethod
|
0
|
1400 |
def _read_xml_doc_from_resource(cls, resource_ref, configuration):
|
|
1401 |
"""
|
|
1402 |
Parse an ElementTree instance from the given resource.
|
|
1403 |
"""
|
|
1404 |
resource = configuration.get_resource(resource_ref)
|
|
1405 |
try:
|
|
1406 |
try:
|
|
1407 |
data = resource.read()
|
|
1408 |
return utils.etree.fromstring(data)
|
|
1409 |
except exceptions.XmlParseError, e:
|
|
1410 |
msg = "Invalid XML in implementation file '%s'. Exception: %s" % (resource_ref, e)
|
|
1411 |
raise e
|
|
1412 |
finally:
|
|
1413 |
resource.close()
|
|
1414 |
|
|
1415 |
class ImplContainerReader(ReaderBase):
|
|
1416 |
"""
|
|
1417 |
Reader class for reading containers inside implementation files. A container
|
|
1418 |
is a implementation in it self that can contain a list of actual implementations.
|
|
1419 |
"""
|
|
1420 |
NAMESPACE = "http://www.symbianfoundation.org/xml/implml/1"
|
|
1421 |
|
|
1422 |
|
|
1423 |
# The reader class list loaded using ImplFactory
|
|
1424 |
__reader_classes = None
|
|
1425 |
__supported_file_extensions = None
|
|
1426 |
__ignored_namespaces = None
|
|
1427 |
|
|
1428 |
@classmethod
|
|
1429 |
def get_reader_classes(cls):
|
|
1430 |
"""
|
|
1431 |
Return a dictionary of all possible implementation reader classes.
|
|
1432 |
|
|
1433 |
Dictionary key is the XML namespace and the value is the corresponding
|
|
1434 |
reader class.
|
|
1435 |
"""
|
|
1436 |
cls.__reader_classes = ImplFactory.get_reader_dict()
|
|
1437 |
return cls.__reader_classes
|
|
1438 |
|
|
1439 |
@classmethod
|
|
1440 |
def read_impl(cls, resource_ref, configuration, doc_root, read_impl_count=None):
|
3
|
1441 |
on_top_level = read_impl_count == None
|
0
|
1442 |
# The variable read_impl_count is used to keep track of the number of
|
|
1443 |
# currently read actual implementations. It is a list so that it can be used
|
|
1444 |
# like a pointer, i.e. functions called from here can modify the number
|
|
1445 |
# inside it. A more elegant solution is not done here, since this is temporary
|
|
1446 |
# and the index variable in implementation instances will be changed to line_number,
|
|
1447 |
# which specifies the actual line on which the implementation is specified in the file
|
|
1448 |
if read_impl_count is None: read_impl_count = [0]
|
|
1449 |
|
|
1450 |
ns, tag = utils.xml.split_tag_namespace(doc_root.tag)
|
|
1451 |
if tag != "container":
|
3
|
1452 |
logging.getLogger('cone').error("Error: The root element must be a container in %s, %s" % (ns, resource_ref))
|
0
|
1453 |
|
|
1454 |
reader_classes = cls.get_reader_classes()
|
|
1455 |
namespaces = reader_classes.keys()
|
|
1456 |
# Read first the root container object with attributes
|
|
1457 |
# and then traverse through possible child containers
|
|
1458 |
containerobj = ImplContainer(resource_ref, configuration)
|
|
1459 |
containerobj.condition = cls.get_condition(doc_root)
|
|
1460 |
|
3
|
1461 |
containerobj._common_data = _plugin_reader.CommonImplmlDataReader.read_data(doc_root)
|
0
|
1462 |
|
|
1463 |
# traverse through the subelements
|
|
1464 |
for elem in doc_root:
|
|
1465 |
ns, tag = utils.xml.split_tag_namespace(elem.tag)
|
|
1466 |
if ns == cls.NAMESPACE:
|
|
1467 |
# Read a sub-container from the common namespace (all other
|
|
1468 |
# common namespace elements were handled earlier)
|
|
1469 |
if tag == "container":
|
|
1470 |
subcontainer = cls.read_impl(resource_ref, configuration, elem, read_impl_count=read_impl_count)
|
3
|
1471 |
subcontainer.lineno = utils.etree.get_lineno(elem)
|
0
|
1472 |
containerobj.append(subcontainer)
|
|
1473 |
subcontainer.index = None # For now all sub-containers have index = None
|
|
1474 |
else:
|
|
1475 |
# Try to read the sub implementation object from some other namespace
|
|
1476 |
if ns not in namespaces:
|
|
1477 |
logging.getLogger('cone').error("Error: no reader for namespace '%s' in %s" % (ns, resource_ref))
|
|
1478 |
else:
|
|
1479 |
reader = reader_classes[ns]
|
|
1480 |
subelem = reader.read_impl(resource_ref, configuration, elem)
|
3
|
1481 |
subelem.lineno = utils.etree.get_lineno(elem)
|
0
|
1482 |
containerobj.append(subelem)
|
|
1483 |
subelem.index = read_impl_count[0]
|
|
1484 |
read_impl_count[0] = read_impl_count[0] + 1
|
3
|
1485 |
|
|
1486 |
containerobj._tempvar_defs = containerobj._common_data.tempvar_defs
|
|
1487 |
|
|
1488 |
if on_top_level:
|
|
1489 |
def inherit_common_data(container):
|
|
1490 |
for impl in container.impls:
|
|
1491 |
if isinstance(impl, ImplContainer):
|
|
1492 |
new_common_data = container._common_data.copy()
|
|
1493 |
new_common_data.extend(impl._common_data)
|
|
1494 |
impl._common_data = new_common_data
|
|
1495 |
inherit_common_data(impl)
|
|
1496 |
def apply_common_data(container):
|
|
1497 |
for impl in container.impls:
|
|
1498 |
if isinstance(impl, ImplContainer):
|
|
1499 |
apply_common_data(impl)
|
|
1500 |
else:
|
|
1501 |
container._common_data.apply(impl)
|
|
1502 |
inherit_common_data(containerobj)
|
|
1503 |
apply_common_data(containerobj)
|
|
1504 |
|
0
|
1505 |
return containerobj
|
|
1506 |
|
|
1507 |
@classmethod
|
|
1508 |
def read_implementation(cls, xml_data):
|
|
1509 |
"""
|
|
1510 |
Read a container implementation from the given xmlroot element.
|
|
1511 |
"""
|
|
1512 |
root = utils.etree.fromstring(xml_data)
|
|
1513 |
return cls.read_impl("", None,root)
|
|
1514 |
|
|
1515 |
@classmethod
|
|
1516 |
def get_condition(cls, root):
|
|
1517 |
if root.get('condition'):
|
|
1518 |
left = root.get('condition')
|
|
1519 |
right = root.get('value', 'true')
|
|
1520 |
return rules.SimpleCondition(left, right)
|
|
1521 |
else:
|
|
1522 |
return None
|
|
1523 |
|
3
|
1524 |
class ImplSet(set):
|
0
|
1525 |
"""
|
|
1526 |
Implementation set class that can hold a set of ImplBase instances.
|
|
1527 |
"""
|
|
1528 |
|
|
1529 |
"""
|
|
1530 |
The plugin phases is a list of possible phases in which the plugins are executed.
|
|
1531 |
Each plugin instance can tell in which phase it needs to be executed.
|
|
1532 |
"""
|
|
1533 |
INVOCATION_PHASES = ['pre','normal','post']
|
|
1534 |
|
|
1535 |
def __init__(self,implementations=None, generation_context=None):
|
3
|
1536 |
super(ImplSet,self).__init__(implementations or [])
|
0
|
1537 |
self.output = 'output'
|
3
|
1538 |
self.generation_context = generation_context
|
|
1539 |
self.ref_to_impl = {}
|
|
1540 |
|
|
1541 |
def _create_ref_dict(self):
|
|
1542 |
for impl in self:
|
|
1543 |
for ref in impl.get_refs() or []:
|
|
1544 |
self.ref_to_impl.setdefault(ref, []).append(impl)
|
|
1545 |
|
0
|
1546 |
def invocation_phases(self):
|
|
1547 |
"""
|
|
1548 |
@return: A list of possible invocation phases
|
|
1549 |
"""
|
|
1550 |
return self.INVOCATION_PHASES
|
|
1551 |
|
|
1552 |
def list_output_files(self):
|
|
1553 |
"""
|
|
1554 |
List the output file names from this container.
|
|
1555 |
"""
|
|
1556 |
filelist = []
|
|
1557 |
for impl in self:
|
|
1558 |
files = impl.list_output_files()
|
|
1559 |
filelist.extend(files)
|
|
1560 |
return utils.distinct_array(filelist)
|
|
1561 |
|
|
1562 |
def generate(self, context=None):
|
|
1563 |
"""
|
|
1564 |
Generate all implementations.
|
|
1565 |
@return:
|
|
1566 |
"""
|
|
1567 |
#for impl in self.impls:
|
|
1568 |
# impl.generation_context = self.generation_context
|
|
1569 |
if not context:
|
|
1570 |
context = self.generation_context
|
3
|
1571 |
else:
|
|
1572 |
self.generation_context = context
|
|
1573 |
# Sort by file name so that execution order is always the same
|
|
1574 |
# (easier to compare logs)
|
|
1575 |
sorted_impls = sorted(self, key=lambda impl: impl.ref)
|
|
1576 |
|
|
1577 |
for impl in sorted_impls:
|
|
1578 |
# 1. Check should the implementation be run from context
|
|
1579 |
# 2. Run ImplContainer if should
|
|
1580 |
# 3. run other ImplBase objects if this is not a dry_run
|
|
1581 |
if context.should_run(impl):
|
|
1582 |
if isinstance(impl, ImplContainer) or \
|
|
1583 |
not context.dry_run:
|
|
1584 |
self.execute([impl], 'generate', context)
|
|
1585 |
# context.have_run(impl)
|
0
|
1586 |
|
|
1587 |
def post_generate(self, context=None):
|
|
1588 |
"""
|
|
1589 |
@attention: This is a temporary method used for implementing cenrep_rfs.txt generation.
|
|
1590 |
"""
|
|
1591 |
if not context:
|
|
1592 |
context = self.generation_context
|
3
|
1593 |
|
|
1594 |
impls = []
|
|
1595 |
# Sort by file name so that execution order is always the same
|
|
1596 |
# (easier to compare logs)
|
|
1597 |
sorted_impls = sorted(self, key=lambda impl: impl.ref)
|
|
1598 |
for impl in sorted_impls:
|
|
1599 |
if context.should_run(impl, log_debug_message=False):
|
|
1600 |
impls.append(impl)
|
|
1601 |
|
|
1602 |
self.execute(impls, 'post_generate', context)
|
0
|
1603 |
|
|
1604 |
def execute(self, implementations, methodname, *args):
|
|
1605 |
"""
|
|
1606 |
Internal function for executing a function to a list of implementations.
|
|
1607 |
|
|
1608 |
Mutual execution order (for separate implementation instances defined in
|
|
1609 |
the same implementation file) is the order the implementations are
|
|
1610 |
specified in the file.
|
|
1611 |
|
|
1612 |
@param implementations:
|
|
1613 |
@param methodname: the name of the function to execute
|
|
1614 |
"""
|
3
|
1615 |
for impl in implementations:
|
0
|
1616 |
try:
|
|
1617 |
if hasattr(impl, methodname):
|
|
1618 |
_member = getattr(impl, methodname)
|
|
1619 |
_member(*args)
|
|
1620 |
else:
|
|
1621 |
logging.getLogger('cone').error('Impl %r has no method %s' % (impl, methodname))
|
|
1622 |
except Exception, e:
|
3
|
1623 |
if self.generation_context:
|
|
1624 |
self.generation_context.generation_output.append(GenerationOutput('exception from %s' % impl.ref,
|
|
1625 |
impl,
|
|
1626 |
phase=self.generation_context.phase,
|
|
1627 |
type='exception',
|
|
1628 |
output=self.generation_context.output,
|
|
1629 |
exception=e))
|
0
|
1630 |
utils.log_exception(logging.getLogger('cone'), 'Impl %r raised an exception: %s' % (impl, repr(e)))
|
|
1631 |
|
|
1632 |
|
|
1633 |
def add_implementation(self,impl):
|
|
1634 |
"""
|
|
1635 |
Add a ImplBase object to this ImplBaseContainer.
|
|
1636 |
"""
|
|
1637 |
self.add(impl)
|
|
1638 |
|
|
1639 |
def remove_implementation(self,ref):
|
|
1640 |
"""
|
|
1641 |
Remove implementation object by its ref (name of the implml resource).
|
|
1642 |
"""
|
|
1643 |
impls_to_remove = []
|
|
1644 |
for impl in self:
|
|
1645 |
if impl.ref == ref:
|
|
1646 |
impls_to_remove.append(impl)
|
|
1647 |
|
|
1648 |
for impl in impls_to_remove:
|
|
1649 |
self.remove(impl)
|
|
1650 |
|
|
1651 |
def list_implementation(self):
|
|
1652 |
"""
|
|
1653 |
List all implementation in this container.
|
|
1654 |
@return: an array of resource references.
|
|
1655 |
"""
|
|
1656 |
implrefs = []
|
|
1657 |
for impl in self:
|
|
1658 |
if impl.ref not in implrefs:
|
|
1659 |
implrefs.append(impl.ref)
|
|
1660 |
return implrefs
|
|
1661 |
|
|
1662 |
def get_implementations_by_file(self, ref):
|
|
1663 |
"""
|
|
1664 |
Return a list of implementations read from the given file.
|
|
1665 |
"""
|
|
1666 |
return filter(lambda impl: impl.ref == ref, self)
|
|
1667 |
|
|
1668 |
def filter_implementations(self,**kwargs):
|
|
1669 |
"""
|
|
1670 |
Find any implementation with certain parameters.
|
|
1671 |
All arguments are given as dict, so they must be given with name. E.g. copy(phase='normal')
|
|
1672 |
@param phase: name of the phase
|
|
1673 |
@param refs: A list of refs that are filtered with function has_refs
|
|
1674 |
@param tags: A dictionary of tags that are filtered with function has_tags
|
|
1675 |
@return: a new ImplSet object with the filtered items.
|
|
1676 |
"""
|
|
1677 |
impls = []
|
|
1678 |
""" Create a list of filter functions for each argument """
|
|
1679 |
filters=[]
|
|
1680 |
filters.append(lambda x: x != None)
|
|
1681 |
if kwargs.get('phase', None) != None:
|
|
1682 |
filters.append(lambda x: kwargs.get('phase') in x.invocation_phase())
|
|
1683 |
if kwargs.get('refs',None) != None:
|
|
1684 |
# Changed has_ref usage to allow not supporting refs (meaning that non supported wont be filtered with refs)
|
|
1685 |
filters.append(lambda x: x.has_ref(kwargs.get('refs')) == True or x.has_ref(kwargs.get('refs')) == None)
|
|
1686 |
if kwargs.get('tags', None) != None:
|
|
1687 |
filters.append(lambda x: x.has_tag(kwargs.get('tags'),kwargs.get('policy')))
|
|
1688 |
|
|
1689 |
""" Go through the implementations and add all to resultset that pass all filters """
|
|
1690 |
for impl in self:
|
|
1691 |
pass_filters = True
|
|
1692 |
for filter in filters:
|
|
1693 |
if not filter(impl):
|
|
1694 |
pass_filters = False
|
|
1695 |
break
|
|
1696 |
if pass_filters:
|
|
1697 |
impls.append(impl)
|
|
1698 |
return ImplSet(impls)
|
|
1699 |
|
3
|
1700 |
def find_implementations(self,**kwargs):
|
|
1701 |
"""
|
|
1702 |
Find any implementation with certain parameters.
|
|
1703 |
All arguments are given as dict, so they must be given with name. E.g. copy(phase='normal')
|
|
1704 |
@param phase: name of the phase
|
|
1705 |
@param refs: A list of refs that are filtered with function has_refs
|
|
1706 |
@param tags: A dictionary of tags that are filtered with function has_tags
|
|
1707 |
@return: a new ImplSet object with the filtered items.
|
|
1708 |
"""
|
|
1709 |
impls = []
|
|
1710 |
""" Create a list of filter functions for each argument """
|
|
1711 |
filters=[]
|
|
1712 |
filters.append(lambda x: x != None)
|
|
1713 |
if kwargs.get('phase', None) != None:
|
|
1714 |
filters.append(lambda x: kwargs.get('phase') in x.invocation_phase())
|
|
1715 |
if kwargs.get('refs',None) != None:
|
|
1716 |
# Changed has_ref usage to allow not supporting refs (meaning that non supported wont be filtered with refs)
|
|
1717 |
filters.append(lambda x: x.has_ref(kwargs.get('refs')) == True)
|
|
1718 |
if kwargs.get('tags', None) != None:
|
|
1719 |
filters.append(lambda x: x.has_tag(kwargs.get('tags'),kwargs.get('policy')))
|
|
1720 |
|
|
1721 |
""" Go through the implementations and add all to resultset that pass all filters """
|
|
1722 |
for impl in self:
|
|
1723 |
pass_filters = True
|
|
1724 |
for filter in filters:
|
|
1725 |
if not filter(impl):
|
|
1726 |
pass_filters = False
|
|
1727 |
break
|
|
1728 |
if pass_filters:
|
|
1729 |
impls.append(impl)
|
|
1730 |
return ImplSet(impls)
|
|
1731 |
|
0
|
1732 |
def flat_compare(self, other):
|
|
1733 |
"""
|
|
1734 |
Perform a flat comparison between this implementation container and another one.
|
|
1735 |
@return: @return: A FlatComparisonResult object.
|
|
1736 |
"""
|
|
1737 |
# Collect dictionaries of all comparable implementation instances
|
|
1738 |
# ---------------------------------------------------------------
|
|
1739 |
source_impls_by_class, duplicates_in_source = self._get_flat_comparison_impl_by_class_dicts('source')
|
|
1740 |
target_impls_by_class, duplicates_in_target = other._get_flat_comparison_impl_by_class_dicts('target')
|
|
1741 |
|
|
1742 |
# Collect a list containing all implementation classes
|
|
1743 |
# ----------------------------------------------------
|
|
1744 |
all_impl_classes = []
|
|
1745 |
for impl_class in source_impls_by_class.iterkeys():
|
|
1746 |
if impl_class not in all_impl_classes:
|
|
1747 |
all_impl_classes.append(impl_class)
|
|
1748 |
for impl_class in target_impls_by_class.iterkeys():
|
|
1749 |
if impl_class not in all_impl_classes:
|
|
1750 |
all_impl_classes.append(impl_class)
|
|
1751 |
|
|
1752 |
# Perform comparison for all classes
|
|
1753 |
# ----------------------------------
|
|
1754 |
result = FlatComparisonResult()
|
|
1755 |
for impl_class in all_impl_classes:
|
|
1756 |
src = source_impls_by_class.get(impl_class, {})
|
|
1757 |
tgt = target_impls_by_class.get(impl_class, {})
|
|
1758 |
temp_result = self._get_flat_comparison_result(impl_class, src, tgt)
|
|
1759 |
result.extend(temp_result)
|
|
1760 |
|
|
1761 |
# Add duplicates into the comparison result
|
|
1762 |
# -----------------------------------------
|
|
1763 |
def get_or_add_dup_entry(impl_type_id, impl_id):
|
|
1764 |
for e in result.duplicate:
|
|
1765 |
if e.impl_type == impl_type_id and e.id == impl_id:
|
|
1766 |
return e
|
|
1767 |
e = DuplicateImplementationEntry(impl_type=impl_type_id, id=impl_id)
|
|
1768 |
result.duplicate.append(e)
|
|
1769 |
return e
|
|
1770 |
|
|
1771 |
for impl_class, impl_type_id, impl_id, file in duplicates_in_source:
|
|
1772 |
entry = get_or_add_dup_entry(impl_type_id, impl_id)
|
|
1773 |
entry.files_in_source.append(file)
|
|
1774 |
for impl_class, impl_type_id, impl_id, file in duplicates_in_target:
|
|
1775 |
entry = get_or_add_dup_entry(impl_type_id, impl_id)
|
|
1776 |
entry.files_in_target.append(file)
|
|
1777 |
|
|
1778 |
# Sort the files so that the output is easier to compare in unit tests
|
|
1779 |
for e in result.duplicate:
|
|
1780 |
e.files_in_source.sort()
|
|
1781 |
e.files_in_target.sort()
|
|
1782 |
|
|
1783 |
return result
|
|
1784 |
|
|
1785 |
def _get_flat_comparison_impl_by_class_dicts(self, name):
|
|
1786 |
result = {}
|
|
1787 |
duplicates = [] # List of (impl_class, impl_type_id, impl_id, file) tuples
|
|
1788 |
for impl in self:
|
|
1789 |
# See if the implementation is flat comparable
|
|
1790 |
try:
|
|
1791 |
impl_id = impl.get_flat_comparison_id()
|
|
1792 |
except exceptions.NotSupportedException:
|
|
1793 |
continue
|
|
1794 |
|
|
1795 |
# Get the dictionary where implementations of this type are collected
|
|
1796 |
impl_class = type(impl)
|
|
1797 |
if impl_class not in result:
|
|
1798 |
result[impl_class] = {}
|
|
1799 |
impls_dict = result[impl_class]
|
|
1800 |
|
|
1801 |
# Add to the dictionary
|
|
1802 |
if impl_id not in impls_dict:
|
|
1803 |
impls_dict[impl_id] = impl
|
|
1804 |
else:
|
|
1805 |
logging.getLogger('cone').warning("Multiple '%s' implementations with ID %r in %s" % (impl.IMPL_TYPE_ID, impl_id, name))
|
|
1806 |
duplicates.append((impl_class, impl.IMPL_TYPE_ID, impl_id, impl.ref))
|
|
1807 |
|
|
1808 |
# Handle duplicates (add new duplicate entries and
|
|
1809 |
# remove from the dictionaries)
|
|
1810 |
new_duplicates = []
|
|
1811 |
for impl_class, impl_type_id, impl_id, _ in duplicates:
|
|
1812 |
# Get the corresponding dictionary
|
|
1813 |
if impl_class not in result: continue
|
|
1814 |
impls_dict = result[impl_class]
|
|
1815 |
if impl_id not in impls_dict: continue
|
|
1816 |
impl = impls_dict[impl_id]
|
|
1817 |
|
|
1818 |
# Add a new entry
|
|
1819 |
new_duplicates.append((impl_class, impl.IMPL_TYPE_ID, impl_id, impl.ref))
|
|
1820 |
|
|
1821 |
# Remove from the dictionary
|
|
1822 |
del impls_dict[impl_id]
|
|
1823 |
duplicates.extend(new_duplicates)
|
|
1824 |
|
|
1825 |
return result, duplicates
|
|
1826 |
|
|
1827 |
def _get_flat_comparison_result(self, impl_class, source_impls_dict, target_impls_dict):
|
|
1828 |
result = FlatComparisonResult()
|
|
1829 |
impl_type_id = impl_class.get_flat_comparison_impl_type_id()
|
|
1830 |
|
|
1831 |
for impl_id, impl in target_impls_dict.iteritems():
|
|
1832 |
if impl_id not in source_impls_dict:
|
|
1833 |
result.only_in_target.append(FlatComparisonResultEntry(
|
|
1834 |
file = impl.ref,
|
|
1835 |
impl_type = impl_type_id,
|
|
1836 |
id = impl_id,
|
|
1837 |
data = impl.get_flat_comparison_extra_data()))
|
|
1838 |
|
|
1839 |
|
|
1840 |
def fill_in_fields(entries, field_values):
|
|
1841 |
for entry in entries:
|
|
1842 |
for varname, value in field_values.iteritems():
|
|
1843 |
setattr(entry, varname, value)
|
|
1844 |
|
|
1845 |
for impl_id, src_impl in source_impls_dict.iteritems():
|
|
1846 |
if impl_id not in target_impls_dict:
|
|
1847 |
result.only_in_source.append(FlatComparisonResultEntry(
|
|
1848 |
file = src_impl.ref,
|
|
1849 |
impl_type = impl_type_id,
|
|
1850 |
id = impl_id,
|
|
1851 |
data = src_impl.get_flat_comparison_extra_data()))
|
|
1852 |
else:
|
|
1853 |
tgt_impl = target_impls_dict[impl_id]
|
|
1854 |
|
|
1855 |
temp_result = src_impl.flat_compare(tgt_impl)
|
|
1856 |
field_values = {'file' : tgt_impl.ref,
|
|
1857 |
'impl_type' : impl_type_id,
|
|
1858 |
'id' : impl_id}
|
|
1859 |
fill_in_fields(temp_result.only_in_source, field_values)
|
|
1860 |
fill_in_fields(temp_result.only_in_target, field_values)
|
|
1861 |
fill_in_fields(temp_result.modified, field_values)
|
|
1862 |
result.extend(temp_result)
|
|
1863 |
|
|
1864 |
return result
|
|
1865 |
|
|
1866 |
def create_temp_features(self, configuration):
|
|
1867 |
"""
|
|
1868 |
Create all temporary features for the implementations in this container.
|
|
1869 |
|
|
1870 |
@param configuration: The configuration where the temporary features are
|
|
1871 |
to be created.
|
|
1872 |
@return: A list containing the references of all created temporary features.
|
|
1873 |
|
3
|
1874 |
@raise exceptions.AlreadyExists: There are duplicate temporary features defined
|
|
1875 |
in the configuration. Redefinitions of the temporaty features are only ignored.
|
0
|
1876 |
"""
|
|
1877 |
# ----------------------------------------------------
|
|
1878 |
# Collect a list of all temporary variable definitions
|
|
1879 |
# and check for duplicates and already existing
|
|
1880 |
# features at the same time
|
|
1881 |
# ----------------------------------------------------
|
|
1882 |
tempvar_defs = []
|
|
1883 |
files_by_refs = {}
|
|
1884 |
dview = configuration.get_default_view()
|
|
1885 |
|
|
1886 |
for impl in self:
|
|
1887 |
for fea_def in impl.get_temp_variable_definitions():
|
|
1888 |
# Check if already exists
|
|
1889 |
try:
|
|
1890 |
dview.get_feature(fea_def.ref)
|
3
|
1891 |
#raise exceptions.AlreadyExists(
|
|
1892 |
# "Temporary variable '%s' defined in file '%s' already exists in the configuration!" \
|
|
1893 |
# % (fea_def.ref, impl.ref))
|
|
1894 |
logging.getLogger('cone').warning("Temporary variable '%s' re-definition ignored." % fea_def.ref)
|
|
1895 |
continue
|
0
|
1896 |
except exceptions.NotFound:
|
|
1897 |
pass
|
|
1898 |
|
|
1899 |
# Add to temporary dictionary for duplicate checking
|
|
1900 |
if fea_def.ref not in files_by_refs:
|
|
1901 |
files_by_refs[fea_def.ref] = []
|
|
1902 |
files_by_refs[fea_def.ref].append(impl.ref)
|
|
1903 |
|
|
1904 |
# Add to the list of all temp feature definitions
|
|
1905 |
tempvar_defs.append(fea_def)
|
|
1906 |
|
|
1907 |
# Check for duplicates
|
|
1908 |
for ref, file_list in files_by_refs.iteritems():
|
|
1909 |
if len(file_list) > 1:
|
|
1910 |
raise exceptions.AlreadyExists(
|
|
1911 |
"Duplicate temporary variable! '%s' defined in the following files: %r" \
|
|
1912 |
% (ref, file_list))
|
|
1913 |
del files_by_refs
|
|
1914 |
|
|
1915 |
|
|
1916 |
# ------------------------------
|
|
1917 |
# Create the temporary variables
|
|
1918 |
# ------------------------------
|
|
1919 |
refs = []
|
|
1920 |
if tempvar_defs:
|
3
|
1921 |
logging.getLogger('cone').debug('Creating %d temporary variable(s) %r' % (len(tempvar_defs), tempvar_defs))
|
0
|
1922 |
autoconfig = get_autoconfig(configuration)
|
|
1923 |
for fea_def in tempvar_defs:
|
|
1924 |
fea_def.create_feature(autoconfig)
|
|
1925 |
refs.append(fea_def.ref)
|
|
1926 |
|
|
1927 |
# The default view needs to be recreated, or the created
|
|
1928 |
# features will not be visible there
|
|
1929 |
configuration.recreate_default_view()
|
|
1930 |
return refs
|
|
1931 |
|
|
1932 |
def get_relation_container(self):
|
|
1933 |
"""
|
|
1934 |
Return a relation container containing all rules from this set
|
|
1935 |
of implementation instances.
|
|
1936 |
"""
|
|
1937 |
container = RelationContainer([], '<root>')
|
|
1938 |
for impl in self:
|
|
1939 |
c = impl.get_relation_container()
|
|
1940 |
if isinstance(c, RelationContainer):
|
|
1941 |
container.entries.append(c)
|
|
1942 |
return container
|
|
1943 |
|
|
1944 |
def get_all_implementations(self):
|
|
1945 |
"""
|
|
1946 |
Return a flattened list of all implementation instances in this set.
|
|
1947 |
|
|
1948 |
The returned list contains only actual implementation instances, not
|
|
1949 |
ImplContainer objects.
|
|
1950 |
"""
|
|
1951 |
# Get a list of implementation objects sorted by file name
|
|
1952 |
impl_list = list(self)
|
|
1953 |
impl_list.sort(key=lambda impl: impl.ref)
|
|
1954 |
|
|
1955 |
result = []
|
|
1956 |
for impl in impl_list:
|
|
1957 |
result += impl.get_all_implementations()
|
|
1958 |
return result
|
|
1959 |
|
3
|
1960 |
def get_implemented_refs(self):
|
|
1961 |
if not self.ref_to_impl:
|
|
1962 |
self._create_ref_dict()
|
|
1963 |
return sorted(self.ref_to_impl.keys())
|
|
1964 |
|
|
1965 |
def get_implementations_with_ref(self, ref):
|
|
1966 |
if not self.ref_to_impl:
|
|
1967 |
self._create_ref_dict()
|
|
1968 |
return sorted(self.ref_to_impl.get(ref, []), lambda a,b: cmp(a.ref, b.ref))
|
|
1969 |
|
0
|
1970 |
class RelationExecutionResult(object):
|
|
1971 |
"""
|
|
1972 |
Class representing a result from relation execution.
|
|
1973 |
"""
|
|
1974 |
def __init__(self, input_refs, affected_refs, source=None, index=None):
|
|
1975 |
"""
|
|
1976 |
@param input_refs: Input references, i.e. the references on the left side of
|
|
1977 |
the relation.
|
|
1978 |
@param affected_refs: Affected references, i.e. the references of the setting
|
|
1979 |
that have been assigned something as a result of the relation execution.
|
|
1980 |
@param source: The source of the relation. Can be e.g. the path to a RuleML file.
|
|
1981 |
@param index: The index (number) of the relation in the source. This could be
|
|
1982 |
e.g. 1 to denote the first rule in a RuleML file.
|
|
1983 |
"""
|
|
1984 |
self.input_refs = input_refs
|
|
1985 |
self.affected_refs = affected_refs
|
|
1986 |
self.source = source
|
|
1987 |
self.index = index
|
|
1988 |
|
|
1989 |
def __repr__(self):
|
|
1990 |
return "RelationExecutionResult(input_refs=%r, affected_refs=%r, source=%r, index=%r)" \
|
|
1991 |
% (sorted(self.input_refs), sorted(self.affected_refs), self.source, self.index)
|
|
1992 |
|
|
1993 |
def __eq__(self, other):
|
|
1994 |
if type(self) is not type(other):
|
|
1995 |
return False
|
|
1996 |
return sorted(self.input_refs) == sorted(other.input_refs) \
|
|
1997 |
and sorted(self.affected_refs) == sorted(other.affected_refs) \
|
|
1998 |
and self.source == other.source \
|
|
1999 |
and self.index == other.index
|
|
2000 |
|
|
2001 |
def __ne__(self, other):
|
|
2002 |
return not (self == other)
|
|
2003 |
|
|
2004 |
class RelationContainer(object):
|
|
2005 |
"""
|
|
2006 |
A relation container that may contain relations or other
|
|
2007 |
RelationContainer objects.
|
|
2008 |
"""
|
|
2009 |
def __init__(self, entries=[], source=None):
|
|
2010 |
"""
|
|
2011 |
@param entries: The relations or relation containers to be added.
|
|
2012 |
@param source: The source of the relations in this container. Can be
|
|
2013 |
e.g. the path to a RuleML file.
|
|
2014 |
"""
|
|
2015 |
self.entries = entries
|
|
2016 |
self.source = source
|
|
2017 |
|
3
|
2018 |
def execute(self, context=None):
|
0
|
2019 |
"""
|
|
2020 |
Execute all relations inside the container, logging any exceptions thrown
|
|
2021 |
during the execution.
|
|
2022 |
@return: A list of RelationExecutionResult objects.
|
|
2023 |
"""
|
|
2024 |
results = []
|
|
2025 |
for i, entry in enumerate(self.entries):
|
3
|
2026 |
|
0
|
2027 |
if isinstance(entry, rules.RelationBase):
|
3
|
2028 |
result = self._execute_relation_and_log_error(entry, self.source, i + 1, context)
|
0
|
2029 |
if isinstance(RelationExecutionResult):
|
|
2030 |
results.append(result)
|
|
2031 |
elif isinstance(entry, RelationContainer):
|
3
|
2032 |
results.extend(self._execute_container_and_log_error(entry, context))
|
0
|
2033 |
else:
|
|
2034 |
logging.getLogger('cone').warning("Invalid RelationContainer entry: type=%s, obj=%r" % (type(entry), entry))
|
|
2035 |
return results
|
|
2036 |
|
3
|
2037 |
def _execute_relation_and_log_error(self, relation, source, index, context=None):
|
0
|
2038 |
"""
|
|
2039 |
Execute a relation, logging any exceptions that may be thrown.
|
|
2040 |
@param relation: The relation to execute.
|
|
2041 |
@param source: The source of the rule.
|
|
2042 |
@param index: The index of the rule, can be None if the index is not known.
|
|
2043 |
@return: The return value from the relation execution, or None if an error occurred.
|
|
2044 |
"""
|
3
|
2045 |
try:
|
|
2046 |
return relation.execute(context)
|
0
|
2047 |
except Exception, e:
|
3
|
2048 |
msg = "Error executing rule %r: %s: %s" % (relation, e.__class__.__name__, e)
|
|
2049 |
if context:
|
|
2050 |
gout = GenerationOutput('exception from %s' % source,
|
|
2051 |
relation,
|
|
2052 |
phase=context.phase,
|
|
2053 |
type='exception',
|
|
2054 |
output=context.output,
|
|
2055 |
exception=msg)
|
|
2056 |
context.generation_output.append(gout)
|
|
2057 |
utils.log_exception(logging.getLogger('cone'), msg)
|
0
|
2058 |
return None
|
|
2059 |
|
3
|
2060 |
def _execute_container_and_log_error(self, container, context):
|
0
|
2061 |
"""
|
|
2062 |
Execute a relation container, logging any exceptions that may be thrown.
|
|
2063 |
@param relation: The relation container to execute.
|
|
2064 |
@return: The results from the relation execution, or an empty list if an error occurred.
|
|
2065 |
"""
|
|
2066 |
try:
|
3
|
2067 |
return container.execute(context)
|
0
|
2068 |
except Exception, e:
|
|
2069 |
log = logging.getLogger('cone')
|
3
|
2070 |
utils.log_exception(log, "Exception executing rules in '%s': %s" % container.source, e)
|
0
|
2071 |
return []
|
|
2072 |
|
|
2073 |
def get_relation_count(self):
|
|
2074 |
"""
|
|
2075 |
Return the number of relations in this container.
|
|
2076 |
"""
|
|
2077 |
count = 0
|
|
2078 |
for entry in self.entries:
|
|
2079 |
if isinstance(entry, RelationContainer):
|
|
2080 |
count += entry.get_relation_count()
|
|
2081 |
else:
|
|
2082 |
count += 1
|
|
2083 |
return count
|
|
2084 |
|
3
|
2085 |
def get_relations(self):
|
|
2086 |
"""
|
|
2087 |
Return a list of all relations in this container.
|
|
2088 |
"""
|
|
2089 |
result = []
|
|
2090 |
for entry in self.entries:
|
|
2091 |
if isinstance(entry, RelationContainer):
|
|
2092 |
result.extend(entry.get_relations())
|
|
2093 |
else:
|
|
2094 |
result.append(entry)
|
|
2095 |
return result
|
|
2096 |
|
0
|
2097 |
|
|
2098 |
class ImplFactory(api.FactoryBase):
|
|
2099 |
|
|
2100 |
__registered_reader_classes = None
|
|
2101 |
__registered_reader_classes_override = None
|
|
2102 |
__common_reader_classes = [ImplContainerReader]
|
|
2103 |
|
|
2104 |
@classmethod
|
|
2105 |
def get_reader_classes(cls):
|
|
2106 |
"""
|
|
2107 |
return a list of reader classes
|
|
2108 |
"""
|
|
2109 |
reader_classes = cls.__common_reader_classes[:]
|
|
2110 |
# If the reader class list is overridden, return that
|
|
2111 |
if cls.__registered_reader_classes_override is not None:
|
|
2112 |
reader_classes += cls.__registered_reader_classes_override
|
|
2113 |
else:
|
|
2114 |
# Load the classes if not loaded already
|
|
2115 |
if cls.__registered_reader_classes is None:
|
|
2116 |
cls.__registered_reader_classes = cls.__load_reader_classes()
|
|
2117 |
reader_classes += cls.__registered_reader_classes
|
|
2118 |
|
|
2119 |
return reader_classes
|
|
2120 |
|
|
2121 |
@classmethod
|
|
2122 |
def get_reader_dict(cls):
|
|
2123 |
"""
|
|
2124 |
return a dictionary of reader classes, where key is the reader namespace
|
|
2125 |
"""
|
|
2126 |
reader_dict = {}
|
|
2127 |
for reader in cls.get_reader_classes():
|
|
2128 |
reader_dict[reader.NAMESPACE] = reader
|
|
2129 |
return reader_dict
|
|
2130 |
|
|
2131 |
@classmethod
|
|
2132 |
def get_supported_file_extensions(cls):
|
|
2133 |
"""
|
|
2134 |
return a dictionary of reader classes, where key is the reader namespace
|
|
2135 |
"""
|
|
2136 |
file_extensions = []
|
|
2137 |
for reader in cls.get_reader_classes():
|
|
2138 |
for fe in reader.FILE_EXTENSIONS:
|
3
|
2139 |
fe = fe.lower()
|
|
2140 |
if fe not in file_extensions:
|
|
2141 |
file_extensions.append(fe)
|
0
|
2142 |
return file_extensions
|
|
2143 |
|
|
2144 |
@classmethod
|
|
2145 |
def set_reader_classes_override(cls, reader_classes):
|
|
2146 |
"""
|
|
2147 |
Override the list of registered reader classes.
|
|
2148 |
|
|
2149 |
This method is provided for unit tests.
|
|
2150 |
@param reader_classes: Reader class list to use as override. Pass None to
|
|
2151 |
disable overriding.
|
|
2152 |
"""
|
|
2153 |
cls.__registered_reader_classes_override = reader_classes
|
|
2154 |
|
|
2155 |
@classmethod
|
|
2156 |
def force_reload_reader_classes(cls):
|
|
2157 |
"""
|
|
2158 |
Force-reload all reader classes.
|
|
2159 |
"""
|
|
2160 |
cls.__registered_reader_classes = cls.__load_reader_classes()
|
|
2161 |
|
|
2162 |
@classmethod
|
|
2163 |
def __load_reader_classes(cls):
|
|
2164 |
"""
|
|
2165 |
Load all registered ImplML reader classes from plug-ins.
|
|
2166 |
"""
|
|
2167 |
log = logging.getLogger('cone')
|
|
2168 |
log.setLevel(logging.DEBUG)
|
|
2169 |
reader_classes = []
|
|
2170 |
ENTRY_POINT = 'cone.plugins.implmlreaders'
|
|
2171 |
|
|
2172 |
import pkg_resources
|
|
2173 |
working_set = pkg_resources.WorkingSet(sys.path)
|
|
2174 |
for entry_point in working_set.iter_entry_points(ENTRY_POINT):
|
|
2175 |
reader_class = entry_point.load()
|
|
2176 |
if not inspect.isclass(reader_class):
|
|
2177 |
log.warn("'%s' entry point '%s' is not a class (%r)" % (ENTRY_POINT, entry_point.name, reader_class))
|
|
2178 |
elif not issubclass(reader_class, ReaderBase):
|
|
2179 |
log.warn("'%s' entry point '%s' is not a sub-class of cone.plugin.ReaderBase (%r)" % (ENTRY_POINT, entry_point.name, reader_class))
|
|
2180 |
else:
|
|
2181 |
msg = "Reader class for XML namespace '%s' loaded from egg '%s' entry point '%s'" % (reader_class.NAMESPACE, ENTRY_POINT, entry_point.name)
|
3
|
2182 |
#log.debug(msg)
|
0
|
2183 |
#print msg
|
|
2184 |
reader_classes.append(reader_class)
|
|
2185 |
|
|
2186 |
return reader_classes
|
|
2187 |
|
|
2188 |
@classmethod
|
|
2189 |
def is_supported_impl_file(cls, file_name):
|
|
2190 |
"""
|
|
2191 |
Return whether the given file is a supported implementation file.
|
|
2192 |
"""
|
|
2193 |
ext = os.path.splitext(file_name)[1]
|
|
2194 |
if ext is not None:
|
|
2195 |
return ext[1:].lower() in cls.get_supported_file_extensions()
|
|
2196 |
else:
|
|
2197 |
return False
|
|
2198 |
|
|
2199 |
@classmethod
|
|
2200 |
def get_impls_from_file(cls, resource_ref, configuration):
|
|
2201 |
"""
|
|
2202 |
Get a list of implementation instances from the given file (resource in a configuration).
|
|
2203 |
|
|
2204 |
@param resource_ref: Reference of the resource to read the impls from.
|
|
2205 |
@param configuration: The configuration to use.
|
|
2206 |
@return: List of implementation instances parsed and created from the file.
|
|
2207 |
|
|
2208 |
@raise NotSupportedException: The file contains an XML namespace that is
|
|
2209 |
not registered as an ImplML namespace.
|
|
2210 |
"""
|
3
|
2211 |
context = parsecontext.get_implml_context()
|
|
2212 |
context.current_file = resource_ref
|
0
|
2213 |
try:
|
3
|
2214 |
resource = configuration.get_resource(resource_ref)
|
|
2215 |
try: data = resource.read()
|
|
2216 |
finally: resource.close()
|
|
2217 |
|
|
2218 |
# Schema-validation while parsing disabled for now
|
|
2219 |
#cone.validation.schemavalidation.validate_implml_data(data)
|
|
2220 |
|
0
|
2221 |
impls = []
|
|
2222 |
reader_dict = cls.get_reader_dict()
|
3
|
2223 |
|
|
2224 |
root = utils.etree.fromstring(data)
|
0
|
2225 |
ns = utils.xml.split_tag_namespace(root.tag)[0]
|
|
2226 |
if ns not in reader_dict.keys():
|
3
|
2227 |
context.handle_problem(api.Problem("No reader for namespace '%s'" % ns,
|
|
2228 |
type="xml.implml",
|
|
2229 |
file=resource_ref,
|
|
2230 |
line=utils.etree.get_lineno(root)))
|
|
2231 |
#logging.getLogger('cone').error("Error: no reader for namespace '%s' in %s" % (ns, resource_ref))
|
0
|
2232 |
return []
|
|
2233 |
rc = reader_dict[ns]
|
|
2234 |
# return the single implementation as a list to maintain
|
|
2235 |
# backwards compability
|
|
2236 |
impl = rc.read_impl(resource_ref, configuration, root)
|
|
2237 |
impl.index = 0
|
3
|
2238 |
impl.lineno = utils.etree.get_lineno(root)
|
0
|
2239 |
return [impl]
|
3
|
2240 |
except Exception, e:
|
|
2241 |
if isinstance(e, exceptions.XmlParseError):
|
|
2242 |
e.problem_type = 'xml.implml'
|
|
2243 |
context.handle_exception(e)
|
0
|
2244 |
return []
|
|
2245 |
|
|
2246 |
def get_impl_set(configuration,filter='.*'):
|
|
2247 |
"""
|
|
2248 |
return a ImplSet object that contains all implementation objects related to the
|
|
2249 |
given configuration
|
|
2250 |
"""
|
3
|
2251 |
impls = configuration.layered_implml().flatten().values()
|
0
|
2252 |
impls = pre_filter_impls(impls)
|
|
2253 |
# filter the resources with a given filter
|
|
2254 |
impls = utils.resourceref.filter_resources(impls,filter)
|
3
|
2255 |
impl_set = create_impl_set(impls,configuration)
|
|
2256 |
return impl_set
|
0
|
2257 |
|
|
2258 |
def filtered_impl_set(configuration,pathfilters=None, reffilters=None):
|
|
2259 |
"""
|
|
2260 |
return a ImplSet object that contains all implementation objects related to the
|
|
2261 |
given configuration
|
|
2262 |
"""
|
|
2263 |
if pathfilters: logging.getLogger('cone').info('Filtering impls with %s' % pathfilters)
|
3
|
2264 |
impls = configuration.layered_implml().flatten().values()
|
0
|
2265 |
impls = pre_filter_impls(impls)
|
|
2266 |
# filter the resources with a given filter
|
|
2267 |
if pathfilters:
|
|
2268 |
newimpls = []
|
|
2269 |
for filter in pathfilters:
|
|
2270 |
newimpls += utils.resourceref.filter_resources(impls,filter)
|
|
2271 |
impls = utils.distinct_array(newimpls)
|
3
|
2272 |
impl_set = create_impl_set(impls,configuration,reffilters)
|
|
2273 |
return impl_set
|
0
|
2274 |
|
|
2275 |
def create_impl_set(impl_filename_list, configuration,reffilters=None):
|
|
2276 |
impl_filename_list = pre_filter_impls(impl_filename_list)
|
|
2277 |
if reffilters: logging.getLogger('cone').info('Filtering with refs %s' % reffilters)
|
|
2278 |
impl_container = ImplSet()
|
3
|
2279 |
impl_container.generation_context = GenerationContext()
|
|
2280 |
impl_container.generation_context.configuration = configuration
|
0
|
2281 |
for impl in impl_filename_list:
|
|
2282 |
try:
|
|
2283 |
if configuration != None and ImplFactory.is_supported_impl_file(impl):
|
|
2284 |
plugin_impls = ImplFactory.get_impls_from_file(impl, configuration)
|
|
2285 |
for plugin_impl in plugin_impls:
|
|
2286 |
if not reffilters or plugin_impl.has_ref(reffilters):
|
|
2287 |
impl_container.add_implementation(plugin_impl)
|
|
2288 |
except Exception, e:
|
|
2289 |
utils.log_exception(logging.getLogger('cone'), "Creating impl '%s' failed. Exception: %s" % (impl,e))
|
|
2290 |
continue
|
|
2291 |
return impl_container
|
|
2292 |
|
|
2293 |
def pre_filter_impls(impls):
|
|
2294 |
"""
|
|
2295 |
Pre-filter implementation file refs so that files and directories
|
|
2296 |
beginning with a dot (e.g. '.svn', '.scripts') are ignored.
|
|
2297 |
"""
|
|
2298 |
filter = r'(/|^|\\)\..*(/|$|\\)'
|
|
2299 |
return utils.resourceref.neg_filter_resources(impls, filter)
|
3
|
2300 |
|
|
2301 |
def read_impl_from_location(resource_ref, configuration, lineno):
|
|
2302 |
return ReaderBase.read_impl_from_location(resource_ref, configuration, lineno)
|