-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.py
More file actions
163 lines (126 loc) · 4.82 KB
/
validator.py
File metadata and controls
163 lines (126 loc) · 4.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#!/usr/bin/env python3
"""
Configuration Validator using JSON Schema
"""
import sys
import yaml
import json
from jsonschema import validate, ValidationError, SchemaError
from pathlib import Path
class ConfigValidator:
"""Validate generated configurations against schemas."""
def __init__(self, schema_dir='schemas'):
"""
Initialize the validator.
Args:
schema_dir: Directory containing JSON schemas
"""
self.schema_dir = schema_dir
self.schemas = {}
def load_schema(self, schema_name):
"""
Load a JSON schema file.
Args:
schema_name: Name of the schema file
Returns:
Dictionary containing the schema
"""
if schema_name in self.schemas:
return self.schemas[schema_name]
schema_path = Path(self.schema_dir) / schema_name
if not schema_path.is_file():
raise FileNotFoundError(f"Schema file not found: {schema_path}")
try:
with open(schema_path, 'r', encoding='utf-8') as f:
schema = json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in schema file '{schema_path}': {e}")
self.schemas[schema_name] = schema
return schema
def validate_yaml_config(self, config_file, schema_name):
"""
Validate a YAML configuration file against a schema.
Args:
config_file: Path to YAML configuration file
schema_name: Name of the schema to validate against
Returns:
Tuple (is_valid: bool, errors: list)
"""
errors = []
try:
with open(config_file, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
schema = self.load_schema(schema_name)
validate(instance=config, schema=schema)
return True, []
except FileNotFoundError as e:
return False, [str(e)]
except yaml.YAMLError as e:
return False, [f"Invalid YAML in config file '{config_file}': {e}"]
except ValidationError as e:
path = ".".join(str(p) for p in e.path) if e.path else "root"
return False, [f"Validation error at '{path}': {e.message}"]
except SchemaError as e:
return False, [f"Invalid schema '{schema_name}': {e.message}"]
except Exception as e:
return False, [str(e)]
def validate_nginx_config(self, config_file):
"""
Perform basic syntax validation on Nginx config.
Args:
config_file: Path to Nginx configuration file
Returns:
Tuple (is_valid: bool, message: str)
"""
try:
with open(config_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
except FileNotFoundError:
return False, f"Config file not found: {config_file}"
content = "".join(lines)
open_braces = content.count("{")
close_braces = content.count("}")
if open_braces != close_braces:
return False, f"Unbalanced curly braces: '{{'={open_braces}, '}}'={close_braces}"
if "server {" not in content:
return False, "Missing 'server' block"
if "location" not in content:
return False, "Missing 'location' block"
for lineno, raw_line in enumerate(lines, start=1):
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.endswith("{") or line == "}" or line.endswith("}"):
continue
if ";" not in line:
return False, f"Missing semicolon on line {lineno}: {line}"
return True, "Nginx configuration passed basic syntax validation"
def main():
"""Main execution function."""
if len(sys.argv) < 3:
print("Usage: python3 validator.py <config_file> <schema_name>")
print("Example: python3 validator.py configs/app_config.yaml app_config_schema.json")
sys.exit(1)
config_file = sys.argv[1]
schema_name = sys.argv[2]
validator = ConfigValidator()
if schema_name.lower() == "nginx":
is_valid, message = validator.validate_nginx_config(config_file)
if is_valid:
print(f"VALID: {message}")
sys.exit(0)
else:
print(f"INVALID: {message}")
sys.exit(1)
else:
is_valid, errors = validator.validate_yaml_config(config_file, schema_name)
if is_valid:
print(f"VALID: {config_file} matches schema {schema_name}")
sys.exit(0)
else:
print(f"INVALID: {config_file} does not match schema {schema_name}")
for error in errors:
print(f" - {error}")
sys.exit(1)
if __name__ == '__main__':
main()