Skip to content

Commit 8b7be75

Browse files
committed
Properly handle json and yml decoding errors.
1 parent a0a40cd commit 8b7be75

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

scripts/guideline_recategorization/recategorize.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import jsonpath_ng.ext
1010
import jsonpointer
1111
import yaml
12+
import yaml.parser
1213
import re
1314
import jsonpatch
1415
from functools import reduce
@@ -111,14 +112,20 @@ def resolve_path(path : Path) -> Optional[Path]:
111112
resolved_schema_path = resolve_path(path.resolve())
112113
if resolved_schema_path:
113114
with resolved_schema_path.open(mode='r') as fp:
114-
return json.load(fp)
115+
try:
116+
return json.load(fp)
117+
except json.decoder.JSONDecodeError as e:
118+
print_failure(f"Failed to load schema with error \"{e.msg}\" at {resolved_schema_path}:{e.lineno}:{e.colno}!")
115119
else:
116120
return None
117121

118122
def load_config(path: Path) -> Optional[Mapping[str, Any]]:
119123
if path.is_file():
120124
with path.open('r') as fp:
121-
return yaml.safe_load(fp)
125+
try:
126+
return yaml.safe_load(fp)
127+
except yaml.parser.ParserError as e:
128+
print_failure(f"Failed to load config with error \"{e.problem}\" at {path}:{e.problem_mark.line}:{e.problem_mark.column}!")
122129
else:
123130
return None
124131

@@ -137,17 +144,23 @@ def main(args: argparse.Namespace):
137144
if not coding_standards_schema:
138145
print_failure("Failed to load Coding Standards schema!")
139146

147+
if not '$id' in coding_standards_schema:
148+
print_failure(f"Missing id for Coding Standards schema: '{args.coding_standards_schema_file}'")
149+
140150
if coding_standards_schema['$id'] != CODING_STANDARDS_SCHEMA_ID:
141151
print_failure(f"Unexpected id for Coding Standards schema, expecting '{CODING_STANDARDS_SCHEMA_ID}'!")
142152

143153
sarif_schema = load_schema(args.sarif_schema_file, 'sarif-schema-2.1.0.json')
144154
if not sarif_schema:
145-
print("Failed to load Sarif schema!", file=sys.stderr)
155+
print(f"Failed to load Sarif schema: '{args.sarif_schema_file}'!", file=sys.stderr)
146156
sys.exit(1)
147157
sarif_schema = cast(Mapping[str, Any], sarif_schema)
148158

159+
if not '$id' in sarif_schema:
160+
print_failure(f"Missing id for Sarif schema: '{args.sarif_schema_file}'")
161+
149162
if sarif_schema['$id'] != SARIF_SCHEMA_ID:
150-
print_failure(f"Unexpected id for Sarif schema, expecting '{SARIF_SCHEMA_ID}'!")
163+
print_failure(f"Unexpected id for Sarif schema: '{args.sarif_schema_file}, expecting '{SARIF_SCHEMA_ID}'!")
151164

152165
coding_standards_config = load_config(args.coding_standards_config_file)
153166
if not coding_standards_schema:

0 commit comments

Comments
 (0)