Skip to content

Commit 6ffe9ee

Browse files
committed
Initial version
0 parents  commit 6ffe9ee

10 files changed

+233
-0
lines changed

Diff for: .flake8

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[flake8]
2+
exclude = .git,.tox,__pycache__,.eggs,dist,.venv*,docs,build,_build
3+
# we enforce 80 char width with `black` "loosely", so flake8 should be set to
4+
# not fail on up to 90 chars of width
5+
max-line-length = 90
6+
7+
# based on the flake8 conf for `black` itself:
8+
# https://github.com/ambv/black/blob/master/.flake8
9+
#
10+
# W503/W504 conflict, black causes E203
11+
ignore = W503,W504,E203,

Diff for: .gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.venv
2+
*.egg-info
3+
__pycache__

Diff for: .pre-commit-config.yaml

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
repos:
2+
- repo: https://github.com/pre-commit/pre-commit-hooks.git
3+
rev: v3.1.0
4+
hooks:
5+
- id: check-merge-conflict
6+
- id: trailing-whitespace
7+
- repo: https://github.com/python/black
8+
rev: 20.8b1
9+
hooks:
10+
- id: black
11+
name: "Autoformat python files"
12+
types: [python]
13+
language_version: python3
14+
- repo: https://gitlab.com/pycqa/flake8
15+
rev: 3.8.4
16+
hooks:
17+
- id: flake8
18+
name: "Lint python files"
19+
types: [python]
20+
language_version: python3
21+
additional_dependencies: ['flake8-bugbear==20.11.1']
22+
- repo: https://github.com/timothycrosley/isort
23+
rev: 5.6.4
24+
hooks:
25+
- id: isort
26+
name: "Sort python imports"
27+
types: [python]
28+
language_version: python3

Diff for: .pre-commit-hooks.yaml

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
- id: check-jsonschema
2+
name: Validate files with jsonschema
3+
entry: check-jsonschema
4+
language: python
5+
types_or: [json,yaml]

Diff for: LICENSE

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Copyright 2021, Stephen Rosen
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://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,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.

Diff for: README.md

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# check-jsonschema
2+
3+
A pre-commit hook for checking files against a JSONSchema.
4+
The schema may be specified as a local or remote (HTTP or HTTPS) file.
5+
6+
Remote files are automatically downloaded and cached if possible.
7+
8+
## Example Usage: Validate GitHub Workflows with Schemastore
9+
10+
Add this hook to your pre-commit config:
11+
12+
```yaml
13+
- repo: https://github.com/sirosen/check-jsonschema
14+
rev: 0.1.0
15+
hooks:
16+
- id: check-workflows
17+
name: "Lint GitHub Workflows"
18+
language: python
19+
files: ^\.github/workflows/.*\.yaml$
20+
args: ["--schemafile", "https://json.schemastore.org/github-workflow"]
21+
```

Diff for: check_jsonschema/__init__.py

Whitespace-only changes.

Diff for: check_jsonschema/cli.py

