Skip to content

Commit d9b7965

Browse files
committed
Add NNCP validate to pre-commit
Run nmstatectl -q validate -- on all files named nncp.(yaml|yml) Assisted-By: calude-4-sonnet
1 parent 789f403 commit d9b7965

3 files changed

Lines changed: 75 additions & 0 deletions

File tree

.pre-commit-config.yaml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,17 @@ repos:
4040
hooks:
4141
- id: black
4242

43+
- repo: local
44+
hooks:
45+
- id: NNCP validate
46+
name: Check NNCP with nmstate validate
47+
entry: ./ci/nmstate_validate.py
48+
language: python
49+
additional_dependencies:
50+
- pyyaml
51+
files: nncp.(yaml|yml)$
52+
types: [file, yaml]
53+
4354
- repo: https://github.com/ansible/ansible-lint
4455
rev: v6.22.2
4556
hooks:

ci/nmstate_validate.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env python3
2+
3+
import subprocess
4+
import sys
5+
import yaml
6+
import shutil
7+
8+
9+
def get_nncp_yaml_documents(yaml_file):
10+
try:
11+
with open(yaml_file, "r") as f:
12+
documents = list(yaml.safe_load_all(f))
13+
except Exception as e:
14+
print(f"Error reading YAML file: {e}")
15+
sys.exit(1)
16+
17+
return documents
18+
19+
20+
def validate_nncp_documents(docs):
21+
# Process each document that has spec.desiredState
22+
for _idx, doc in enumerate(docs):
23+
if doc and "spec" in doc and "desiredState" in doc["spec"]:
24+
desired_state = doc["spec"]["desiredState"]
25+
26+
# Convert the desiredState back to YAML for nmstatectl
27+
content = yaml.dump(desired_state, default_flow_style=False)
28+
29+
# Validate with nmstatectl
30+
cmd = ["nmstatectl", "-q", "validate", "--"]
31+
try:
32+
subprocess.run(
33+
cmd, input=content, text=True, capture_output=True, check=True
34+
)
35+
except subprocess.CalledProcessError as e:
36+
print(f"Document {_idx}: Validation failed")
37+
if e.stderr:
38+
print(f"Error: {e.stderr.strip()}")
39+
sys.exit(1)
40+
except Exception as e:
41+
print(f"Document {_idx}: Error running nmstatectl - {e}")
42+
sys.exit(1)
43+
44+
45+
def main():
46+
print(sys.argv)
47+
if len(sys.argv) < 2:
48+
print("Usage: nmstate_validate.py <yaml_file> <yaml_file> ...")
49+
sys.exit(1)
50+
51+
# Check if nmstatectl is installed
52+
if not shutil.which("nmstatectl"):
53+
print("nmstatectl is not installed")
54+
sys.exit(0)
55+
56+
for yaml_file in sys.argv[1:]:
57+
print(f"Validating {yaml_file}")
58+
documents = get_nncp_yaml_documents(yaml_file)
59+
validate_nncp_documents(documents)
60+
61+
62+
if __name__ == "__main__":
63+
main()

ci/playbooks/pre-commit.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
name:
1111
- python3
1212
- python3-pip
13+
- nmstate
1314
state: present
1415
- name: Pip install
1516
ansible.builtin.pip:

0 commit comments

Comments
 (0)