xref: /aosp_15_r20/external/pigweed/pw_presubmit/py/pw_presubmit/json_check.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2023 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""JSON validity check."""
15
16import json
17
18from . import presubmit, presubmit_context
19
20
21@presubmit.filter_paths(endswith=('.json',))
22@presubmit.check(name='json_check')
23def presubmit_check(ctx: presubmit_context.PresubmitContext):
24    """Presubmit check that ensures JSON files are valid."""
25
26    ctx.paths = presubmit_context.apply_exclusions(ctx)
27
28    for path in ctx.paths:
29        with path.open('r') as ins:
30            try:
31                json.load(ins)
32            except json.decoder.JSONDecodeError as exc:
33                intro_line = f'failed to parse {path.relative_to(ctx.root)}'
34                with ctx.failure_summary_log.open('w') as outs:
35                    print(intro_line, file=outs)
36                    print(exc, file=outs)
37                ctx.fail(intro_line)
38                ctx.fail(str(exc))
39