style: ruff format and the lint rules of the driver standard

Mechanical: ruff format, and ruff check --fix with the rule set every NAPALM
driver uses (E, F, I, UP, B at line length 100, Python 3.10). What ruff
cannot fix comes in the next commit.
This commit is contained in:
Christian Manivong committed 2026-10-23 08:32:47 +02:00
1 parent 7f2ae6ac58
commit a212bc8715
14 files changed
+322 -239

No files matched your search

+72 -59
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
@@ -16,8 +15,6 @@ from __future__ import annotations
import re
from typing import Any
#: Printed after a command so its exit status survives the shell session.
_RC_MARKER = "__OWRT_RC="
_RC_RE = re.compile(rf"^{_RC_MARKER}(\d+)\s*$", re.MULTILINE)
@@ -31,6 +28,7 @@ def _split_status(raw: str) -> tuple[str, int | None]:
output = _RC_RE.sub("", raw or "").strip()
return output, int(statuses[-1]) if statuses else None
class OpenWrtSystemMixin:
"""Mixin providing system-level NAPALM getters (environment, NTP, SNMP, users, services, updates, device actions)."""
@@ -95,9 +93,7 @@ class OpenWrtSystemMixin:
"""
sys_out = self._send_command("uci show system 2>/dev/null || true")
db_out = self._send_command("uci show dropbear 2>/dev/null || true")
luci_out = self._send_command(
"/etc/init.d/uhttpd enabled 2>/dev/null && echo 1 || echo 0"
)
luci_out = self._send_command("/etc/init.d/uhttpd enabled 2>/dev/null && echo 1 || echo 0")
net_out = self._send_command("uci show network 2>/dev/null || true")
sys_cfg: dict[str, str] = {}
@@ -238,7 +234,8 @@ class OpenWrtSystemMixin:
running = (
self._send_command(
"/etc/init.d/snmpd running 2>/dev/null && echo active || echo inactive"
).strip() == "active"
).strip()
== "active"
)
if not running:
return None
@@ -282,7 +279,13 @@ class OpenWrtSystemMixin:
if len(parts) < 7:
continue
username, password_hash, uid_str, _, _, home, shell = (
parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6],
parts[0],
parts[1],
parts[2],
parts[3],
parts[4],
parts[5],
parts[6],
)
if shell not in valid_shells:
continue
@@ -325,9 +328,7 @@ class OpenWrtSystemMixin:
import json as _json
# -- enabled set: names from /etc/rc.d/S<priority><name> symlinks ----
rc_out = self._send_command(
"ls /etc/rc.d/ 2>/dev/null | grep '^S' | sed 's/^S[0-9]*//'"
)
rc_out = self._send_command("ls /etc/rc.d/ 2>/dev/null | grep '^S' | sed 's/^S[0-9]*//'")
enabled: set[str] = {s.strip() for s in rc_out.splitlines() if s.strip()}
# -- running info from procd via ubus ---------------------------------
@@ -345,9 +346,7 @@ class OpenWrtSystemMixin:
continue
instances = svc_info.get("instances", {})
running = any(
inst.get("running", False)
for inst in instances.values()
if isinstance(inst, dict)
inst.get("running", False) for inst in instances.values() if isinstance(inst, dict)
)
pid = next(
(
@@ -371,21 +370,24 @@ class OpenWrtSystemMixin:
result: list[dict[str, Any]] = []
for name in sorted(all_names):
info = service_map.get(name, {})
result.append({
"name": name,
"running": info.get("running", False),
"enabled": name in enabled,
"pid": info.get("pid", 0),
})
result.append(
{
"name": name,
"running": info.get("running", False),
"enabled": name in enabled,
"pid": info.get("pid", 0),
}
)
return result
def manage_service(self, name: str, action: str) -> dict[str, Any]:
"""Execute a lifecycle action (start/stop/restart/enable/disable) on a service."""
import re as _re
if not _re.match(r'^[a-zA-Z0-9_\-]+$', name):
if not _re.match(r"^[a-zA-Z0-9_\-]+$", name):
raise ValueError(f"Invalid service name: {name!r}")
if action not in ('start', 'stop', 'restart', 'enable', 'disable'):
if action not in ("start", "stop", "restart", "enable", "disable"):
raise ValueError(f"Invalid action: {action!r}")
output = self._send_command(f"/etc/init.d/{name} {action} 2>&1")
return {"success": True, "output": output}
@@ -417,11 +419,13 @@ class OpenWrtSystemMixin:
# Output format: "pkgname-current_ver < new_ver"
m = _re.match(r"^(.+)-(\d\S*)\s+<\s+(\S+)", line.strip())
if m:
updates.append({
"name": m.group(1),
"current_version": m.group(2),
"new_version": m.group(3),
})
updates.append(
{
"name": m.group(1),
"current_version": m.group(2),
"new_version": m.group(3),
}
)
return updates
def _updates_opkg(self) -> list[dict[str, Any]]:
@@ -436,11 +440,13 @@ class OpenWrtSystemMixin:
# opkg output: "pkgname - current_ver - new_ver"
parts = [p.strip() for p in line.split(" - ")]
if len(parts) == 3:
updates.append({
"name": parts[0],
"current_version": parts[1],
"new_version": parts[2],
})
updates.append(
{
"name": parts[0],
"current_version": parts[1],
"new_version": parts[2],
}
)
return updates
def refresh_available_updates(self) -> dict[str, Any]:
@@ -452,8 +458,9 @@ class OpenWrtSystemMixin:
def apply_updates(self, packages: list[str]) -> dict[str, Any]:
"""Upgrade the given packages using the device's package manager."""
import re as _re
for pkg in packages:
if not _re.match(r'^[a-zA-Z0-9_\-\+\.]+$', pkg):
if not _re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
raise ValueError(f"Invalid package name: {pkg!r}")
pm = self._pm_type()
pkg_args = " ".join(packages)
@@ -535,19 +542,21 @@ class OpenWrtSystemMixin:
if len(parts) < 10:
continue
try:
stats.append({
"remote": parts[0],
"referenceid": parts[1],
"synchronized": tally == "*",
"stratum": int(parts[2]),
"type": parts[3],
"when": parts[4],
"hostpoll": int(parts[5]),
"reachability": int(parts[6], 8), # octal
"delay": float(parts[7]),
"offset": float(parts[8]),
"jitter": float(parts[9]),
})
stats.append(
{
"remote": parts[0],
"referenceid": parts[1],
"synchronized": tally == "*",
"stratum": int(parts[2]),
"type": parts[3],
"when": parts[4],
"hostpoll": int(parts[5]),
"reachability": int(parts[6], 8), # octal
"delay": float(parts[7]),
"offset": float(parts[8]),
"jitter": float(parts[9]),
}
)
except (ValueError, IndexError):
continue
return stats
@@ -564,19 +573,23 @@ class OpenWrtSystemMixin:
continue
tally = m.group(1)
try:
stats.append({
"remote": m.group(2),
"referenceid": "",
"synchronized": tally == "^*",
"stratum": int(m.group(3)),
"type": "u",
"when": m.group(6),
"hostpoll": int(m.group(4)),
"reachability": int(m.group(5), 8) if re.match(r"^[0-7]+$", m.group(5)) else 0,
"delay": 0.0,
"offset": 0.0,
"jitter": 0.0,
})
stats.append(
{
"remote": m.group(2),
"referenceid": "",
"synchronized": tally == "^*",
"stratum": int(m.group(3)),
"type": "u",
"when": m.group(6),
"hostpoll": int(m.group(4)),
"reachability": int(m.group(5), 8)
if re.match(r"^[0-7]+$", m.group(5))
else 0,
"delay": 0.0,
"offset": 0.0,
"jitter": 0.0,
}
)
except (ValueError, IndexError):
continue
return stats