summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFranois Gaffie <francois.gaffie@renault.com>2019-10-10 09:14:51 -0700
committerandroid-build-merger <android-build-merger@google.com>2019-10-10 09:14:51 -0700
commita37ebc0705c9f37fb4ba9f2889f7098add684c73 (patch)
tree688ee97102b8bf643921261a04cef7273cfd42cc
parentff866bab591a5f997cb960572fed300fde454bd1 (diff)
parent38e4d991fe14c31baa024d8070e604edc3a60bd7 (diff)
downloadparameter-framework-a37ebc0705c9f37fb4ba9f2889f7098add684c73.tar.gz
Switch to python 3 - run pylint am: 06f9d1430a am: 731c2cb78f am: bcaf3eb6cd
am: 38e4d991fe Change-Id: I787f517950334c73bcea3cec55f589549e6f9ec9
-rw-r--r--Android.bp20
-rwxr-xr-xupstream/tools/coverage/coverage.py322
-rwxr-xr-xupstream/tools/xmlGenerator/EddParser.py292
-rwxr-xr-xupstream/tools/xmlGenerator/PFWScriptGenerator.py37
-rw-r--r--upstream/tools/xmlGenerator/PfwBaseTranslator.py8
-rwxr-xr-xupstream/tools/xmlGenerator/domainGenerator.py153
-rwxr-xr-xupstream/tools/xmlGenerator/hostConfig.py4
-rwxr-xr-xupstream/tools/xmlValidator/xmlValidator.py9
8 files changed, 426 insertions, 419 deletions
diff --git a/Android.bp b/Android.bp
index 57f7b36..a1fb36f 100644
--- a/Android.bp
+++ b/Android.bp
@@ -336,10 +336,10 @@ python_library_host {
srcs: [":EddParser.py-srcs"],
version: {
py2: {
- enabled: true,
+ enabled: false,
},
py3: {
- enabled: false,
+ enabled: true,
},
},
}
@@ -358,10 +358,10 @@ python_library_host {
srcs: [":PfwBaseTranslator.py-srcs"],
version: {
py2: {
- enabled: true,
+ enabled: false,
},
py3: {
- enabled: false,
+ enabled: true,
},
},
}
@@ -384,10 +384,10 @@ python_library_host {
],
version: {
py2: {
- enabled: true,
+ enabled: false,
},
py3: {
- enabled: false,
+ enabled: true,
},
},
}
@@ -414,10 +414,10 @@ python_library_host {
srcs: [":hostConfig.py-srcs"],
version: {
py2: {
- enabled: true,
+ enabled: false,
},
py3: {
- enabled: false,
+ enabled: true,
},
},
}
@@ -436,10 +436,10 @@ python_binary_host {
],
version: {
py2: {
- enabled: true,
+ enabled: false,
},
py3: {
- enabled: false,
+ enabled: true,
},
},
required: [
diff --git a/upstream/tools/coverage/coverage.py b/upstream/tools/coverage/coverage.py
index 0a23285..bbc96c5 100755
--- a/upstream/tools/coverage/coverage.py
+++ b/upstream/tools/coverage/coverage.py
@@ -99,21 +99,21 @@ class Element():
def _getDescendants(self):
for child in self.children:
yield child
- for descendant in child._getDescendants() :
+ for descendant in child._getDescendants():
yield descendant
def getChildFromName(self, childName):
- for child in self.children :
+ for child in self.children:
- if child.getName() == childName :
+ if child.getName() == childName:
return child
self.debug('Child "%s" not found' % childName, logging.ERROR)
self.debug("Child list :")
- for child in self.children :
+ for child in self.children:
self.debug(" - %s" % child)
raise ChildNotFoundError(self, childName)
@@ -134,10 +134,10 @@ class Element():
def _description(self, withCoverage, withNbUse):
description = self.name
- if withNbUse or withCoverage :
+ if withNbUse or withCoverage:
description += " has been used " + str(self.nbUse) + " time"
- if withCoverage :
+ if withCoverage:
description += self._coverageFormating(self._getCoverage())
return description
@@ -159,7 +159,7 @@ class Element():
return 1
coverageDependenceValues = (depElement._getCoverage()
- for depElement in coverageDependanceElements)
+ for depElement in coverageDependanceElements)
return sum(coverageDependenceValues) / nbcoverageDependence
@@ -168,7 +168,7 @@ class Element():
def _coverageFormating(self, coverage):
# If no coverage provided
- if not coverage :
+ if not coverage:
return ""
# Calculate coverage
@@ -188,21 +188,20 @@ class Element():
self.debug("yelding description")
yield RankedLine(self._description(withCoverage, withNbUse), lineSuffix="")
- for dumped in self._dumpPropagate(withCoverage, withNbUse) :
+ for dumped in self._dumpPropagate(withCoverage, withNbUse):
yield dumped
def _dumpPropagate(self, withCoverage, withNbUse):
- for child in self.children :
- for dumpedDescription in child._dumpDescription(withCoverage, withNbUse) :
+ for child in self.children:
+ for dumpedDescription in child._dumpDescription(withCoverage, withNbUse):
yield dumpedDescription.increasedRank()
def dump(self, withCoverage=False, withNbUse=True):
- return "\n".join(
- str(dumpedDescription) for dumpedDescription in
- self._dumpDescription(withCoverage, withNbUse))
+ return "\n".join(str(dumpedDescription) for dumpedDescription in
+ self._dumpDescription(withCoverage, withNbUse))
def exportToXML(self, document, domElement=None):
if domElement == None:
@@ -210,7 +209,7 @@ class Element():
self._XMLaddAttributes(domElement)
- for child in self.children :
+ for child in self.children:
domElement.appendChild(child.exportToXML(document))
return domElement
@@ -219,17 +218,16 @@ class Element():
attributes = self._getXMLAttributes()
coverage = self._getCoverage()
- if coverage != None :
+ if coverage != None:
attributes["Coverage"] = self._number2percent(coverage)
for key, value in attributes.items():
domElement.setAttribute(key, value)
def _getXMLAttributes(self):
- return {
- "Name": self.name,
+ return {"Name": self.name,
"NbUse": str(self.nbUse)
- }
+ }
def _incNbUse(self):
self.nbUse += 1
@@ -240,14 +238,14 @@ class Element():
self._tellParentThatChildUsed()
def _tellParentThatChildUsed(self):
- if self.parent :
+ if self.parent:
self.parent.childUsed(self)
def parentUsed(self):
self._incNbUse()
# Propagate to children
- for child in self.children :
+ for child in self.children:
child.parentUsed()
def hasBeenUsed(self):
@@ -257,7 +255,7 @@ class Element():
if path:
return self._operationPropagate(path, operation)
- else :
+ else:
self.debug("operating on self")
return operation(self)
@@ -292,7 +290,7 @@ class Element():
if self.parent:
self.parent._logDebug(rankedLine.increasedRank(), level)
- else :
+ else:
logger.log(level, str(rankedLine))
@@ -312,9 +310,9 @@ class FromDomElement(Element):
class DomElementLocation():
def __init__(self, classConstructor, path=None):
self.classConstructor = classConstructor
- if path :
+ if path:
self.path = path
- else :
+ else:
self.path = []
self.path.append(classConstructor.tag)
@@ -330,12 +328,12 @@ class DomPopulatedElement(Element):
def populate(self, dom):
- for childDomElementLocation in self.childClasses :
+ for childDomElementLocation in self.childClasses:
self.debug("Looking for child %s in path %s" % (
childDomElementLocation.path[-1], childDomElementLocation.path))
- for childDomElement in self._findChildFromTagPath(dom, childDomElementLocation.path) :
+ for childDomElement in self._findChildFromTagPath(dom, childDomElementLocation.path):
childElement = childDomElementLocation.classConstructor(childDomElement)
self.addChild(childElement)
@@ -343,9 +341,9 @@ class DomPopulatedElement(Element):
childElement.populate(childDomElement)
def _findChildFromTagPath(self, dom, path):
- if not path :
+ if not path:
yield dom
- else :
+ else:
# Copy list
path = list(path)
@@ -355,15 +353,15 @@ class DomPopulatedElement(Element):
self.debug("Going to find elements with tag %s in %s" % (tag, dom))
self.debug(lambda: "Nb of solutions: %s" % len(dom.getElementsByTagName(tag)))
- for elementByTag in dom.getElementsByTagName(tag) :
+ for elementByTag in dom.getElementsByTagName(tag):
self.debug("Found element: %s" % elementByTag)
# If the same tag is found
- if elementByTag in dom.childNodes :
+ if elementByTag in dom.childNodes:
# Yield next level
- for element in self._findChildFromTagPath(elementByTag, path) :
+ for element in self._findChildFromTagPath(elementByTag, path):
yield element
@@ -371,11 +369,11 @@ class Rule(Element):
def usedIfApplicable(self, criteria):
childApplicability = (child.usedIfApplicable(criteria)
- for child in self.children)
+ for child in self.children)
isApplicable = self._isApplicable(criteria, childApplicability)
- if isApplicable :
+ if isApplicable:
self._incNbUse()
self.debug("Rule applicability: %s" % isApplicable)
@@ -396,11 +394,11 @@ class CriterionRule(FromDomElement, DomPopulatedElement, Rule):
tag = "SelectionCriterionRule"
childClasses = []
isApplicableOperations = {
- "Includes" : lambda criterion, value: criterion.stateIncludes(value),
- "Excludes" : lambda criterion, value: not criterion.stateIncludes(value),
- "Is" : lambda criterion, value: criterion.stateIs(value),
- "IsNot" : lambda criterion, value: not criterion.stateIs(value)
- }
+ "Includes" : lambda criterion, value: criterion.stateIncludes(value),
+ "Excludes" : lambda criterion, value: not criterion.stateIncludes(value),
+ "Is" : lambda criterion, value: criterion.stateIs(value),
+ "IsNot" : lambda criterion, value: not criterion.stateIs(value)
+ }
def _initFromDom(self, DomElement):
self.selectionCriterion = DomElement.getAttribute("SelectionCriterion")
@@ -409,12 +407,12 @@ class CriterionRule(FromDomElement, DomPopulatedElement, Rule):
self.name = "%s %s %s" % (self.selectionCriterion, self.matchesWhen, self.value)
applicableOperationWithoutValue = self.isApplicableOperations[self.matchesWhen]
- self.isApplicableOperation = lambda criterion: applicableOperationWithoutValue(criterion, self.value)
+ self.isApplicableOperation = lambda criterion: applicableOperationWithoutValue(criterion,
+ self.value)
def _isApplicable(self, criteria, childApplicability):
- return criteria.operationOnChild([self.selectionCriterion],
- self.isApplicableOperation)
+ return criteria.operationOnChild([self.selectionCriterion], self.isApplicableOperation)
class CompoundRule(FromDomElement, DomPopulatedElement, Rule):
@@ -425,9 +423,9 @@ class CompoundRule(FromDomElement, DomPopulatedElement, Rule):
def __init__(self, dom):
# Define childClasses at first class instantiation
- if self.childClasses == None :
+ if self.childClasses == None:
self.childClasses = [DomElementLocation(CriterionRule),
- DomElementLocation(CompoundRule)]
+ DomElementLocation(CompoundRule)]
super().__init__(dom)
def _initFromDom(self, DomElement):
@@ -437,7 +435,7 @@ class CompoundRule(FromDomElement, DomPopulatedElement, Rule):
self.name = type
def _isApplicable(self, criteria, childApplicability):
- if self.ofTypeAll :
+ if self.ofTypeAll:
applicability = super()._isApplicable(criteria, childApplicability)
else:
# Lazy evaluation as in the PFW
@@ -471,10 +469,10 @@ class CriteronStates(Element):
assert(len(matches) <= 1)
- if matches :
+ if matches:
self.debug("Criteria state has already been encounter")
currentcriteria = matches[0]
- else :
+ else:
self.debug("Criteria state has never been encounter, saving it")
currentcriteria = criteria
self.addChild(criteria)
@@ -496,11 +494,11 @@ class Configuration(FromDomElement, DomPopulatedElement):
def __str__(self):
return ("Applying ineligible %s, "
- "rule:\n%s\n"
- "Criteria current state:\n%s" % (
- self.configuration,
- self.configuration.rootRule.dump(withCoverage=False, withNbUse=False),
- self.criteria.dump(withCoverage=False, withNbUse=False)
+ "rule:\n%s\n"
+ "Criteria current state:\n%s" % (
+ self.configuration,
+ self.configuration.rootRule.dump(withCoverage=False, withNbUse=False),
+ self.criteria.dump(withCoverage=False, withNbUse=False)
))
def __init__(self, DomElement):
@@ -531,11 +529,11 @@ class Configuration(FromDomElement, DomPopulatedElement):
self.criteronStates.parentUsed(criteria.export())
# Propagate to rules
- if not self.rootRule.usedIfApplicable(criteria) :
+ if not self.rootRule.usedIfApplicable(criteria):
self.debug("Applied but rule does not match current "
"criteria (parent: %s) " % self.parent.name,
- logging.ERROR)
+ logging.ERROR)
raise self.IneligibleConfigurationAppliedError(self, criteria.export())
@@ -543,13 +541,13 @@ class Configuration(FromDomElement, DomPopulatedElement):
self.debug("Going to ask %s for description" % self.rootRule)
for dumpedDescription in self.rootRule._dumpDescription(
withCoverage=withCoverage,
- withNbUse=withNbUse) :
+ withNbUse=withNbUse):
yield dumpedDescription.increasedRank()
self.debug("Going to ask %s for description" % self.criteronStates)
for dumpedDescription in self.criteronStates._dumpDescription(
withCoverage=False,
- withNbUse=withNbUse) :
+ withNbUse=withNbUse):
yield dumpedDescription.increasedRank()
@@ -565,10 +563,10 @@ class Domains(DomPopulatedElement):
class RankedLine():
def __init__(self, string,
- stringPrefix="|-- ",
- rankString="| ",
- linePrefix="",
- lineSuffix="\n"):
+ stringPrefix="|-- ",
+ rankString="| ",
+ linePrefix="",
+ lineSuffix="\n"):
self.string = string
self.rank = 0
self.stringPrefix = stringPrefix
@@ -591,10 +589,10 @@ class DebugRankedLine(RankedLine):
def __init__(self, string, lineSuffix=""):
super().__init__(string,
- stringPrefix="",
- rankString=" ",
- linePrefix="",
- lineSuffix=lineSuffix)
+ stringPrefix="",
+ rankString=" ",
+ linePrefix="",
+ lineSuffix=lineSuffix)
class CriterionState(Element):
@@ -614,15 +612,15 @@ class Criterion(Element):
def __str__(self):
return ("Change request to non accessible state %s. Detail: %s" %
- (self.requestedState, self.detail))
+ (self.requestedState, self.detail))
def __init__(self, name, isInclusif,
- stateNamesList, currentStateNamesList,
- ignoreIntegrity=False):
+ stateNamesList, currentStateNamesList,
+ ignoreIntegrity=False):
super().__init__(name)
self.isInclusif = isInclusif
- for state in stateNamesList :
+ for state in stateNamesList:
self.addChild(CriterionState(state))
self.currentState = []
@@ -635,15 +633,16 @@ class Criterion(Element):
def changeState(self, subStateNames, ignoreIntegrity=False):
self.debug("Changing state from: %s to: %s" % (
- list(self._getElementNames(self.currentState)),
- subStateNames))
+ list(self._getElementNames(self.currentState)),
+ subStateNames))
if not ignoreIntegrity and not self.isIntegre(subStateNames):
raise self.ChangeRequestToNonAccessibleState(subStateNames,
- "An exclusive criterion must have a non empty state")
+ "An exclusive criterion must have a non \
+ empty state")
newCurrentState = []
- for subStateName in subStateNames :
+ for subStateName in subStateNames:
subState = self.getChildFromName(subStateName)
subState.used()
newCurrentState.append(subState)
@@ -663,7 +662,7 @@ class Criterion(Element):
def export(self):
subStateNames = self._getElementNames(self.currentState)
return Criterion(self.name, self.isInclusif, subStateNames, subStateNames,
- ignoreIntegrity=True)
+ ignoreIntegrity=True)
def stateIncludes(self, subStateName):
subStateCurrentNames = list(self._getElementNames(self.currentState))
@@ -677,9 +676,9 @@ class Criterion(Element):
def stateIs(self, subStateNames):
- if len(self.currentState) != 1 :
+ if len(self.currentState) != 1:
return False
- else :
+ else:
return self.stateIncludes(subStateNames)
def _getXMLAttributes(self):
@@ -699,7 +698,7 @@ class Criteria(Element):
assert(self.children)
exported = Criteria(self.name)
- for child in self.children :
+ for child in self.children:
exported.addChild(child.export())
return exported
@@ -726,40 +725,41 @@ class ParsePFWlog():
def __str__(self):
return ("Change request on an unknown criterion %s." %
- self.criterion)
+ self.criterion)
def __init__(self, domains, criteria, ErrorsToIgnore=()):
- self.domains = domains;
- self.criteria = criteria;
+ self.domains = domains
+ self.criteria = criteria
self.ErrorsToIgnore = ErrorsToIgnore
configApplicationRegext = r""".*Applying configuration "(.*)" from domain "([^"]*)"""
matchConfigApplicationLine = re.compile(configApplicationRegext).match
criterionCreationRegext = ", ".join([
- r""".*Criterion name: (.*)""",
- r"""type kind: (.*)""",
- r"""current state: (.*)""",
- r"""states: {(.*)}"""
- ])
+ r""".*Criterion name: (.*)""",
+ r"""type kind: (.*)""",
+ r"""current state: (.*)""",
+ r"""states: {(.*)}"""
+ ])
matchCriterionCreationLine = re.compile(criterionCreationRegext).match
- changingCriterionRegext = r""".*Selection criterion changed event: Criterion name: (.*), current state: ([^\n\r]*)"""
+ changingCriterionRegext = r""".*Selection criterion changed event: Criterion name: (.*), \
+ current state: ([^\n\r]*)"""
matchChangingCriterionLine = re.compile(changingCriterionRegext).match
self.lineLogTypes = [
- {
- self.MATCH: matchConfigApplicationLine,
- self.ACTION: self._configApplication
- }, {
- self.MATCH: matchCriterionCreationLine,
- self.ACTION: self._criterionCreation
- }, {
- self.MATCH: matchChangingCriterionLine,
- self.ACTION: self._changingCriterion
- }
- ]
+ {
+ self.MATCH: matchConfigApplicationLine,
+ self.ACTION: self._configApplication
+ }, {
+ self.MATCH: matchCriterionCreationLine,
+ self.ACTION: self._criterionCreation
+ }, {
+ self.MATCH: matchChangingCriterionLine,
+ self.ACTION: self._changingCriterion
+ }
+ ]
@staticmethod
def _formatCriterionList(liststring, separator):
@@ -785,11 +785,11 @@ class ParsePFWlog():
try:
self.criteria.addChild(Criterion(
- criterionName,
- criterionIsInclusif,
- criterionStateList,
- currentcriterionStateList
- ))
+ criterionName,
+ criterionIsInclusif,
+ criterionStateList,
+ currentcriterionStateList
+ ))
except self.criteria.DuplicatedCriterionError as ex:
logger.debug(ex)
logger.warning("Reseting criterion %s. Did you reset the PFW ?" % criterionName)
@@ -806,10 +806,10 @@ class ParsePFWlog():
newCriterionState = self._formatCriterionList(newCriterionSubStateNames, "|")
- logger.info("Changing criterion %s to %s" % (criterionName , newCriterionState))
+ logger.info("Changing criterion %s to %s" % (criterionName, newCriterionState))
path = [criterionName]
- changeCriterionOperation = lambda criterion : criterion.changeState(newCriterionState)
+ changeCriterionOperation = lambda criterion: criterion.changeState(newCriterionState)
try:
self.criteria.operationOnChild(path, changeCriterionOperation)
except ChildNotFoundError:
@@ -820,17 +820,17 @@ class ParsePFWlog():
configurationName, domainName = matchConfig.group(1, 2)
# Check that at least one criterion exist
- if not self.criteria.hasChildren() :
+ if not self.criteria.hasChildren():
logger.error("Applying configuration before declaring criteria")
logger.info("Is the log starting at PFW boot ?")
raise ConfigAppliedWithoutCriteriaError(configurationName, domainName)
# Change criterion state
path = [domainName, configurationName]
- usedOperation = lambda element : element.used(self.criteria)
+ usedOperation = lambda element: element.used(self.criteria)
logger.info("Applying configuration %s from domain %s" % (
- configurationName, domainName))
+ configurationName, domainName))
self.domains.operationOnChild(path, usedOperation)
@@ -838,7 +838,7 @@ class ParsePFWlog():
def _digest(self, lineLogType, lineLog):
match = lineLogType[self.MATCH](lineLog)
- if match :
+ if match:
lineLogType[self.ACTION](match)
return True
return False
@@ -850,7 +850,7 @@ class ParsePFWlog():
logger.debug("Parsing line :%s" % lineLog.rstrip())
digested = (self._digest(lineLogType, lineLog)
- for lineLogType in self.lineLogTypes)
+ for lineLogType in self.lineLogTypes)
try:
success = any(digested)
@@ -859,7 +859,7 @@ class ParsePFWlog():
# then raise the exception again if not continue of error
except CustomError as ex:
logger.error('Error raised while parsing line %s: "%s"' %
- (lineNb, repr(lineLog)))
+ (lineNb, repr(lineLog)))
# If exception is a subclass of ErrorsToIgnore, log it and continue
# otherwise raise it again.
@@ -867,7 +867,7 @@ class ParsePFWlog():
raise ex
else:
logger.error('Ignoring exception:"%s", '
- 'can not guarantee database integrity' % ex)
+ 'can not guarantee database integrity' % ex)
else:
if not success:
logger.debug("Line does not match, dropped")
@@ -936,69 +936,69 @@ class ArgumentParser:
logger.warning(" - Debug level: error")
self.debugLevel = logging.ERROR
- else :
+ else:
myArgParser = argparse.ArgumentParser(description='Generate PFW report')
myArgParser.add_argument(
- 'domainsFile',
- type=argparse.FileType('r'),
- help="the PFW domain XML file"
- )
+ 'domainsFile',
+ type=argparse.FileType('r'),
+ help="the PFW domain XML file"
+ )
myArgParser.add_argument(
- 'pfwlog', nargs='?',
- type=argparse.FileType('r'), default=sys.stdin,
- help="the PFW log file, default stdin"
- )
+ 'pfwlog', nargs='?',
+ type=argparse.FileType('r'), default=sys.stdin,
+ help="the PFW log file, default stdin"
+ )
myArgParser.add_argument(
- '-o', '--output',
- dest="outputFile",
- type=argparse.FileType('w'), default=sys.stdout,
- help="the coverage report output file, default stdout"
- )
+ '-o', '--output',
+ dest="outputFile",
+ type=argparse.FileType('w'), default=sys.stdout,
+ help="the coverage report output file, default stdout"
+ )
myArgParser.add_argument(
- '-v', '--verbose',
- dest="debugLevel", default=0,
- action='count',
- help="print debug warnings from warning (default) to debug (-vv)"
- )
+ '-v', '--verbose',
+ dest="debugLevel", default=0,
+ action='count',
+ help="print debug warnings from warning (default) to debug (-vv)"
+ )
outputFormatGroupe = myArgParser.add_mutually_exclusive_group(required=False)
outputFormatGroupe.add_argument(
- '--xml',
- dest="xmlFlag",
- action='store_true',
- help=" XML coverage output report"
- )
+ '--xml',
+ dest="xmlFlag",
+ action='store_true',
+ help=" XML coverage output report"
+ )
outputFormatGroupe.add_argument(
- '--raw',
- dest="rawFlag",
- action='store_true',
- help="raw coverage output report"
- )
+ '--raw',
+ dest="rawFlag",
+ action='store_true',
+ help="raw coverage output report"
+ )
myArgParser.add_argument(
- '--ignore-unknown-criterion',
- dest="unknwonCriterionFlag",
- action='store_true',
- help="ignore unknown criterion"
- )
+ '--ignore-unknown-criterion',
+ dest="unknwonCriterionFlag",
+ action='store_true',
+ help="ignore unknown criterion"
+ )
myArgParser.add_argument(
- '--ignore-incoherent-criterion-state',
- dest="incoherentCriterionFlag",
- action='store_true',
- help="ignore criterion transition to incoherent state"
- )
+ '--ignore-incoherent-criterion-state',
+ dest="incoherentCriterionFlag",
+ action='store_true',
+ help="ignore criterion transition to incoherent state"
+ )
myArgParser.add_argument(
- '--ignore-ineligible-configuration-application',
- dest="ineligibleConfigurationApplicationFlag",
- action='store_true',
- help="ignore application of configuration with a false rule "
- "(not applicable configuration)"
- )
+ '--ignore-ineligible-configuration-application',
+ dest="ineligibleConfigurationApplicationFlag",
+ action='store_true',
+ help="ignore application of configuration with a false rule "
+ "(not applicable configuration)"
+ )
# Process command line arguments
options = myArgParser.parse_args()
@@ -1017,7 +1017,7 @@ class ArgumentParser:
# Setting ignore options
errorToIgnore = []
- if options.ineligibleConfigurationApplicationFlag :
+ if options.ineligibleConfigurationApplicationFlag:
errorToIgnore.append(Configuration.IneligibleConfigurationAppliedError)
if options.incoherentCriterionFlag:
@@ -1045,7 +1045,7 @@ def main():
# Setting logger level
logger.setLevel(commandLineArguments.debugLevel)
logger.info("Log level set to: %s" %
- logging.getLevelName(commandLineArguments.debugLevel))
+ logging.getLevelName(commandLineArguments.debugLevel))
# Create tree from XML
dom = xml.dom.minidom.parse(commandLineArguments.domainsFile)
@@ -1060,19 +1060,19 @@ def main():
parser.parsePFWlog(commandLineArguments.inputFile.readlines())
except CustomError as ex:
logger.fatal("Error during parsing log file %s: %s" %
- (commandLineArguments.inputFile, ex))
+ (commandLineArguments.inputFile, ex))
sys.exit(errorDuringLogParsing)
# Output report
outputFile = commandLineArguments.outputFile
- if not commandLineArguments.XMLreport :
+ if not commandLineArguments.XMLreport:
outputFile.write("%s\n" % root.dump(withCoverage=True, withNbUse=True))
- else :
+ else:
outputFile.write(root.exportToXML().toprettyxml())
-if __name__ == "__main__" :
+if __name__ == "__main__":
""" Execute main if the python interpreter is running this module as the main program """
main()
diff --git a/upstream/tools/xmlGenerator/EddParser.py b/upstream/tools/xmlGenerator/EddParser.py
index 7f8a5b9..285c6d0 100755
--- a/upstream/tools/xmlGenerator/EddParser.py
+++ b/upstream/tools/xmlGenerator/EddParser.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python2
+#!/usr/bin/python3
# -*-coding:utf-8 -*
# Copyright (c) 2011-2014, Intel Corporation
@@ -33,7 +33,7 @@
import re
import sys
-import copy
+
# For Python 2.x/3.x compatibility
try:
from itertools import izip as zip
@@ -45,68 +45,68 @@ except:
""" Context classes, used during propagation and the "to PFW script" step """
# =====================================================================
-class PropagationContextItem(list) :
+class PropagationContextItem(list):
"""Handle an item during the propagation step"""
def __copy__(self):
"""C.__copy__() -> a shallow copy of C"""
return self.__class__(self)
-class PropagationContextElement(PropagationContextItem) :
+class PropagationContextElement(PropagationContextItem):
"""Handle an Element during the propagation step"""
def getElementsFromName(self, name):
matchingElements = []
- for element in self :
- if element.getName() == name :
+ for element in self:
+ if element.getName() == name:
matchingElements.append(element)
return matchingElements
-class PropagationContextOption(PropagationContextItem) :
+class PropagationContextOption(PropagationContextItem):
"""Handle an Option during the propagation step"""
- def getOptionItems (self, itemName):
+ def getOptionItems(self, itemName):
items = []
- for options in self :
+ for options in self:
items.append(options.getOption(itemName))
return items
-class PropagationContext() :
+class PropagationContext():
"""Handle the context during the propagation step"""
- def __init__(self, propagationContext=None) :
+ def __init__(self, propagationContext=None):
- if propagationContext == None :
+ if propagationContext == None:
self._context = {
- "DomainOptions" : PropagationContextOption() ,
- "Configurations" : PropagationContextElement() ,
- "ConfigurationOptions" : PropagationContextOption() ,
- "Rules" : PropagationContextElement() ,
- "PathOptions" : PropagationContextOption() ,
- }
- else :
+ "DomainOptions" : PropagationContextOption(),
+ "Configurations" : PropagationContextElement(),
+ "ConfigurationOptions" : PropagationContextOption(),
+ "Rules" : PropagationContextElement(),
+ "PathOptions" : PropagationContextOption(),
+ }
+ else:
self._context = propagationContext
def copy(self):
"""return a copy of the context"""
contextCopy = self._context.copy()
- for key in iter(self._context) :
+ for key in iter(self._context):
contextCopy[key] = contextCopy[key].__copy__()
return self.__class__(contextCopy)
- def getDomainOptions (self):
+ def getDomainOptions(self):
return self._context["DomainOptions"]
- def getConfigurations (self):
+ def getConfigurations(self):
return self._context["Configurations"]
- def getConfigurationOptions (self):
+ def getConfigurationOptions(self):
return self._context["ConfigurationOptions"]
- def getRules (self):
+ def getRules(self):
return self._context["Rules"]
- def getPathOptions (self):
+ def getPathOptions(self):
return self._context["PathOptions"]
@@ -114,16 +114,16 @@ class PropagationContext() :
"""Element option container"""
# =====================================================
-class Options () :
+class Options():
"""handle element options"""
- def __init__(self, options=[], optionNames=[]) :
+ def __init__(self, options=[], optionNames=[]):
self.options = dict(zip(optionNames, options))
# print(options,optionNames,self.options)
- def __str__(self) :
+ def __str__(self):
ops2str = []
- for name, argument in list(self.options.items()) :
+ for name, argument in list(self.options.items()):
ops2str.append(str(name) + "=\"" + str(argument) + "\"")
return " ".join(ops2str)
@@ -136,7 +136,7 @@ class Options () :
"""set option by its name"""
self.options[name] = newOption
- def copy (self):
+ def copy(self):
"""D.copy() -> a shallow copy of D"""
copy = Options()
copy.options = self.options.copy()
@@ -155,16 +155,16 @@ class Element(object):
childWhiteList = []
optionDelimiter = " "
- def __init__(self, line=None) :
+ def __init__(self, line=None):
- if line == None :
+ if line == None:
self.option = Options([], self.optionNames)
- else :
+ else:
self.option = self.optionFromLine(line)
self.children = []
- def optionFromLine(self, line) :
+ def optionFromLine(self, line):
# get ride of spaces
line = line.strip()
@@ -172,7 +172,7 @@ class Element(object):
return Options(options, self.optionNames)
- def extractOptions(self, line) :
+ def extractOptions(self, line):
"""return the line splited by the optionDelimiter atribute
Option list length is less or equal to the optionNames list length
@@ -184,23 +184,23 @@ class Element(object):
return optionsStrip
- def addChild(self, child, append=True) :
+ def addChild(self, child, append=True):
""" A.addChid(B) -> add B to A child list if B class name is in A white List"""
try:
# Will raise an exception if this child is not in the white list
self.childWhiteList.index(child.__class__.__name__)
# If no exception was raised, add child to child list
- if append :
+ if append:
self.children.append(child)
- else :
+ else:
self.children.insert(0, child)
except ValueError:
# the child class is not in the white list
raise ChildNotPermitedError("", self, child)
- def addChildren(self, children, append=True) :
+ def addChildren(self, children, append=True):
"""Add a list of child"""
if append:
# Add children at the end of the child list
@@ -212,32 +212,32 @@ class Element(object):
def childrenToString(self, prefix=""):
"""return raw printed children """
body = ""
- for child in self.children :
+ for child in self.children:
body = body + child.__str__(prefix)
return body
- def __str__(self, prefix="") :
+ def __str__(self, prefix=""):
"""return raw printed element"""
selfToString = prefix + " " + self.tag + " " + str(self.option)
return selfToString + "\n" + self.childrenToString(prefix + "\t")
- def extractChildrenByClass(self, classTypeList) :
+ def extractChildrenByClass(self, classTypeList):
"""return all children whose class is in the list argument
return a list of all children whose class in the list "classTypeList" (second arguments)"""
selectedChildren = []
- for child in self.children :
- for classtype in classTypeList :
- if child.__class__ == classtype :
+ for child in self.children:
+ for classtype in classTypeList:
+ if child.__class__ == classtype:
selectedChildren.append(child)
break
return selectedChildren
- def propagate (self, context=PropagationContext()):
+ def propagate(self, context=PropagationContext()):
"""call the propagate method of all children"""
- for child in self.children :
+ for child in self.children:
child.propagate(context)
def getName(self):
@@ -253,9 +253,9 @@ class Element(object):
# ----------------------------------------------------------
-class ElementWithTag (Element):
+class ElementWithTag(Element):
"""Element of this class are declared with a tag => line == "tag: .*" """
- def extractOptions(self, line) :
+ def extractOptions(self, line):
lineWithoutTag = line.split(":", 1)[-1].strip()
options = super(ElementWithTag, self).extractOptions(lineWithoutTag)
return options
@@ -263,7 +263,7 @@ class ElementWithTag (Element):
# ----------------------------------------------------------
class ElementWithInheritance(Element):
- def propagate (self, context=PropagationContext) :
+ def propagate(self, context=PropagationContext):
"""propagate some proprieties to children"""
# copy the context so that everything that hapend next will only affect
@@ -297,15 +297,15 @@ class ElementWithRuleInheritance(ElementWithInheritance):
# ----------------------------------------------------------
-class EmptyLine (Element) :
+class EmptyLine(Element):
"""This class represents an empty line.
Will raise "EmptyLineWarning" exception at instanciation."""
tag = "emptyLine"
match = re.compile(r"[ \t]*\n?$").match
- def __init__ (self, line):
- raise EmptyLineWarning(line)
+ def __init__(self, line):
+ raise EmptyLineWarning(line)
# ----------------------------------------------------------
@@ -317,12 +317,12 @@ class Commentary(Element):
tag = "commentary"
optionNames = ["comment"]
match = re.compile(r"#").match
- def __init__ (self, line):
- raise CommentWarning(line)
+ def __init__(self, line):
+ raise CommentWarning(line)
# ----------------------------------------------------------
-class Path (ElementWithInheritance) :
+class Path(ElementWithInheritance):
"""class implementing the "path = value" concept"""
tag = "path"
optionNames = ["Name", "value"]
@@ -332,34 +332,34 @@ class Path (ElementWithInheritance) :
def translate(self, translator):
translator.setParameter(self.getName(), self.option.getOption("value"))
- def Inheritance (self, context) :
+ def Inheritance(self, context):
"""check for path name inheritance"""
self.OptionsInheritance(context)
- def OptionsInheritance (self, context) :
+ def OptionsInheritance(self, context):
"""make configuration name inheritance """
context.getPathOptions().append(self.option.copy())
self.setName("/".join(context.getPathOptions().getOptionItems("Name")))
-class GroupPath (Path, ElementWithTag) :
+class GroupPath(Path, ElementWithTag):
tag = "component"
match = re.compile(tag + r" *:").match
optionNames = ["Name"]
childWhiteList = ["Path", "GroupPath"]
- def getPathNames (self) :
+ def getPathNames(self):
"""Return the list of all path child name"""
pathNames = []
paths = self.extractChildrenByClass([Path])
- for path in paths :
+ for path in paths:
pathNames.append(path.getName())
groupPaths = self.extractChildrenByClass([GroupPath])
- for groupPath in groupPaths :
+ for groupPath in groupPaths:
pathNames += groupPath.getPathNames()
return pathNames
@@ -370,7 +370,7 @@ class GroupPath (Path, ElementWithTag) :
# ----------------------------------------------------------
-class Rule (Element) :
+class Rule(Element):
"""class implementing the rule concept
A rule is composed of a criterion, a rule type and an criterion state.
@@ -382,7 +382,7 @@ class Rule (Element) :
match = re.compile(r"[a-zA-Z0-9_.]+ +(Is|IsNot|Includes|Excludes) +[a-zA-Z0-9_.]+").match
childWhiteList = []
- def PFWSyntax (self, prefix=""):
+ def PFWSyntax(self, prefix=""):
script = prefix + \
self.option.getOption("criterion") + " " + \
@@ -392,7 +392,7 @@ class Rule (Element) :
return script
-class Operator (Rule) :
+class Operator(Rule):
"""class implementing the operator concept
An operator contains rules and other operators
@@ -405,10 +405,11 @@ class Operator (Rule) :
match = re.compile(r"ANY|ALL").match
childWhiteList = ["Rule", "Operator"]
- syntax = { "ANY" : "Any" , "ALL" : "All"}
+ syntax = {"ANY" : "Any", "ALL" : "All"}
- def PFWSyntax (self, prefix=""):
- """ return a pfw rule (ex : "Any{criterion1 is state1}") generated from "self" and its children options"""
+ def PFWSyntax(self, prefix=""):
+ """ return a pfw rule (ex : "Any{criterion1 is state1}") generated from "self" \
+ and its children options"""
script = ""
script += prefix + \
@@ -417,7 +418,7 @@ class Operator (Rule) :
rules = self.extractChildrenByClass([Rule, Operator])
PFWRules = []
- for rule in rules :
+ for rule in rules:
PFWRules.append(rule.PFWSyntax(prefix + " "))
script += (" , ").join(PFWRules)
@@ -428,13 +429,13 @@ class Operator (Rule) :
# ----------------------------------------------------------
-class Configuration (ElementWithRuleInheritance, ElementWithTag) :
+class Configuration(ElementWithRuleInheritance, ElementWithTag):
tag = "configuration"
optionNames = ["Name"]
match = re.compile(r"conf *:").match
childWhiteList = ["Rule", "Operator", "Path", "GroupPath"]
- def composition (self, context):
+ def composition(self, context):
"""make all needed composition
Composition is the fact that group configuration with the same name defined
@@ -446,12 +447,12 @@ class Configuration (ElementWithRuleInheritance, ElementWithTag) :
sameNameConf.reverse()
- for configuration in sameNameConf :
+ for configuration in sameNameConf:
# add same name configuration rule children to self child list
self.addChildren(configuration.extractChildrenByClass([Operator, Rule]), append=False)
- def propagate (self, context=PropagationContext) :
+ def propagate(self, context=PropagationContext):
"""propagate proprieties to children
make needed compositions, join ancestor name to its name,
@@ -462,7 +463,7 @@ class Configuration (ElementWithRuleInheritance, ElementWithTag) :
super(Configuration, self).propagate(context)
- def Inheritance (self, context) :
+ def Inheritance(self, context):
"""make configuration name and rule inheritance"""
# check for configuration name inheritance
self.OptionsInheritance(context)
@@ -470,14 +471,14 @@ class Configuration (ElementWithRuleInheritance, ElementWithTag) :
# check for rule inheritance
self.ruleInheritance(context)
- def OptionsInheritance (self, context) :
+ def OptionsInheritance(self, context):
"""make configuration name inheritance """
context.getConfigurationOptions().append(self.option.copy())
self.setName(".".join(context.getConfigurationOptions().getOptionItems("Name")))
- def getRootPath (self) :
+ def getRootPath(self):
paths = self.extractChildrenByClass([Path, GroupPath])
@@ -486,7 +487,7 @@ class Configuration (ElementWithRuleInheritance, ElementWithTag) :
return rootPath
- def getConfigurableElements (self) :
+ def getConfigurableElements(self):
"""return all path name defined in this configuration"""
return self.getRootPath().getPathNames()
@@ -498,10 +499,10 @@ class Configuration (ElementWithRuleInheritance, ElementWithTag) :
ruleChildren = self.extractChildrenByClass([Rule, Operator])
# Do not create a root rule if there is only one fist level Operator rule
- if len(ruleChildren) == 1 and ruleChildren[0].__class__ == Operator :
+ if len(ruleChildren) == 1 and ruleChildren[0].__class__ == Operator:
ruleroot = ruleChildren[0]
- else :
+ else:
ruleroot = Operator()
ruleroot.setName("ALL")
ruleroot.addChildren(ruleChildren)
@@ -517,7 +518,7 @@ class Configuration (ElementWithRuleInheritance, ElementWithTag) :
for path in paths:
path.translate(translator)
- def copy (self) :
+ def copy(self):
"""return a shallow copy of the configuration"""
# create configuration or subclass copy
@@ -531,13 +532,13 @@ class Configuration (ElementWithRuleInheritance, ElementWithTag) :
return confCopy
-class GroupConfiguration (Configuration) :
+class GroupConfiguration(Configuration):
tag = "GroupConfiguration"
optionNames = ["Name"]
match = re.compile(r"(supConf|confGroup|confType) *:").match
childWhiteList = ["Rule", "Operator", "GroupConfiguration", "Configuration", "GroupPath"]
- def composition (self, context) :
+ def composition(self, context):
"""add itself in context for configuration composition
Composition is the fact that group configuration with the same name defined
@@ -554,7 +555,7 @@ class GroupConfiguration (Configuration) :
context.getConfigurations().append(selfCopy)
- def getConfigurableElements (self) :
+ def getConfigurableElements(self):
"""return a list. Each elements consist of a list of configurable element of a configuration
return a list consisting of all configurable elements for each configuration.
@@ -562,11 +563,11 @@ class GroupConfiguration (Configuration) :
configurableElements = []
configurations = self.extractChildrenByClass([Configuration])
- for configuration in configurations :
+ for configuration in configurations:
configurableElements.append(configuration.getConfigurableElements())
groudeConfigurations = self.extractChildrenByClass([GroupConfiguration])
- for groudeConfiguration in groudeConfigurations :
+ for groudeConfiguration in groudeConfigurations:
configurableElements += groudeConfiguration.getConfigurableElements()
return configurableElements
@@ -577,7 +578,7 @@ class GroupConfiguration (Configuration) :
# ----------------------------------------------------------
-class Domain (ElementWithRuleInheritance, ElementWithTag) :
+class Domain(ElementWithRuleInheritance, ElementWithTag):
tag = "domain"
sequenceAwareKeyword = "sequenceAware"
@@ -585,7 +586,7 @@ class Domain (ElementWithRuleInheritance, ElementWithTag) :
optionNames = ["Name", sequenceAwareKeyword]
childWhiteList = ["Configuration", "GroupConfiguration", "Rule", "Operator"]
- def propagate (self, context=PropagationContext) :
+ def propagate(self, context=PropagationContext):
""" propagate name, sequenceAwareness and rule to children"""
# call the propagate method of all children
@@ -593,7 +594,7 @@ class Domain (ElementWithRuleInheritance, ElementWithTag) :
self.checkConfigurableElementUnicity()
- def Inheritance (self, context) :
+ def Inheritance(self, context):
"""check for domain name, sequence awarness and rules inheritance"""
# check for domain name and sequence awarness inheritance
self.OptionsInheritance(context)
@@ -601,7 +602,7 @@ class Domain (ElementWithRuleInheritance, ElementWithTag) :
# check for rule inheritance
self.ruleInheritance(context)
- def OptionsInheritance(self, context) :
+ def OptionsInheritance(self, context):
""" make domain name and sequence awareness inheritance
join to the domain name all domain names defined in context and
@@ -617,13 +618,13 @@ class Domain (ElementWithRuleInheritance, ElementWithTag) :
sequenceAwareList = context.getDomainOptions().getOptionItems(self.sequenceAwareKeyword)
# or operation on all booleans in sequenceAwareList
sequenceAwareness = False
- for sequenceAware in sequenceAwareList :
+ for sequenceAware in sequenceAwareList:
sequenceAwareness = sequenceAwareness or sequenceAware
# current domain sequenceAwareness = sequenceAwareness
self.option.setOption(self.sequenceAwareKeyword, sequenceAwareness)
- def extractOptions(self, line) :
+ def extractOptions(self, line):
"""Extract options from the definition line"""
options = super(Domain, self).extractOptions(line)
@@ -631,16 +632,16 @@ class Domain (ElementWithRuleInheritance, ElementWithTag) :
# translate the keyword self.sequenceAwareKeyword if specified to boolean True,
# to False otherwise
- try :
- if options[sequenceAwareIndex] == self.sequenceAwareKeyword :
- options[sequenceAwareIndex] = True
+ try:
+ if options[sequenceAwareIndex] == self.sequenceAwareKeyword:
+ options[sequenceAwareIndex] = True
else:
- options[sequenceAwareIndex] = False
- except IndexError :
+ options[sequenceAwareIndex] = False
+ except IndexError:
options = options + [None] * (sequenceAwareIndex - len(options)) + [False]
return options
- def getRootConfiguration (self) :
+ def getRootConfiguration(self):
"""return the root configuration group"""
configurations = self.extractChildrenByClass([Configuration, GroupConfiguration])
@@ -651,27 +652,28 @@ class Domain (ElementWithRuleInheritance, ElementWithTag) :
return configurationRoot
# TODO: don't do that in the parser, let the PFW tell you that
- def checkConfigurableElementUnicity (self):
+ def checkConfigurableElementUnicity(self):
""" check that all configurable elements defined in child configuration are the sames"""
# get a list. Each elements of is the configurable element list of a configuration
configurableElementsList = self.getRootConfiguration().getConfigurableElements()
# if at least two configurations in the domain
- if len(configurableElementsList) > 1 :
+ if len(configurableElementsList) > 1:
# get first configuration configurable element list sort
configurableElementsList0 = list(configurableElementsList[0])
configurableElementsList0.sort()
- for configurableElements in configurableElementsList :
+ for configurableElements in configurableElementsList:
# sort current configurable element list
auxConfigurableElements = list(configurableElements)
auxConfigurableElements.sort()
- if auxConfigurableElements != configurableElementsList0 :
- # if different, 2 configurations those not have the same configurable element list
- # => one or more configurable element is missing in one of the 2 configuration
+ if auxConfigurableElements != configurableElementsList0:
+ # if different, 2 configurations those not have the same configurable element
+ # list => one or more configurable element is missing in one of the 2
+ # configuration
raise UndefinedParameter(self.getName())
@@ -683,13 +685,13 @@ class Domain (ElementWithRuleInheritance, ElementWithTag) :
configurableElementsList = configurations.getConfigurableElements()
# add configurable elements
- if len(configurableElementsList) != 0 :
- for configurableElement in configurableElementsList[0] :
+ if len(configurableElementsList) != 0:
+ for configurableElement in configurableElementsList[0]:
translator.addElement(configurableElement)
configurations.translate(translator)
-class GroupDomain (Domain) :
+class GroupDomain(Domain):
tag = "groupDomain"
match = re.compile(r"(supDomain|domainGroup) *:").match
childWhiteList = ["GroupDomain", "Domain", "GroupConfiguration", "Rule", "Operator"]
@@ -709,7 +711,7 @@ class Root(Element):
""" Syntax error Exceptions"""
# ===========================================
-class MySyntaxProblems(SyntaxError) :
+class MySyntaxProblems(SyntaxError):
comment = "syntax error in %(line)s "
def __init__(self, line=None, num=None):
@@ -717,43 +719,43 @@ class MySyntaxProblems(SyntaxError) :
def __str__(self):
- if self.line :
+ if self.line:
self.comment = self.comment % {"line" : repr(self.line)}
- if self.num :
+ if self.num:
self.comment = "Line " + str(self.num) + ", " + self.comment
return self.comment
- def setLine (self, line, num):
+ def setLine(self, line, num):
self.line = str(line)
self.num = num
# ---------------------------------------------------------
-class MyPropagationError(MySyntaxProblems) :
+class MyPropagationError(MySyntaxProblems):
""" Syntax error Exceptions used in the propagation step"""
pass
-class UndefinedParameter(MyPropagationError) :
+class UndefinedParameter(MyPropagationError):
comment = "Configurations in domain '%(domainName)s' do not all set the same parameters "
- def __init__ (self, domainName):
+ def __init__(self, domainName):
self.domainName = domainName
- def __str__ (self):
- return self.comment % { "domainName" : self.domainName }
+ def __str__(self):
+ return self.comment % {"domainName" : self.domainName}
# -----------------------------------------------------
""" Syntax error Exceptions used by parser"""
-class MySyntaxError(MySyntaxProblems) :
+class MySyntaxError(MySyntaxProblems):
""" Syntax error Exceptions used by parser"""
pass
-class MySyntaxWarning(MySyntaxProblems) :
+class MySyntaxWarning(MySyntaxProblems):
""" Syntax warning Exceptions used by parser"""
pass
-class IndentationSyntaxError(MySyntaxError) :
+class IndentationSyntaxError(MySyntaxError):
comment = """syntax error in %(line)s has no father element.
You can only increment indentation by one tabutation per line")"""
@@ -765,7 +767,8 @@ class CommentWarning(MySyntaxWarning):
class ChildNotPermitedError(MySyntaxError):
def __init__(self, line, fatherElement, childElement):
- self.comment = "syntax error in %(line)s, " + fatherElement.tag + " should not have a " + childElement.tag + " child."
+ self.comment = "syntax error in %(line)s, " + fatherElement.tag + " should not have a " \
+ + childElement.tag + " child."
super(ChildNotPermitedError, self).__init__(line)
@@ -780,35 +783,35 @@ class SpaceInIndentationError(MySyntaxError):
"""Class creating the DOM elements from a stream"""
# ============================================
-class ElementsFactory(object) :
+class ElementsFactory(object):
"""Element factory, return an instance of the first matching element
Test each element list in elementClass and instanciate it if it's methode match returns True
The method match is called with input line as argument
"""
- def __init__ (self):
+ def __init__(self):
self.elementClass = [
- EmptyLine ,
- Commentary,
- GroupDomain,
- Domain,
- Path,
- GroupConfiguration,
- Configuration,
- Operator,
- Rule,
- GroupPath
+ EmptyLine,
+ Commentary,
+ GroupDomain,
+ Domain,
+ Path,
+ GroupConfiguration,
+ Configuration,
+ Operator,
+ Rule,
+ GroupPath
]
- def createElementFromLine (self, line) :
+ def createElementFromLine(self, line):
"""return an instance of the first matching element
Test each element list in elementClass and instanciate it if it's methode match returns True
The method match is called with the argument line.
Raise UnknownElementTypeError if no element matched.
"""
- for element in self.elementClass :
- if element.match(line) :
+ for element in self.elementClass:
+ if element.match(line):
# print (line + element.__class__.__name__)
return element(line)
# if we have not find any
@@ -816,7 +819,7 @@ class ElementsFactory(object) :
#------------------------------------------------------
-class Parser(object) :
+class Parser(object):
"""Class implementing the parser"""
def __init__(self):
self.rankPattern = re.compile(r"^([\t ]*)(.*)")
@@ -841,20 +844,20 @@ the rank is the number of tabulation (\t) at the line beginning.
the rest is the rest of the line."""
# split line in rank and rest
rank = self.rankPattern.match(line)
- if rank :
+ if rank:
rank, rest = rank.group(1, 2)
- else :
+ else:
raise MySyntaxError(line)
# check for empty line
- if rest == "" :
+ if rest == "":
raise EmptyLineWarning(line)
# check for space in indentation
- if rank.find(" ") > -1 :
+ if rank.find(" ") > -1:
raise SpaceInIndentationError(line)
- rank = len (rank) + 1 # rank starts at 1
+ rank = len(rank) + 1 # rank starts at 1
return rank, rest
@@ -862,7 +865,7 @@ the rest is the rest of the line."""
def __checkIndentation__(self, rank):
"""check if indentation > previous indentation + 1. If so, raise IndentationSyntaxError"""
- if (rank > self.previousRank + 1) :
+ if rank > self.previousRank + 1:
raise IndentationSyntaxError()
self.previousRank = rank
@@ -870,23 +873,22 @@ the rest is the rest of the line."""
"""parse a stream, usually a opened file"""
myroot = Root("root")
context = [myroot] # root is element of rank 0
- warnings = ""
for num, line in enumerate(stream):
try:
rank, myelement = self.__parseLine__(line)
- while len(context) > rank :
+ while len(context) > rank:
context.pop()
context.append(myelement)
context[-2].addChild(myelement)
except MySyntaxWarning as ex:
ex.setLine(line, num + 1)
- if verbose :
+ if verbose:
sys.stderr.write("{}\n".format(ex))
- except MySyntaxError as ex :
+ except MySyntaxError as ex:
ex.setLine(line, num + 1)
raise
diff --git a/upstream/tools/xmlGenerator/PFWScriptGenerator.py b/upstream/tools/xmlGenerator/PFWScriptGenerator.py
index 145295d..d047972 100755
--- a/upstream/tools/xmlGenerator/PFWScriptGenerator.py
+++ b/upstream/tools/xmlGenerator/PFWScriptGenerator.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python2
+#!/usr/bin/python3
# Copyright (c) 2015, Intel Corporation
# All rights reserved.
@@ -28,12 +28,13 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-import EddParser
-from PfwBaseTranslator import PfwBaseTranslator
import argparse
import sys
+import EddParser
+from PfwBaseTranslator import PfwBaseTranslator
+
class PfwScriptTranslator(PfwBaseTranslator):
def __init__(self):
@@ -66,9 +67,10 @@ class PfwScriptTranslator(PfwBaseTranslator):
self._appendCommand("setRule", self._ctx_domain, self._ctx_configuration, rule)
def _doSetParameter(self, path, value):
- self._appendCommand("setConfigurationParameter", self._ctx_domain, self._ctx_configuration, path, value)
+ self._appendCommand("setConfigurationParameter", self._ctx_domain, self._ctx_configuration,
+ path, value)
-class ArgparseArgumentParser(object) :
+class ArgparseArgumentParser(object):
"""class that parse command line arguments with argparse library
result of parsing are the class atributs"""
@@ -77,21 +79,22 @@ class ArgparseArgumentParser(object) :
myArgParser = argparse.ArgumentParser(description='Process domain scripts.')
myArgParser.add_argument('input', nargs='?',
- type=argparse.FileType('r'), default=sys.stdin,
- help="the domain script file, default stdin")
+ type=argparse.FileType('r'), default=sys.stdin,
+ help="the domain script file, default stdin")
myArgParser.add_argument('-o', '--output',
- type=argparse.FileType('w'), default=sys.stdout,
- help="the output file, default stdout")
+ type=argparse.FileType('w'), default=sys.stdout,
+ help="the output file, default stdout")
myArgParser.add_argument('-d', '--debug',
- action='store_true',
- help="print debug warnings")
+ action='store_true',
+ help="print debug warnings")
myArgParser.add_argument('--output-kind',
- choices=['pfw', 'raw'],
- default='pfw',
- help="output kind; can be either 'raw' (debug only) or 'pfw' (pfw commands; default choice)")
+ choices=['pfw', 'raw'],
+ default='pfw',
+ help="output kind; can be either 'raw' (debug only) or 'pfw' \
+ (pfw commands; default choice)")
# process command line arguments
@@ -114,7 +117,7 @@ def printE(s):
"""print in stderr"""
sys.stderr.write(str(s))
-def main ():
+def main():
options = ArgparseArgumentParser()
@@ -133,7 +136,7 @@ def main ():
try:
myroot.propagate()
- except EddParser.MyPropagationError as ex :
+ except EddParser.MyPropagationError as ex:
printE(ex)
printE("EXIT ON FAILURE")
exit(1)
@@ -144,6 +147,6 @@ def main ():
options.output.write("\n".join(translator.getScript()))
# execute main function if the python interpreter is running this module as the main program
-if __name__ == "__main__" :
+if __name__ == "__main__":
main()
diff --git a/upstream/tools/xmlGenerator/PfwBaseTranslator.py b/upstream/tools/xmlGenerator/PfwBaseTranslator.py
index 0d08565..b99eb88 100644
--- a/upstream/tools/xmlGenerator/PfwBaseTranslator.py
+++ b/upstream/tools/xmlGenerator/PfwBaseTranslator.py
@@ -53,10 +53,10 @@ class PfwBaseTranslator(object):
def _getContext(self):
return {
- 'domain': self._ctx_domain,
- 'configuration': self._ctx_configuration,
- 'sequence_aware': self._ctx_sequence_aware,
- 'command': self._ctx_command}
+ 'domain': self._ctx_domain,
+ 'configuration': self._ctx_configuration,
+ 'sequence_aware': self._ctx_sequence_aware,
+ 'command': self._ctx_command}
def _check(self, func):
"""Check and handles exceptions
diff --git a/upstream/tools/xmlGenerator/domainGenerator.py b/upstream/tools/xmlGenerator/domainGenerator.py
index 12a26f1..0051329 100755
--- a/upstream/tools/xmlGenerator/domainGenerator.py
+++ b/upstream/tools/xmlGenerator/domainGenerator.py
@@ -1,4 +1,4 @@
-#! /usr/bin/python
+#! /usr/bin/python3
#
# Copyright (c) 2011-2015, Intel Corporation
# All rights reserved.
@@ -28,10 +28,6 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-import EddParser
-from PFWScriptGenerator import PfwScriptTranslator
-import hostConfig
-
import argparse
import re
import sys
@@ -40,51 +36,57 @@ import os
import logging
import subprocess
+import EddParser
+from PFWScriptGenerator import PfwScriptTranslator
+import hostConfig
+
+
def parseArgs():
argparser = argparse.ArgumentParser(description="Parameter-Framework XML \
- Settings file generator.\n\
- Exit with the number of (recoverable or not) error that occured.")
+ Settings file generator.\n\
+ Exit with the number of (recoverable or not) \
+ error that occured.")
argparser.add_argument('--toplevel-config',
- help="Top-level parameter-framework configuration file. Mandatory.",
- metavar="TOPLEVEL_CONFIG_FILE",
- required=True)
+ help="Top-level parameter-framework configuration file. Mandatory.",
+ metavar="TOPLEVEL_CONFIG_FILE",
+ required=True)
argparser.add_argument('--criteria',
- help="Criteria file, in '<type> <name> : <value> <value...>' \
- format. Mandatory.",
- metavar="CRITERIA_FILE",
- type=argparse.FileType('r'),
- required=True)
+ help="Criteria file, in '<type> <name> : <value> <value...>' \
+ format. Mandatory.",
+ metavar="CRITERIA_FILE",
+ type=argparse.FileType('r'),
+ required=True)
argparser.add_argument('--initial-settings',
- help="Initial XML settings file (containing a \
- <ConfigurableDomains> tag",
- nargs='?',
- default=None,
- metavar="XML_SETTINGS_FILE")
+ help="Initial XML settings file (containing a \
+ <ConfigurableDomains> tag",
+ nargs='?',
+ default=None,
+ metavar="XML_SETTINGS_FILE")
argparser.add_argument('--add-domains',
- help="List of single domain files (each containing a single \
- <ConfigurableDomain> tag",
- metavar="XML_DOMAIN_FILE",
- nargs='*',
- dest='xml_domain_files',
- default=[])
+ help="List of single domain files (each containing a single \
+ <ConfigurableDomain> tag",
+ metavar="XML_DOMAIN_FILE",
+ nargs='*',
+ dest='xml_domain_files',
+ default=[])
argparser.add_argument('--add-edds',
- help="List of files in EDD syntax (aka \".pfw\" files)",
- metavar="EDD_FILE",
- type=argparse.FileType('r'),
- nargs='*',
- default=[],
- dest='edd_files')
+ help="List of files in EDD syntax (aka \".pfw\" files)",
+ metavar="EDD_FILE",
+ type=argparse.FileType('r'),
+ nargs='*',
+ default=[],
+ dest='edd_files')
argparser.add_argument('--schemas-dir',
- help="Directory of parameter-framework XML Schemas for generation \
- validation",
- default=None)
+ help="Directory of parameter-framework XML Schemas for generation \
+ validation",
+ default=None)
argparser.add_argument('--target-schemas-dir',
- help="Ignored. Kept for retro-compatibility")
+ help="Ignored. Kept for retro-compatibility")
argparser.add_argument('--validate',
- help="Validate the settings against XML schemas",
- action='store_true')
+ help="Validate the settings against XML schemas",
+ action='store_true')
argparser.add_argument('--verbose',
- action='store_true')
+ action='store_true')
return argparser.parse_args()
@@ -140,7 +142,7 @@ def parseEdd(EDDFiles):
try:
root.propagate()
- except EddParser.MyPropagationError as ex :
+ except EddParser.MyPropagationError as ex:
logging.critical(str(ex))
logging.info("EXIT ON FAILURE")
exit(1)
@@ -148,32 +150,32 @@ def parseEdd(EDDFiles):
parsed_edds.append((edd_file.name, root))
return parsed_edds
-def generateDomainCommands(logging, all_criteria, initial_settings, xml_domain_files, parsed_edds):
- # create and inject all the criteria
- logging.info("Creating all criteria")
- for criterion in all_criteria:
- yield ["createSelectionCriterion", criterion['inclusive'],
- criterion['name']] + criterion['values']
-
- yield ["start"]
-
- # Import initial settings file
- if initial_settings:
- logging.info("Importing initial settings file {}".format(initial_settings))
- yield ["importDomainsWithSettingsXML", initial_settings]
-
- # Import each standalone domain files
- for domain_file in xml_domain_files:
- logging.info("Importing single domain file {}".format(domain_file))
- yield ["importDomainWithSettingsXML", domain_file]
-
- # Generate the script for each EDD file
- for filename, parsed_edd in parsed_edds:
- logging.info("Translating and injecting EDD file {}".format(filename))
- translator = PfwScriptTranslator()
- parsed_edd.translate(translator)
- for command in translator.getScript():
- yield command
+def generateDomainCommands(logger, all_criteria, initial_settings, xml_domain_files, parsed_edds):
+ # create and inject all the criteria
+ logger.info("Creating all criteria")
+ for criterion in all_criteria:
+ yield ["createSelectionCriterion", criterion['inclusive'],
+ criterion['name']] + criterion['values']
+
+ yield ["start"]
+
+ # Import initial settings file
+ if initial_settings:
+ logger.info("Importing initial settings file {}".format(initial_settings))
+ yield ["importDomainsWithSettingsXML", initial_settings]
+
+ # Import each standalone domain files
+ for domain_file in xml_domain_files:
+ logger.info("Importing single domain file {}".format(domain_file))
+ yield ["importDomainWithSettingsXML", domain_file]
+
+ # Generate the script for each EDD file
+ for filename, parsed_edd in parsed_edds:
+ logger.info("Translating and injecting EDD file {}".format(filename))
+ translator = PfwScriptTranslator()
+ parsed_edd.translate(translator)
+ for command in translator.getScript():
+ yield command
def main():
logging.root.setLevel(logging.INFO)
@@ -193,28 +195,27 @@ def main():
prefix="TMPdomainGeneratorPFConfig_")
install_path = os.path.dirname(os.path.realpath(args.toplevel_config))
- hostConfig.configure(
- infile=args.toplevel_config,
- outfile=fake_toplevel_config,
- structPath=install_path)
+ hostConfig.configure(infile=args.toplevel_config,
+ outfile=fake_toplevel_config,
+ structPath=install_path)
fake_toplevel_config.close()
# Create the connector. Pipe its input to us in order to write commands;
# connect its output to stdout in order to have it dump the domains
# there; connect its error output to stderr.
connector = subprocess.Popen(["domainGeneratorConnector",
- fake_toplevel_config.name,
- 'verbose' if args.verbose else 'no-verbose',
- 'validate' if args.validate else 'no-validate',
- args.schemas_dir],
- stdout=sys.stdout, stdin=subprocess.PIPE, stderr=sys.stderr)
+ fake_toplevel_config.name,
+ 'verbose' if args.verbose else 'no-verbose',
+ 'validate' if args.validate else 'no-validate',
+ args.schemas_dir],
+ stdout=sys.stdout, stdin=subprocess.PIPE, stderr=sys.stderr)
initial_settings = None
if args.initial_settings:
initial_settings = os.path.realpath(args.initial_settings)
for command in generateDomainCommands(logging, all_criteria, initial_settings,
- args.xml_domain_files, parsed_edds):
+ args.xml_domain_files, parsed_edds):
connector.stdin.write('\0'.join(command))
connector.stdin.write("\n")
diff --git a/upstream/tools/xmlGenerator/hostConfig.py b/upstream/tools/xmlGenerator/hostConfig.py
index 871f8f2..647d652 100755
--- a/upstream/tools/xmlGenerator/hostConfig.py
+++ b/upstream/tools/xmlGenerator/hostConfig.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
# -*-coding:utf-8 -*
# Copyright (c) 2011-2014, Intel Corporation
@@ -57,7 +57,7 @@ def configure(infile=sys.stdin, outfile=sys.stdout, serverPort=None, structPath=
outfile.write(dom.toxml())
-if __name__ == "__main__" :
+if __name__ == "__main__":
""" Execute main if the python interpreter is running this module as the main program """
configure(serverPort=sys.argv[1], structPath=sys.argv[2])
diff --git a/upstream/tools/xmlValidator/xmlValidator.py b/upstream/tools/xmlValidator/xmlValidator.py
index ccf4bd0..3de29a1 100755
--- a/upstream/tools/xmlValidator/xmlValidator.py
+++ b/upstream/tools/xmlValidator/xmlValidator.py
@@ -1,4 +1,4 @@
-#! /usr/bin/python
+#! /usr/bin/python3
# Copyright (c) 2014, Intel Corporation
# All rights reserved.
@@ -28,20 +28,21 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-from lxml import etree
from os import path
from os import walk
from sys import argv
+from lxml import etree
+
class PrintColor():
@staticmethod
def success(stringToPrint):
- green=32
+ green = 32
PrintColor._printColor(green, stringToPrint)
@staticmethod
def error(stringToPrint):
- red=31
+ red = 31
PrintColor._printColor(red, stringToPrint)
@staticmethod