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