Files
troupe-standup/wizard-work/spark/json_sha256_validator.py
T

60 lines
1.5 KiB
Python

#!/usr/bin/env python3
"""Simple JSON validator that generates SHA256 checksums for verification."""
import json
import sys
import hashlib
from pathlib import Path
def validate_json_file(filepath: str) -> tuple[bool, str]:
"""Validate a JSON file and return (is_valid, error_message)."""
try:
with open(filepath, 'r') as f:
json.load(f)
return True, ""
except json.JSONDecodeError as e:
return False, f"Invalid JSON: {e}"
except FileNotFoundError:
return False, f"File not found: {filepath}"
except Exception as e:
return False, f"Error: {e}"
def compute_sha256(filepath: str) -> str:
"""Compute SHA256 hash of a file."""
sha256_hash = hashlib.sha256()
with open(filepath, 'rb') as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def main():
if len(sys.argv) < 2:
print("Usage: json_sha256_validator.py <file1.json> [file2.json ...]")
sys.exit(1)
results = []
all_valid = True
for filepath in sys.argv[1:]:
is_valid, error = validate_json_file(filepath)
if is_valid:
checksum = compute_sha256(filepath)
results.append(f"VALID {filepath} SHA256={checksum}")
else:
results.append(f"INVALID {filepath} ERROR={error}")
all_valid = False
for r in results:
print(r)
if all_valid:
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()