Rules checker#
This section provides an example of how to define a rule using the base class Rule. The example rule checks
if the operators’ pathname exceeds a certain threshold in a Scade One project.
from ansys.scadeone.core import swan
from ansys.scadeone.core.svc.metrics_rules.rules import Rule, RuleSeverity, RuleResult, RuleStatus
class OperatorNamePathLength(Rule):
def __init__(
self,
id: str = "SCADEONE_R001",
label: str = "Operator Name Path Length Check",
description: str = "This rule checks that the full path of an operator declaration does not exceed a certain length.",
category: str = "Naming",
severity: RuleSeverity = RuleSeverity.MANDATORY,
types: list[type[swan.SwanItem]] | None = [swan.OperatorDeclarationDefinitionBase],
parameters: str = "max=50",
):
super().__init__(
id=id,
label=label,
category=category,
severity=severity,
types=types,
description=description,
parameters=parameters,
)
def on_check(self, item: swan.SwanItem) -> RuleResult:
if not self.parameters:
return RuleResult(
status=RuleStatus.ERROR, message="Maximum length of operator namepath is required."
)
max_len = self._parse_parameters()
if len(item.get_full_path()) > max_len:
return RuleResult(RuleStatus.FAILED, "Operator path length exceeds maximum.")
return RuleResult(RuleStatus.OK)
def _parse_parameters(self):
try:
key, value = self.parameters.split("=")
if key.strip() != "max":
raise ValueError("Invalid parameter key. Expected 'max'.")
return int(value.strip())
except Exception as e:
raise ValueError(
f"Invalid parameters format: {self.parameters}. Expected format: 'max=<int>'. Error: {e}"
)