53 lines
1.4 KiB
Python
53 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
"""JSON Validator - validates JSON files with proper exit codes.
|
|
Exit 0: Valid JSON
|
|
Exit 1: Invalid JSON or file not found
|
|
Exit 2: Usage error
|
|
"""
|
|
|
|
import sys
|
|
import json
|
|
from pathlib import Path
|
|
|
|
|
|
def validate_json_file(filepath: str) -> bool:
|
|
"""Validate a JSON file. Returns True if valid, False otherwise."""
|
|
try:
|
|
with open(filepath, 'r') as f:
|
|
json.load(f)
|
|
print(f"VALID: {filepath}")
|
|
return True
|
|
except json.JSONDecodeError as e:
|
|
print(f"INVALID: {filepath} - line {e.lineno}, column {e.colno}: {e.msg}", file=sys.stderr)
|
|
return False
|
|
except FileNotFoundError:
|
|
print(f"NOT FOUND: {filepath}", file=sys.stderr)
|
|
return False
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: json-validator.py <file-or-directory>", file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
paths = sys.argv[1:]
|
|
all_valid = True
|
|
|
|
for path in paths:
|
|
p = Path(path)
|
|
if p.is_dir():
|
|
for json_file in p.rglob("*.json"):
|
|
if not validate_json_file(str(json_file)):
|
|
all_valid = False
|
|
elif p.is_file():
|
|
if not validate_json_file(str(p)):
|
|
all_valid = False
|
|
else:
|
|
print(f"NOT FOUND: {path}", file=sys.stderr)
|
|
all_valid = False
|
|
|
|
sys.exit(0 if all_valid else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |