|
| 1 | +import json |
| 2 | +import os |
| 3 | + |
| 4 | +import yaml |
| 5 | +from jsonschema import validate, ValidationError |
| 6 | +import sys |
| 7 | + |
| 8 | +FEATURES_FILE_NAME='features.yml' |
| 9 | + |
| 10 | +def load_yaml_file(file_path: str): |
| 11 | + try: |
| 12 | + with open(file_path, 'r') as file: |
| 13 | + return yaml.safe_load(file) |
| 14 | + except yaml.YAMLError as e: |
| 15 | + print(f"Error parsing YAML file: {e}") |
| 16 | + sys.exit(1) |
| 17 | + except FileNotFoundError: |
| 18 | + print(f"YAML file not found: {file_path}") |
| 19 | + sys.exit(1) |
| 20 | + |
| 21 | +def load_json_file(file_path: str): |
| 22 | + try: |
| 23 | + with open(file_path, 'r') as file: |
| 24 | + return json.load(file) |
| 25 | + except json.JSONDecodeError as e: |
| 26 | + print(f"Failed to parse JSON schema file: {e}") |
| 27 | + sys.exit(1) |
| 28 | + except FileNotFoundError: |
| 29 | + print(f"Json schema file not found: {file_path}") |
| 30 | + sys.exit(1) |
| 31 | + |
| 32 | +def validate_yaml_against_schema(yaml_data: str, json_schema: str, file_path: str) -> bool: |
| 33 | + try: |
| 34 | + validate(instance=yaml_data, schema=json_schema) |
| 35 | + print(f"Successful validation of file: {file_path}") |
| 36 | + return True |
| 37 | + except ValidationError as e: |
| 38 | + sys.stdout.write(f"::error file={file_path},title=Validation has failed at path {' -> '.join(str(x) for x in e.path)}::{e.message}") |
| 39 | + return False |
| 40 | + |
| 41 | +def main(): |
| 42 | + # Detect changed features files |
| 43 | + comma_separated_changed_files = os.getenv('ALL_CHANGED_FILES') |
| 44 | + if not comma_separated_changed_files: |
| 45 | + print("Environment variable ALL_CHANGED_FILES is not set. Skipping validation.") |
| 46 | + sys.exit(1) |
| 47 | + |
| 48 | + changed_files = comma_separated_changed_files.split(',') |
| 49 | + changed_features_files = [path for path in changed_files if path.lower().endswith(FEATURES_FILE_NAME)] |
| 50 | + print(f'Changed features files: {",".join(changed_features_files)}') |
| 51 | + |
| 52 | + if len(changed_features_files) == 0: |
| 53 | + print('No feature file was changed. Skipping validation.') |
| 54 | + sys.exit(0) |
| 55 | + |
| 56 | + features_schema_path = os.getenv('FEATURES_JSON_SCHEMA', 'features_schema.json') |
| 57 | + features_schema = load_json_file(features_schema_path) |
| 58 | + print(f'Features schema file was loaded: {features_schema_path}') |
| 59 | + |
| 60 | + # validate schemas |
| 61 | + all_valid = True |
| 62 | + for file_path in changed_features_files: |
| 63 | + features_file = load_yaml_file(file_path) |
| 64 | + if not validate_yaml_against_schema(features_file, features_schema, file_path): |
| 65 | + all_valid = False |
| 66 | + sys.exit(0 if all_valid else 1) |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + main() |
0 commit comments