ros2inspector 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ros2inspector/__init__.py +10 -0
- ros2inspector/cache/__init__.py +0 -0
- ros2inspector/cache/analysis_cache.py +110 -0
- ros2inspector/cli/__init__.py +0 -0
- ros2inspector/cli/_output.py +15 -0
- ros2inspector/cli/_state.py +5 -0
- ros2inspector/cli/_workspace.py +56 -0
- ros2inspector/cli/app.py +55 -0
- ros2inspector/cli/cmd_audit.py +362 -0
- ros2inspector/cli/cmd_graph.py +77 -0
- ros2inspector/cli/cmd_nodes.py +274 -0
- ros2inspector/cli/cmd_packages.py +119 -0
- ros2inspector/cli/cmd_scan.py +88 -0
- ros2inspector/cli/cmd_validate.py +175 -0
- ros2inspector/cli/cmd_viz.py +59 -0
- ros2inspector/discovery/__init__.py +23 -0
- ros2inspector/discovery/errors.py +34 -0
- ros2inspector/discovery/interface_finder.py +8 -0
- ros2inspector/discovery/package_finder.py +93 -0
- ros2inspector/discovery/workspace.py +48 -0
- ros2inspector/graph/__init__.py +3 -0
- ros2inspector/graph/renderer.py +178 -0
- ros2inspector/model/__init__.py +25 -0
- ros2inspector/model/schemas.py +105 -0
- ros2inspector/model/uam.py +694 -0
- ros2inspector/output/__init__.py +0 -0
- ros2inspector/policy/__init__.py +3 -0
- ros2inspector/policy/engine.py +141 -0
- ros2inspector/policy/rules.py +482 -0
- ros2inspector/static/__init__.py +18 -0
- ros2inspector/static/cpp_parser.py +316 -0
- ros2inspector/static/health_scorer.py +100 -0
- ros2inspector/static/interface_parser.py +39 -0
- ros2inspector/static/launch_analyzer.py +229 -0
- ros2inspector/static/package_xml.py +80 -0
- ros2inspector/static/python_parser.py +257 -0
- ros2inspector/utils/__init__.py +0 -0
- ros2inspector/utils/enums.py +10 -0
- ros2inspector/viz/__init__.py +3 -0
- ros2inspector/viz/_cytoscape.min.js +32 -0
- ros2inspector/viz/renderer.py +868 -0
- ros2inspector-0.1.0.dist-info/METADATA +312 -0
- ros2inspector-0.1.0.dist-info/RECORD +47 -0
- ros2inspector-0.1.0.dist-info/WHEEL +5 -0
- ros2inspector-0.1.0.dist-info/entry_points.txt +2 -0
- ros2inspector-0.1.0.dist-info/licenses/LICENSE +21 -0
- ros2inspector-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""ROS2 Inspector — architectural analysis and governance for ROS 2 workspaces."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("ros2inspector")
|
|
7
|
+
except PackageNotFoundError: # pragma: no cover - only when run from an uninstalled checkout
|
|
8
|
+
__version__ = "0.0.0+unknown"
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
|
File without changes
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import logging
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import diskcache
|
|
9
|
+
|
|
10
|
+
from ros2inspector.model.schemas import InterfaceDefinition, NodeDefinition
|
|
11
|
+
|
|
12
|
+
_LOG = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
_DEFAULT_CACHE_DIR = Path.home() / ".cache" / "ros2inspector"
|
|
15
|
+
|
|
16
|
+
_SOURCE_SUFFIXES = frozenset((".py", ".cpp", ".hpp", ".h", ".msg", ".srv", ".action"))
|
|
17
|
+
|
|
18
|
+
_CACHE_VERSION = "v3-content-sha256"
|
|
19
|
+
_CACHE_SIZE_LIMIT = 256 * 1024 * 1024 # 256 MB
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _pkg_fingerprint(pkg_path: Path) -> str:
|
|
23
|
+
"""SHA-256 of relative paths and file contents for all package source inputs."""
|
|
24
|
+
h = hashlib.sha256()
|
|
25
|
+
h.update(_CACHE_VERSION.encode())
|
|
26
|
+
files: list[Path] = sorted(
|
|
27
|
+
f
|
|
28
|
+
for f in pkg_path.rglob("*")
|
|
29
|
+
if f.is_file() and (f.suffix in _SOURCE_SUFFIXES or f.name == "package.xml")
|
|
30
|
+
)
|
|
31
|
+
for f in files:
|
|
32
|
+
try:
|
|
33
|
+
h.update(str(f.relative_to(pkg_path)).encode("utf-8", errors="surrogateescape"))
|
|
34
|
+
h.update(b"\0")
|
|
35
|
+
with f.open("rb") as stream:
|
|
36
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
37
|
+
h.update(chunk)
|
|
38
|
+
h.update(b"\0")
|
|
39
|
+
except OSError:
|
|
40
|
+
pass
|
|
41
|
+
return h.hexdigest()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AnalysisCache:
|
|
45
|
+
"""Disk-backed cache for per-package parse results.
|
|
46
|
+
|
|
47
|
+
Keys are SHA-256 fingerprints of package source paths and contents.
|
|
48
|
+
Values are serialised lists of NodeDefinition and InterfaceDefinition.
|
|
49
|
+
A stale entry is never served — any file change invalidates the key.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, cache_dir: Path | None = None) -> None:
|
|
53
|
+
self._dir = cache_dir or _DEFAULT_CACHE_DIR
|
|
54
|
+
self._cache: diskcache.Cache = diskcache.Cache(str(self._dir), size_limit=_CACHE_SIZE_LIMIT)
|
|
55
|
+
# One-slot memoisation so a get() + set() pair on the same path only
|
|
56
|
+
# runs the rglob/stat fingerprint scan once instead of twice.
|
|
57
|
+
self._fp_cache: tuple[Path, str] | None = None
|
|
58
|
+
|
|
59
|
+
def _fingerprint(self, pkg_path: Path) -> str:
|
|
60
|
+
if self._fp_cache is not None and self._fp_cache[0] == pkg_path:
|
|
61
|
+
return self._fp_cache[1]
|
|
62
|
+
fp = _pkg_fingerprint(pkg_path)
|
|
63
|
+
self._fp_cache = (pkg_path, fp)
|
|
64
|
+
return fp
|
|
65
|
+
|
|
66
|
+
# ── public API ─────────────────────────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
def get(self, pkg_path: Path) -> tuple[list[NodeDefinition], list[InterfaceDefinition]] | None:
|
|
69
|
+
key = self._fingerprint(pkg_path)
|
|
70
|
+
result: Any = self._cache.get(key)
|
|
71
|
+
if result is None:
|
|
72
|
+
_LOG.debug("cache miss: %s", pkg_path)
|
|
73
|
+
return None
|
|
74
|
+
_LOG.debug("cache hit: %s", pkg_path)
|
|
75
|
+
nodes_raw, ifaces_raw = result
|
|
76
|
+
nodes = [NodeDefinition.model_validate(n) for n in nodes_raw]
|
|
77
|
+
ifaces = [InterfaceDefinition.model_validate(i) for i in ifaces_raw]
|
|
78
|
+
return nodes, ifaces
|
|
79
|
+
|
|
80
|
+
def set(
|
|
81
|
+
self,
|
|
82
|
+
pkg_path: Path,
|
|
83
|
+
nodes: list[NodeDefinition],
|
|
84
|
+
ifaces: list[InterfaceDefinition],
|
|
85
|
+
) -> None:
|
|
86
|
+
key = self._fingerprint(pkg_path) # reuses the value computed by get()
|
|
87
|
+
self._cache.set(
|
|
88
|
+
key,
|
|
89
|
+
(
|
|
90
|
+
[n.model_dump(mode="json") for n in nodes],
|
|
91
|
+
[i.model_dump(mode="json") for i in ifaces],
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def clear(self) -> None:
|
|
96
|
+
self._cache.clear()
|
|
97
|
+
|
|
98
|
+
def close(self) -> None:
|
|
99
|
+
self._cache.close()
|
|
100
|
+
|
|
101
|
+
def stats(self) -> dict[str, Any]:
|
|
102
|
+
return {"size": len(self._cache), "directory": str(self._dir)}
|
|
103
|
+
|
|
104
|
+
# ── context manager ────────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
def __enter__(self) -> AnalysisCache:
|
|
107
|
+
return self
|
|
108
|
+
|
|
109
|
+
def __exit__(self, *_: Any) -> None:
|
|
110
|
+
self.close()
|
|
File without changes
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from ros2inspector.utils.enums import StrEnum
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class OutputFormat(StrEnum):
|
|
5
|
+
TABLE = "table"
|
|
6
|
+
JSON = "json"
|
|
7
|
+
YAML = "yaml"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def health_bar(score: int, include_score: bool = True) -> str:
|
|
11
|
+
filled = round(score / 10)
|
|
12
|
+
color = "green" if score >= 70 else "yellow" if score >= 40 else "red"
|
|
13
|
+
bar = "█" * filled + "░" * (10 - filled)
|
|
14
|
+
suffix = f" {score}/100" if include_score else ""
|
|
15
|
+
return f"[{color}]{bar}[/{color}]{suffix}"
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import NoReturn
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
|
|
9
|
+
from ros2inspector.discovery import (
|
|
10
|
+
DuplicatePackageError,
|
|
11
|
+
NoPackagesFoundError,
|
|
12
|
+
WorkspaceAnalysisError,
|
|
13
|
+
find_package_xml_files,
|
|
14
|
+
)
|
|
15
|
+
from ros2inspector.model.schemas import PackageMetadata
|
|
16
|
+
from ros2inspector.model.uam import UAM, UnifiedArchitectureModel
|
|
17
|
+
from ros2inspector.static import parse_package_xml
|
|
18
|
+
|
|
19
|
+
_err_console = Console(stderr=True)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _exit_workspace_error(exc: WorkspaceAnalysisError) -> NoReturn:
|
|
23
|
+
_err_console.print(f"[red]Workspace error:[/red] {exc}")
|
|
24
|
+
raise typer.Exit(3) from exc
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load_packages_or_exit(root: Path) -> list[PackageMetadata]:
|
|
28
|
+
"""Load a non-empty, unambiguous package set or terminate the CLI cleanly."""
|
|
29
|
+
packages = [
|
|
30
|
+
package
|
|
31
|
+
for package_xml in find_package_xml_files(root)
|
|
32
|
+
if (package := parse_package_xml(package_xml)) is not None
|
|
33
|
+
]
|
|
34
|
+
if not packages:
|
|
35
|
+
_exit_workspace_error(NoPackagesFoundError(root))
|
|
36
|
+
|
|
37
|
+
by_name: dict[str, list[Path]] = {}
|
|
38
|
+
for package in packages:
|
|
39
|
+
by_name.setdefault(package.name, []).append(Path(package.path).resolve())
|
|
40
|
+
duplicates = {name: paths for name, paths in by_name.items() if len(paths) > 1}
|
|
41
|
+
if duplicates:
|
|
42
|
+
_exit_workspace_error(DuplicatePackageError(duplicates))
|
|
43
|
+
return packages
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def build_uam_or_exit(
|
|
47
|
+
root: Path,
|
|
48
|
+
*,
|
|
49
|
+
use_cache: bool,
|
|
50
|
+
show_progress: bool = False,
|
|
51
|
+
) -> UnifiedArchitectureModel:
|
|
52
|
+
"""Build the model and map user-actionable workspace failures to exit code 3."""
|
|
53
|
+
try:
|
|
54
|
+
return UAM.build(root, use_cache=use_cache, show_progress=show_progress)
|
|
55
|
+
except WorkspaceAnalysisError as exc:
|
|
56
|
+
_exit_workspace_error(exc)
|
ros2inspector/cli/app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from typing import Annotated
|
|
2
|
+
|
|
3
|
+
import typer
|
|
4
|
+
from rich.console import Console
|
|
5
|
+
|
|
6
|
+
from ros2inspector import __version__
|
|
7
|
+
from ros2inspector.cli import (
|
|
8
|
+
cmd_audit,
|
|
9
|
+
cmd_graph,
|
|
10
|
+
cmd_nodes,
|
|
11
|
+
cmd_packages,
|
|
12
|
+
cmd_scan,
|
|
13
|
+
cmd_validate,
|
|
14
|
+
cmd_viz,
|
|
15
|
+
)
|
|
16
|
+
from ros2inspector.cli._state import state
|
|
17
|
+
|
|
18
|
+
app = typer.Typer(
|
|
19
|
+
name="ros2inspector",
|
|
20
|
+
help="Static ROS 2 architecture analysis, visualization, and policy checks.",
|
|
21
|
+
add_completion=False,
|
|
22
|
+
)
|
|
23
|
+
_console = Console(stderr=True)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def version_callback(value: bool) -> None:
|
|
27
|
+
if value:
|
|
28
|
+
_console.print(f"ros2inspector v{__version__}")
|
|
29
|
+
raise typer.Exit()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@app.callback()
|
|
33
|
+
def main(
|
|
34
|
+
version: bool = typer.Option(
|
|
35
|
+
False, "--version", "-v", callback=version_callback, is_eager=True
|
|
36
|
+
),
|
|
37
|
+
quiet: Annotated[
|
|
38
|
+
bool,
|
|
39
|
+
typer.Option("--quiet", "-q", help="Suppress diagnostic headers and progress output"),
|
|
40
|
+
] = False,
|
|
41
|
+
) -> None:
|
|
42
|
+
state.quiet = quiet
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
app.add_typer(cmd_scan.app, name="scan")
|
|
46
|
+
app.add_typer(cmd_packages.app, name="packages")
|
|
47
|
+
app.add_typer(cmd_nodes.app, name="nodes")
|
|
48
|
+
app.add_typer(cmd_graph.app, name="graph")
|
|
49
|
+
app.add_typer(cmd_viz.app, name="viz")
|
|
50
|
+
app.add_typer(cmd_audit.app, name="audit")
|
|
51
|
+
app.add_typer(cmd_validate.app, name="validate")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def run() -> None:
|
|
55
|
+
app()
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Annotated, Any
|
|
6
|
+
|
|
7
|
+
import orjson
|
|
8
|
+
import typer
|
|
9
|
+
import yaml
|
|
10
|
+
from rich import box
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.panel import Panel
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
from rich.text import Text
|
|
15
|
+
|
|
16
|
+
from ros2inspector.cli._output import OutputFormat, health_bar
|
|
17
|
+
from ros2inspector.cli._state import state
|
|
18
|
+
from ros2inspector.cli._workspace import build_uam_or_exit
|
|
19
|
+
from ros2inspector.discovery import find_workspace_root
|
|
20
|
+
from ros2inspector.model.schemas import PolicyViolation, ViolationSeverity
|
|
21
|
+
from ros2inspector.policy.rules import (
|
|
22
|
+
rule_action_connectivity,
|
|
23
|
+
rule_node_isolation,
|
|
24
|
+
rule_service_connectivity,
|
|
25
|
+
rule_topic_connectivity,
|
|
26
|
+
)
|
|
27
|
+
from ros2inspector.static import workspace_aggregate_score
|
|
28
|
+
|
|
29
|
+
app = typer.Typer(
|
|
30
|
+
help="Run architecture quality audit without a policy file.",
|
|
31
|
+
context_settings={"allow_interspersed_args": True},
|
|
32
|
+
)
|
|
33
|
+
console = Console()
|
|
34
|
+
err_console = Console(stderr=True)
|
|
35
|
+
|
|
36
|
+
_SEVERITY_COLOR = {
|
|
37
|
+
ViolationSeverity.ERROR: "red",
|
|
38
|
+
ViolationSeverity.WARNING: "yellow",
|
|
39
|
+
ViolationSeverity.INFO: "cyan",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
_SEVERITY_ICON = {
|
|
43
|
+
ViolationSeverity.ERROR: "✖",
|
|
44
|
+
ViolationSeverity.WARNING: "⚠",
|
|
45
|
+
ViolationSeverity.INFO: "●",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
_DEFAULT_EXCLUDES = ["/rosout", "/parameter_events", "/clock", "/tf", "/tf_static"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _build_rules(exclude: list[str]) -> list[dict[str, Any]]:
|
|
52
|
+
return [
|
|
53
|
+
{
|
|
54
|
+
"type": "topic_connectivity",
|
|
55
|
+
"no_publisher": True,
|
|
56
|
+
"no_subscriber": True,
|
|
57
|
+
"severity_no_publisher": "warning",
|
|
58
|
+
"severity_no_subscriber": "info",
|
|
59
|
+
"exclude": exclude,
|
|
60
|
+
"_source": "audit",
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
"type": "node_isolation",
|
|
64
|
+
"severity": "warning",
|
|
65
|
+
"skip_dynamic_names": True,
|
|
66
|
+
"_source": "audit",
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
"type": "service_connectivity",
|
|
70
|
+
"severity": "info",
|
|
71
|
+
"_source": "audit",
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
"type": "action_connectivity",
|
|
75
|
+
"severity": "warning",
|
|
76
|
+
"_source": "audit",
|
|
77
|
+
},
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_RUNNERS = {
|
|
82
|
+
"topic_connectivity": rule_topic_connectivity,
|
|
83
|
+
"node_isolation": rule_node_isolation,
|
|
84
|
+
"service_connectivity": rule_service_connectivity,
|
|
85
|
+
"action_connectivity": rule_action_connectivity,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
_SECTION_TITLES = {
|
|
89
|
+
"topic_connectivity": "Topic Connectivity",
|
|
90
|
+
"node_isolation": "Node Isolation",
|
|
91
|
+
"service_connectivity": "Service Connectivity",
|
|
92
|
+
"action_connectivity": "Action Connectivity",
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
_SECTION_DESCRIPTIONS = {
|
|
96
|
+
"topic_connectivity": (
|
|
97
|
+
"Topics that are published but never subscribed (silent output) "
|
|
98
|
+
"or subscribed but never published (missing publisher)."
|
|
99
|
+
),
|
|
100
|
+
"node_isolation": (
|
|
101
|
+
"Nodes with no detected publishers, subscribers, services, or action connections. "
|
|
102
|
+
"May indicate misconfiguration or purely dynamic topic names."
|
|
103
|
+
),
|
|
104
|
+
"service_connectivity": (
|
|
105
|
+
"Services whose provider/client counterpart is missing in the analysed workspace. "
|
|
106
|
+
"The counterpart may be external or not yet implemented."
|
|
107
|
+
),
|
|
108
|
+
"action_connectivity": (
|
|
109
|
+
"Actions whose server/client counterpart is missing in the analysed workspace."
|
|
110
|
+
),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@app.callback(invoke_without_command=True)
|
|
115
|
+
def audit(
|
|
116
|
+
path: Annotated[Path, typer.Argument(help="Workspace root (default: CWD)")] = Path("."),
|
|
117
|
+
fmt: Annotated[
|
|
118
|
+
OutputFormat, typer.Option("--format", "-f", help="Output format: table|json|yaml")
|
|
119
|
+
] = OutputFormat.TABLE,
|
|
120
|
+
fail_on: Annotated[
|
|
121
|
+
str,
|
|
122
|
+
typer.Option("--fail-on", help="Min severity for non-zero exit: error|warning|info"),
|
|
123
|
+
] = "error",
|
|
124
|
+
strict: Annotated[
|
|
125
|
+
bool,
|
|
126
|
+
typer.Option("--strict", help="Treat warnings as errors for exit code"),
|
|
127
|
+
] = False,
|
|
128
|
+
exclude: Annotated[
|
|
129
|
+
str,
|
|
130
|
+
typer.Option(
|
|
131
|
+
"--exclude",
|
|
132
|
+
help="Comma-separated extra topics to exclude (e.g. /my_topic,/other)",
|
|
133
|
+
),
|
|
134
|
+
] = "",
|
|
135
|
+
no_cache: Annotated[
|
|
136
|
+
bool, typer.Option("--no-cache", help="Skip the incremental cache")
|
|
137
|
+
] = False,
|
|
138
|
+
) -> None:
|
|
139
|
+
"""Run an architecture quality audit on the workspace.
|
|
140
|
+
|
|
141
|
+
Checks topic connectivity, node isolation, unused services, and
|
|
142
|
+
action servers without clients — no policy file required.
|
|
143
|
+
|
|
144
|
+
Exit codes:
|
|
145
|
+
0 — no findings at or above --fail-on severity
|
|
146
|
+
1 — findings found at or above --fail-on severity
|
|
147
|
+
2 — invocation error
|
|
148
|
+
3 — workspace not found
|
|
149
|
+
|
|
150
|
+
Examples:
|
|
151
|
+
ros2inspector audit
|
|
152
|
+
ros2inspector audit --strict
|
|
153
|
+
ros2inspector audit --fail-on warning
|
|
154
|
+
ros2inspector audit --exclude /my_debug_topic,/legacy_cmd
|
|
155
|
+
ros2inspector audit --format json
|
|
156
|
+
"""
|
|
157
|
+
if fail_on not in ("error", "warning", "info"):
|
|
158
|
+
err_console.print("[red]Error:[/red] --fail-on must be error, warning, or info")
|
|
159
|
+
raise typer.Exit(2)
|
|
160
|
+
|
|
161
|
+
extra_excludes = [t.strip() for t in exclude.split(",") if t.strip()]
|
|
162
|
+
all_excludes = _DEFAULT_EXCLUDES + extra_excludes
|
|
163
|
+
|
|
164
|
+
root = find_workspace_root(path)
|
|
165
|
+
|
|
166
|
+
if not state.quiet:
|
|
167
|
+
diag = console if fmt == OutputFormat.TABLE else err_console
|
|
168
|
+
diag.print(
|
|
169
|
+
f"\n[bold cyan]ROS2 Inspector[/bold cyan] — architecture audit [dim]{root}[/dim]\n"
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
uam = build_uam_or_exit(root, use_cache=not no_cache, show_progress=not state.quiet)
|
|
173
|
+
|
|
174
|
+
rules = _build_rules(all_excludes)
|
|
175
|
+
violations: list[PolicyViolation] = []
|
|
176
|
+
for rule in rules:
|
|
177
|
+
runner = _RUNNERS[rule["type"]]
|
|
178
|
+
violations.extend(runner(uam, rule))
|
|
179
|
+
|
|
180
|
+
scores = {p.name: (p.health_score or 0) for p in uam.packages()}
|
|
181
|
+
agg = workspace_aggregate_score(scores)
|
|
182
|
+
summary_counts = uam.summary()
|
|
183
|
+
|
|
184
|
+
if fmt == OutputFormat.TABLE:
|
|
185
|
+
_render_table(violations, agg, summary_counts)
|
|
186
|
+
elif fmt == OutputFormat.JSON:
|
|
187
|
+
data = _build_data(violations, agg, summary_counts)
|
|
188
|
+
sys.stdout.write(orjson.dumps(data, option=orjson.OPT_INDENT_2).decode() + "\n")
|
|
189
|
+
else:
|
|
190
|
+
data = _build_data(violations, agg, summary_counts)
|
|
191
|
+
sys.stdout.write(yaml.dump(data, default_flow_style=False))
|
|
192
|
+
|
|
193
|
+
effective_fail = "warning" if strict else fail_on
|
|
194
|
+
_fail_on_sev = {
|
|
195
|
+
"error": {ViolationSeverity.ERROR},
|
|
196
|
+
"warning": {ViolationSeverity.ERROR, ViolationSeverity.WARNING},
|
|
197
|
+
"info": {ViolationSeverity.ERROR, ViolationSeverity.WARNING, ViolationSeverity.INFO},
|
|
198
|
+
}[effective_fail]
|
|
199
|
+
|
|
200
|
+
if any(v.severity in _fail_on_sev for v in violations):
|
|
201
|
+
raise typer.Exit(1)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _build_data(
|
|
205
|
+
violations: list[PolicyViolation],
|
|
206
|
+
workspace_health: int,
|
|
207
|
+
summary_counts: dict[str, int],
|
|
208
|
+
) -> dict[str, object]:
|
|
209
|
+
by_rule: dict[str, int] = {}
|
|
210
|
+
for v in violations:
|
|
211
|
+
by_rule[v.rule_type] = by_rule.get(v.rule_type, 0) + 1
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
"summary": {
|
|
215
|
+
"workspace_health": workspace_health,
|
|
216
|
+
"total_findings": len(violations),
|
|
217
|
+
"by_rule": by_rule,
|
|
218
|
+
"workspace": summary_counts,
|
|
219
|
+
},
|
|
220
|
+
"findings": [v.model_dump(mode="json") for v in violations],
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _render_table(
|
|
225
|
+
violations: list[PolicyViolation],
|
|
226
|
+
workspace_health: int,
|
|
227
|
+
summary_counts: dict[str, int],
|
|
228
|
+
) -> None:
|
|
229
|
+
# Group violations by rule type, preserving order
|
|
230
|
+
by_rule: dict[str, list[PolicyViolation]] = {}
|
|
231
|
+
for v in violations:
|
|
232
|
+
by_rule.setdefault(v.rule_type, []).append(v)
|
|
233
|
+
|
|
234
|
+
rule_order = [
|
|
235
|
+
"topic_connectivity",
|
|
236
|
+
"node_isolation",
|
|
237
|
+
"service_connectivity",
|
|
238
|
+
"action_connectivity",
|
|
239
|
+
]
|
|
240
|
+
|
|
241
|
+
if not violations:
|
|
242
|
+
console.print(
|
|
243
|
+
Panel(
|
|
244
|
+
"[bold green]✓ No architecture issues found.[/bold green]\n"
|
|
245
|
+
"[dim]All topics are connected, nodes communicate, "
|
|
246
|
+
"services and actions have counterparts.[/dim]",
|
|
247
|
+
title="[bold]Audit Result[/bold]",
|
|
248
|
+
border_style="green",
|
|
249
|
+
)
|
|
250
|
+
)
|
|
251
|
+
else:
|
|
252
|
+
for rule_type in rule_order:
|
|
253
|
+
rule_violations = by_rule.get(rule_type, [])
|
|
254
|
+
if not rule_violations:
|
|
255
|
+
continue
|
|
256
|
+
|
|
257
|
+
title = _SECTION_TITLES.get(rule_type, rule_type)
|
|
258
|
+
desc = _SECTION_DESCRIPTIONS.get(rule_type, "")
|
|
259
|
+
|
|
260
|
+
table = Table(
|
|
261
|
+
title=f"[bold]{title}[/bold]",
|
|
262
|
+
caption=f"[dim]{desc}[/dim]",
|
|
263
|
+
box=box.ROUNDED,
|
|
264
|
+
show_lines=True,
|
|
265
|
+
title_justify="left",
|
|
266
|
+
caption_justify="left",
|
|
267
|
+
min_width=70,
|
|
268
|
+
)
|
|
269
|
+
table.add_column("Sev", no_wrap=True, width=8)
|
|
270
|
+
table.add_column("Finding", overflow="fold")
|
|
271
|
+
table.add_column("Affected", overflow="fold", style="dim")
|
|
272
|
+
|
|
273
|
+
sev_order = {
|
|
274
|
+
ViolationSeverity.ERROR: 0,
|
|
275
|
+
ViolationSeverity.WARNING: 1,
|
|
276
|
+
ViolationSeverity.INFO: 2,
|
|
277
|
+
}
|
|
278
|
+
for v in sorted(rule_violations, key=lambda x: sev_order.get(x.severity, 9)):
|
|
279
|
+
color = _SEVERITY_COLOR.get(v.severity, "white")
|
|
280
|
+
icon = _SEVERITY_ICON.get(v.severity, "·")
|
|
281
|
+
table.add_row(
|
|
282
|
+
f"[{color}]{icon} {v.severity.upper()[:4]}[/{color}]",
|
|
283
|
+
v.message,
|
|
284
|
+
", ".join(v.affected_entities) if v.affected_entities else "—",
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
console.print(table)
|
|
288
|
+
console.print()
|
|
289
|
+
|
|
290
|
+
_render_summary(violations, workspace_health, summary_counts, by_rule)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _render_summary(
|
|
294
|
+
violations: list[PolicyViolation],
|
|
295
|
+
workspace_health: int,
|
|
296
|
+
summary_counts: dict[str, int],
|
|
297
|
+
by_rule: dict[str, list[PolicyViolation]],
|
|
298
|
+
) -> None:
|
|
299
|
+
errors = sum(1 for v in violations if v.severity == ViolationSeverity.ERROR)
|
|
300
|
+
warnings = sum(1 for v in violations if v.severity == ViolationSeverity.WARNING)
|
|
301
|
+
infos = sum(1 for v in violations if v.severity == ViolationSeverity.INFO)
|
|
302
|
+
|
|
303
|
+
counts_line = Text()
|
|
304
|
+
counts_line.append(
|
|
305
|
+
f"{summary_counts.get('packages', 0)} pkg "
|
|
306
|
+
f"{summary_counts.get('nodes', 0)} nodes "
|
|
307
|
+
f"{summary_counts.get('topics', 0)} topics "
|
|
308
|
+
f"{summary_counts.get('services', 0)} svc "
|
|
309
|
+
f"{summary_counts.get('actions', 0)} actions",
|
|
310
|
+
style="dim",
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
findings_line = Text()
|
|
314
|
+
if not violations:
|
|
315
|
+
findings_line.append("✓ Clean", style="bold green")
|
|
316
|
+
else:
|
|
317
|
+
parts = []
|
|
318
|
+
if errors:
|
|
319
|
+
parts.append((f"{errors} error(s)", "bold red"))
|
|
320
|
+
if warnings:
|
|
321
|
+
parts.append((f"{warnings} warning(s)", "bold yellow"))
|
|
322
|
+
if infos:
|
|
323
|
+
parts.append((f"{infos} info", "bold cyan"))
|
|
324
|
+
for i, (text, style) in enumerate(parts):
|
|
325
|
+
if i:
|
|
326
|
+
findings_line.append(" ", style="dim")
|
|
327
|
+
findings_line.append(text, style=style)
|
|
328
|
+
|
|
329
|
+
rule_breakdown = Text()
|
|
330
|
+
for rule_type, rule_violations in by_rule.items():
|
|
331
|
+
label = _SECTION_TITLES.get(rule_type, rule_type)
|
|
332
|
+
count = len(rule_violations)
|
|
333
|
+
rule_breakdown.append(f" {label}: ", style="dim")
|
|
334
|
+
rule_breakdown.append(str(count), style="bold")
|
|
335
|
+
rule_breakdown.append("\n")
|
|
336
|
+
|
|
337
|
+
body = Text()
|
|
338
|
+
body.append("Workspace ", style="dim")
|
|
339
|
+
body.append(counts_line)
|
|
340
|
+
body.append("\n")
|
|
341
|
+
body.append("Health ", style="dim")
|
|
342
|
+
body.append(Text.from_markup(health_bar(workspace_health)))
|
|
343
|
+
body.append("\n")
|
|
344
|
+
if violations:
|
|
345
|
+
body.append("Findings ", style="dim")
|
|
346
|
+
body.append(findings_line)
|
|
347
|
+
body.append("\n\n")
|
|
348
|
+
body.append(rule_breakdown)
|
|
349
|
+
else:
|
|
350
|
+
body.append("Findings ", style="dim")
|
|
351
|
+
body.append(findings_line)
|
|
352
|
+
|
|
353
|
+
border = (
|
|
354
|
+
"red"
|
|
355
|
+
if any(v.severity == ViolationSeverity.ERROR for v in violations)
|
|
356
|
+
else "yellow"
|
|
357
|
+
if violations
|
|
358
|
+
else "green"
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
console.print(Panel(body, title="[bold]Audit Summary[/bold]", border_style=border))
|
|
362
|
+
console.print()
|