+115
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import argparse
2+
import contextlib
3+
import json
4+
import os
5+
import platform
6+
import time
7+
import urllib.request
8+
9+
from identify import identify
10+
import jsonschema
11+
import ruamel.yaml
12+
13+
yaml = ruamel.yaml.YAML(typ="safe")
14+
15+
16+
sysname = platform.system()
17+
# on windows, try to get the appdata env var
18+
# this *could* result in CACHE_DIR=None, which is fine, just skip caching in
19+
# that case
20+
if sysname == "Windows":
21+
CACHE_DIR = os.getenv("LOCALAPPDATA", os.getenv("APPDATA"))
22+
# macOS -> app support dir
23+
elif sysname == "Darwin":
24+
CACHE_DIR = os.path.expanduser("~/Library/Application Support")
25+
# default for unknown platforms, namely linux behavior
26+
# use XDG env var and default to ~/.cache/
27+
else:
28+
CACHE_DIR = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache/"))
29+
30+
if CACHE_DIR:
31+
CACHE_DIR = os.path.join(CACHE_DIR, "jsonschema_validate")
32+
33+
34+
@contextlib.contextmanager
35+
def cached_open(file_url, filename):
36+
if not CACHE_DIR:
37+
with urllib.request.urlopen(file_url) as fp:
38+
yield fp
39+
else:
40+
try:
41+
os.makedirs(CACHE_DIR)
42+
except FileExistsError:
43+
pass
44+
45+
if not filename:
46+
filename = file_url.split("/")[-1]
47+
dest = os.path.join(CACHE_DIR, filename)
48+
49+
# connect, but don't read yet
50+
conn = urllib.request.urlopen(file_url)
51+
52+
# download and cache to disk based on the mtime of the local file if it
53+
# exists (check mtime before download for speed) or just download if missing
54+
do_download = True
55+
if os.path.exists(dest):
56+
# get both timestamps as epoch times
57+
local_mtime = os.path.getmtime(dest)
58+
remote_mtime = time.mktime(
59+
time.strptime(conn.headers["last-modified"], "%a, %d %b %Y %H:%M:%S %Z")
60+
)
61+
do_download = local_mtime < remote_mtime
62+
if do_download:
63+
with open(dest, "wb") as fp:
64+
fp.write(conn.read())
65+
66+
conn.close()
67+
68+
with open(dest, "r") as fp:
69+
yield fp
70+
71+
72+
def main():
73+
parser = argparse.ArgumentParser()
74+
parser.add_argument(
75+
"--schemafile",
76+
required=True,
77+
help=(
78+
"REQUIRED. "
79+
"The path to a file containing the jsonschema to use or an "
80+
"HTTP(S) URI for the schema. If a remote file is used, "
81+
"it will be downloaded and cached locally based on mtime."
82+
),
83+
)
84+
parser.add_argument(
85+
"--cache-filename",
86+
help=(
87+
"The name to use for caching a remote schema. "
88+
"Defaults to the last slash-delimited part of the URI."
89+
),
90+
)
91+
parser.add_argument("instancefiles", nargs="+", help="JSON or YAML files to check.")
92+
args = parser.parse_args()
93+
94+
if args.schemafile.startswith("https://") or args.schemafile.startswith("http://"):
95+
with cached_open(args.schemafile, args.cache_filename) as fp:
96+
schema = json.load(fp)
97+
else:
98+
with open(args.schemafile) as f:
99+
schema = json.load(f)
100+
101+
for instancefile in args.instancefiles:
102+
tags = identify.tags_from_path(instancefile)
103+
if "yaml" in tags:
104+
loader = yaml.load
105+
elif "json" in tags:
106+
loader = json.load
107+
else:
108+
raise ValueError(
109+
f"cannot check {instancefile} as it is neither yaml nor json"
110+
)
111+
with open(instancefile) as f:
112+
doc = loader(f)
113+
114+
jsonschema.validate(instance=doc, schema=schema)
115+
print("ok -- validation done")

Diff for: setup.cfg

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
[metadata]
2+
name = check-jsonschema
3+
version = 0.1.0
4+
description = A pre-commit hook for validating files against jsonschemas.
5+
long_description = file: README.md
6+
long_description_content_type = text/markdown
7+
url = https://github.com/sirosen/check-jsonschema
8+
author = Stephen Rosen
9+
author_email = [email protected]
10+
11+
classifiers =
12+
Development Status :: 3 - Alpha
13+
Intended Audience :: Developers
14+
License :: OSI Approved :: Apache Software License
15+
Programming Language :: Python :: 3
16+
17+
[options]
18+
python_requires = >=3.6.2
19+
install_requires =
20+
ruamel.yaml==0.16.12
21+
jsonschema<4.0
22+
identify<2.0
23+
packages = find:
24+
25+
[options.entry_points]
26+
console_scripts =
27+
check-jsonschema = check_jsonschema.cli:main
28+
29+
[bdist_wheel]
30+
universal = True
31+
32+
33+
[isort]
34+
profile = black

Diff for: setup.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from setuptools import setup
2+
3+
setup()

0 commit comments

Comments
 (0)