#!/usr/bin/env python3 """ json_dir_validator.py - Validate all JSON files in a directory. Usage: python json_dir_validator.py Exits 0 if all JSON files are valid, 1 if any are invalid or missing. Outputs each file's status: "filename: VALID" or "filename: INVALID - error" """ import json import sys from pathlib import Path def validate_json_file(filepath): """Validate a JSON file. Returns (is_valid, error_message).""" try: with open(filepath, 'r') as f: content = f.read().strip() if not content: return False, "Empty file" json.loads(content) return True, None except json.JSONDecodeError as e: return False, str(e) except Exception as e: return False, str(e) def main(): if len(sys.argv) < 2: print("Usage: json_dir_validator.py ", file=sys.stderr) sys.exit(1) directory = Path(sys.argv[1]) if not directory.exists(): print(f"Error: Directory '{directory}' does not exist", file=sys.stderr) sys.exit(1) if not directory.is_dir(): print(f"Error: '{directory}' is not a directory", file=sys.stderr) sys.exit(1) json_files = sorted(directory.glob('*.json')) if not json_files: print(f"Warning: No JSON files found in {directory}") sys.exit(0) all_valid = True results = [] for json_file in json_files: is_valid, error = validate_json_file(json_file) results.append((json_file, is_valid, error)) if not is_valid: all_valid = False # Output results for filepath, is_valid, error in results: if is_valid: print(f"{filepath.name}: VALID") else: print(f"{filepath.name}: INVALID - {error}") sys.exit(0 if all_valid else 1) if __name__ == '__main__': main()