|
| 1 | +import argparse |
| 2 | +import json |
| 3 | +import sys |
| 4 | + |
| 5 | + |
| 6 | +def main(): |
| 7 | + # Create the argument parser |
| 8 | + parser = argparse.ArgumentParser(description="Validate an HED BIDS dataset.") |
| 9 | + |
| 10 | + # Positional argument for the dataset path |
| 11 | + parser.add_argument("dataset_path", help="Path to the dataset directory") |
| 12 | + |
| 13 | + # Optional argument for the format |
| 14 | + parser.add_argument("-f", "--format", choices=["text", "json", "json_pp"], default="text", |
| 15 | + help="Output format: 'text' (default) or 'json' ('json_pp' for pretty-printed json)") |
| 16 | + |
| 17 | + # Optional argument for the output file |
| 18 | + parser.add_argument("-o", "--output-file", help="File to save the output. If not provided, output is printed to the screen") |
| 19 | + |
| 20 | + # Optional flag to check for warnings |
| 21 | + parser.add_argument("--check-for-warnings", action="store_true", |
| 22 | + help="Enable checking for warnings during validation") |
| 23 | + |
| 24 | + # Parse the arguments |
| 25 | + args = parser.parse_args() |
| 26 | + |
| 27 | + issue_list = validate_dataset(args) |
| 28 | + |
| 29 | + # Return 1 if there are issues, 0 otherwise |
| 30 | + return int(bool(issue_list)) |
| 31 | + |
| 32 | + |
| 33 | +def validate_dataset(args): |
| 34 | + # Delayed imports to speed up --help |
| 35 | + from hed.errors import get_printable_issue_string |
| 36 | + from hed.tools import BidsDataset |
| 37 | + from hed import _version as vr |
| 38 | + |
| 39 | + # Validate the dataset |
| 40 | + bids = BidsDataset(args.dataset_path) |
| 41 | + issue_list = bids.validate(check_for_warnings=args.check_for_warnings) |
| 42 | + # Output based on format |
| 43 | + if args.format in ("json", "json_pp"): |
| 44 | + kw = {"indent": 4} if args.format == "json_pp" else {} |
| 45 | + output = json.dumps( |
| 46 | + { |
| 47 | + "issues": issue_list, |
| 48 | + "hedtools_version": str(vr.get_versions()) |
| 49 | + }, |
| 50 | + **kw) |
| 51 | + elif args.format == "json": |
| 52 | + output = json.dumps(issue_list) |
| 53 | + elif args.format == "text": |
| 54 | + # Print HEDTOOLS version |
| 55 | + print(f"Using HEDTOOLS version: {str(vr.get_versions())}") |
| 56 | + |
| 57 | + if issue_list: |
| 58 | + output = get_printable_issue_string(issue_list, "HED validation errors: ", skip_filename=False) |
| 59 | + # Print number of issues |
| 60 | + print(f"Number of issues: {len(issue_list)}") |
| 61 | + else: |
| 62 | + output = "No HED validation errors" |
| 63 | + else: |
| 64 | + raise ValueError(args.format) |
| 65 | + # Output to file or print to screen |
| 66 | + if args.output_file: |
| 67 | + with open(args.output_file, 'w') as fp: |
| 68 | + fp.write(output) |
| 69 | + else: |
| 70 | + print(output) |
| 71 | + return issue_list |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + sys.exit(main()) |
| 76 | + |
0 commit comments