feat: standards, shared CI and release tooling for NAPALM drivers
CI / test (3.11) (push) Successful in 34s
CI / test (3.12) (push) Successful in 30s
CI / test (3.13) (push) Successful in 37s

STANDARDS.md binds every repository in the NAPALM org: one default branch,
Conventional Commits, the device-types contract, test-driven development,
clean-code limits, a quality ratchet for existing code, packaging rules and
releases by tag to PyPI.

napalm-standard holds what a tool can check: the conformance check (with
release rules on a tag), the quality ratchet (ported from netOrk's
quality_ratchet.py), and the Gitea release from the CHANGELOG section.
.gitea/workflows/driver.yml is the CI every driver calls; template/ is a new
driver's starting point and passes the check as it is.
This commit is contained in:
christianmanivong committed 2026-10-22 19:01:14 +02:00
commit db6b2e4ea7
37 files changed
+2894

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
name: CI
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
jobs:
driver:
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
with:
standard-ref: main
secrets:
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+9
View File
@@ -0,0 +1,9 @@
__pycache__/
*.egg-info/
.venv/
build/
dist/
.coverage
.pytest_cache/
.mypy_cache/
.ruff_cache/
+12
View File
@@ -0,0 +1,12 @@
# Changelog
All notable changes to this driver. The format follows
[Keep a Changelog](https://keepachangelog.com/), versions follow
[Semantic Versioning](https://semver.org/).
## [Unreleased]
## [0.1.0] - 2026-10-22
### Added
- `example` driver: facts from Example switches over SSH.
+191
View File
@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship made available under
the License, as indicated by a copyright notice that is included in
or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other transformations
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean, as submitted to the Licensor for inclusion
in the Work by the copyright owner or by an individual or Legal Entity
authorized to submit on behalf of the copyright owner. For the purposes
of this definition, "submitted" means any form of electronic, verbal,
or written communication sent to the Licensor or its representatives,
including but not limited to communication on electronic mailing lists,
source code control systems, and issue tracking systems that are managed
by, or on behalf of, the Licensor for the purpose of discussing and
improving the Work, but excluding communication that is conspicuously
marked or designated in writing by the copyright owner as "Not a
Contribution."
"Contributor" shall mean Licensor and any Legal Entity on behalf of
whom a Contribution has been received by the Licensor and incorporated
within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by the combined Contribution(s) and the Work
to which such Contribution(s) was submitted. If You institute patent
litigation against any entity (including a cross-claim or counterclaim
in a lawsuit) alleging that the Work or any Contribution embodied
within the Work constitutes direct or contributory patent infringement,
then any patent licenses granted to You under this License for that
Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or Derivative
Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, You must include a readable copy of the
attribution notices contained within such NOTICE file, in
at least one of the following places: within a NOTICE text file
distributed as part of the Derivative Works; within the Source
form or documentation, if provided along with the Derivative
Works; or, within a display generated by the Derivative Works,
if and wherever such third-party notices normally appear. The
contents of the NOTICE file are for informational purposes only
and do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own license statement for Your modifications and
may provide additional grant of rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Work,
and to permit persons to whom the Work is furnished to do so,
subject to the following conditions:
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any conditions of TITLE,
MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE.
See the License for the specific language governing permissions and
limitations under the License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or exemplary damages of any character arising as a
result of this License or out of the use or inability to use the
Work (even if such Contributor has been advised of the possibility
of such damages).
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may offer only
conditions consistent with this License, subject to the following
additional conditions:
(a) You may offer additional warranty, indemnity, or other liability
terms and conditions; and
(b) You may offer support for the Work in return for a fee.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format in question. It may also be
possible to make it available with a creative commons license.
Copyright 2026 Christian Manivong
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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+45
View File
@@ -0,0 +1,45 @@
# napalm-example
NAPALM driver for Example switches, built on
[napalm-device-types](https://git.netork.io/NAPALM/napalm-device-types) (`SwitchDriver`).
## Tested against
| Model | Firmware |
|---|---|
| Example 24 | 1.0.0 |
## Connection
SSH on port 22. The account needs read access to `show version`.
```python
from napalm import get_network_driver
driver = get_network_driver("example")
with driver("192.0.2.10", "admin", "secret") as device:
print(device.get_facts())
```
## Supported
| Getter / action | |
|---|---|
| `get_facts` | yes |
## Not supported
Configuration changes.
## Development
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
```bash
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/pytest --cov
```
## License
Apache-2.0
+5
View File
@@ -0,0 +1,5 @@
"""NAPALM driver for Example switches."""
from napalm_example.driver import ExampleDriver
__all__ = ["ExampleDriver"]
+93
View File
@@ -0,0 +1,93 @@
"""NAPALM driver for Example switches over SSH.
Optional args
-------------
port : int
SSH port (default 22).
"""
from __future__ import annotations
import logging
from typing import Any, Protocol
from napalm.base.exceptions import ConnectionException
from napalm.base.models import FactsDict
from napalm_device_types import SwitchDriver
from napalm_example.parsers import parse_version
LOG = logging.getLogger(__name__)
VENDOR = "Example"
DEFAULT_PORT = 22
class Transport(Protocol):
def command(self, line: str) -> str: ...
def close(self) -> None: ...
class ExampleDriver(SwitchDriver):
"""A switch that answers line commands over SSH."""
def __init__(
self,
hostname: str,
username: str,
password: str,
timeout: int = 60,
optional_args: dict[str, Any] | None = None,
) -> None:
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
self.port = int((optional_args or {}).get("port", DEFAULT_PORT))
self.transport: Transport | None = None
def open(self) -> None: # pragma: no cover - live I/O
from netmiko import ConnectHandler
session = ConnectHandler(
device_type="generic",
host=self.hostname,
port=self.port,
username=self.username,
password=self.password,
timeout=self.timeout,
)
class _Netmiko:
def command(self, line: str) -> str:
return str(session.send_command(line))
def close(self) -> None:
session.disconnect()
self.transport = _Netmiko()
def close(self) -> None:
if self.transport is not None:
self.transport.close()
self.transport = None
def _command(self, line: str) -> str:
if self.transport is None:
raise ConnectionException(f"{self.hostname}: not connected; call open() first")
LOG.debug("%s: %s", self.hostname, line)
return self.transport.command(line)
def get_facts(self) -> FactsDict:
version = parse_version(self._command("show version"))
return {
"vendor": VENDOR,
"model": version["model"],
"hostname": version["hostname"],
"fqdn": version["hostname"],
"os_version": version["os_version"],
"serial_number": version["serial_number"],
"uptime": version["uptime"],
"interface_list": [],
}
@@ -0,0 +1,45 @@
"""Pure functions: device output in, typed values out. No I/O here."""
from __future__ import annotations
import re
from typing import TypedDict
#: "Key : value" lines of `show version`.
_FIELD = re.compile(r"^(?P<key>[^:\n]+?)\s*:\s*(?P<value>.*)$", re.MULTILINE)
#: "3 days, 4:05:06" or "4:05:06".
_UPTIME = re.compile(r"^(?:(?P<days>\d+) days?, )?(?P<h>\d+):(?P<m>\d\d):(?P<s>\d\d)$")
_SECONDS_PER_DAY = 86400
class VersionDict(TypedDict):
model: str
hostname: str
os_version: str
serial_number: str
uptime: float
def parse_uptime(text: str) -> float:
"""Seconds from an uptime like ``3 days, 4:05:06``."""
match = _UPTIME.match(text.strip())
if not match:
raise ValueError(f"unreadable uptime: {text!r}")
days = int(match.group("days") or 0)
hours, minutes, seconds = (int(match.group(k)) for k in ("h", "m", "s"))
return float(days * _SECONDS_PER_DAY + hours * 3600 + minutes * 60 + seconds)
def parse_version(text: str) -> VersionDict:
"""Facts from ``show version``; a field the device did not print is an error."""
fields = {m.group("key").strip(): m.group("value").strip() for m in _FIELD.finditer(text)}
try:
return {
"model": text.splitlines()[0].removesuffix(" Switch").strip(),
"hostname": fields["Hostname"],
"os_version": fields["Firmware"],
"serial_number": fields["Serial number"],
"uptime": parse_uptime(fields["Uptime"]),
}
except KeyError as exc:
raise ValueError(f"show version lacks {exc.args[0]}") from exc
View File
Whitespace-only changes.
+64
View File
@@ -0,0 +1,64 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "napalm-example"
version = "0.1.0"
description = "NAPALM driver for Example switches"
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
authors = [{ name = "Christian Manivong", email = "christian@manivong.de" }]
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Topic :: System :: Networking",
]
dependencies = [
"napalm>=5.0",
"napalm-device-types>=4.21",
]
[project.optional-dependencies]
dev = ["pytest>=8", "pytest-cov>=5", "mypy>=1.11", "ruff>=0.6"]
[project.urls]
Repository = "https://git.netork.io/NAPALM/napalm-example"
Issues = "https://git.netork.io/NAPALM/napalm-example/issues"
[project.entry-points."napalm.drivers"]
example = "napalm_example:ExampleDriver"
[tool.setuptools.packages.find]
include = ["napalm_example*"]
[tool.setuptools.package-data]
napalm_example = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.10"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
[[tool.mypy.overrides]]
module = ["napalm.*"]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.coverage.run]
source = ["napalm_example"]
[tool.coverage.report]
fail_under = 90
exclude_also = ["pragma: no cover - live I/O"]
@@ -0,0 +1,5 @@
Example 24 Switch
Hostname : sw-lab-01
Firmware : 1.0.0
Serial number : EX0000000001
Uptime : 3 days, 4:05:06
+66
View File
@@ -0,0 +1,66 @@
"""The driver with its transport replaced: what it sends, what it returns."""
from __future__ import annotations
import pathlib
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_example import ExampleDriver
FIXTURES = pathlib.Path(__file__).parent / "fixtures"
class FakeTransport:
def __init__(self, answers: dict[str, str]) -> None:
self.answers = answers
self.sent: list[str] = []
self.closed = False
def command(self, line: str) -> str:
self.sent.append(line)
return self.answers[line]
def close(self) -> None:
self.closed = True
@pytest.fixture
def driver() -> ExampleDriver:
return ExampleDriver("192.0.2.10", "admin", "secret")
def test_get_facts(driver: ExampleDriver) -> None:
show_version = (FIXTURES / "example24-1.0.0-show-version.txt").read_text()
driver.transport = FakeTransport({"show version": show_version})
facts = driver.get_facts()
assert facts["vendor"] == "Example"
assert facts["hostname"] == "sw-lab-01"
assert facts["fqdn"] == "sw-lab-01"
assert facts["interface_list"] == []
assert facts["uptime"] == 273906.0
def test_a_getter_before_open_raises(driver: ExampleDriver) -> None:
with pytest.raises(ConnectionException):
driver.get_facts()
def test_close_closes_the_transport_once(driver: ExampleDriver) -> None:
transport = FakeTransport({})
driver.transport = transport
driver.close()
driver.close()
assert transport.closed
assert driver.transport is None
def test_the_driver_is_registered_under_its_name() -> None:
from napalm import get_network_driver
assert get_network_driver("example") is ExampleDriver
+41
View File
@@ -0,0 +1,41 @@
"""Parsers against recorded device output."""
from __future__ import annotations
import pathlib
import pytest
from napalm_example.parsers import parse_uptime, parse_version
FIXTURES = pathlib.Path(__file__).parent / "fixtures"
def test_version_output_becomes_facts() -> None:
text = (FIXTURES / "example24-1.0.0-show-version.txt").read_text()
assert parse_version(text) == {
"model": "Example 24",
"hostname": "sw-lab-01",
"os_version": "1.0.0",
"serial_number": "EX0000000001",
"uptime": 273906.0,
}
def test_a_missing_field_is_an_error_not_an_empty_value() -> None:
with pytest.raises(ValueError, match="Serial number"):
parse_version("Example 24 Switch\nHostname : a\nFirmware : 1\nUptime : 0:00:01\n")
@pytest.mark.parametrize(
("text", "seconds"),
[("0:00:01", 1.0), ("1 day, 0:00:00", 86400.0), ("3 days, 4:05:06", 273906.0)],
)
def test_uptime(text: str, seconds: float) -> None:
assert parse_uptime(text) == seconds
def test_an_unreadable_uptime_is_an_error() -> None:
with pytest.raises(ValueError, match="uptime"):
parse_uptime("soon")