-
Notifications
You must be signed in to change notification settings - Fork 68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Schema for Calibanconfig #37
Changes from all commits
fbbb4e9
8170450
309d380
a07ef6b
76fe3e0
bd2e414
88f675e
f613c11
3329f46
36ff6b1
2d89a20
f317b23
00835e4
c1f9aa8
baa3eeb
bf99232
d67ae41
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,6 +25,7 @@ | |
|
||
import caliban.util as u | ||
import caliban.util.fs as ufs | ||
import schema as s | ||
|
||
t = Terminal() | ||
|
||
|
@@ -39,6 +40,25 @@ def expand_args(items: Dict[str, str]) -> List[str]: | |
return list(it.chain.from_iterable(pairs)) | ||
|
||
|
||
def argparse_schema(schema): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Typing annotations would be helpful for me here, as I'm new to schema. SchemaType = Union[s.And, s.Or, s.Regex, s.Use, s.Schema, s.Const] |
||
"""Wrapper that performs validation and converts SchemaErrors into | ||
ArgumentTypeErrors for better argument error reporting. | ||
|
||
""" | ||
|
||
def check(x): | ||
try: | ||
return schema.validate(x) | ||
except s.SchemaError as e: | ||
raise argparse.ArgumentTypeError(e.code) from None | ||
|
||
return check | ||
|
||
|
||
# TODO: Now that we use schema, validated_package and parse_kv_pair should be | ||
# converted to schema instances. | ||
|
||
|
||
def validated_package(path: str) -> u.Package: | ||
"""similar to generate_package but runs argparse validation on packages that | ||
don't actually exist in the filesystem. | ||
|
@@ -89,26 +109,3 @@ def is_key(k: Optional[str]) -> bool: | |
|
||
""" | ||
return k is not None and len(k) > 0 and k[0] == "-" | ||
|
||
|
||
def validated_directory(path: str) -> str: | ||
"""This validates that the supplied directory exists locally. | ||
|
||
""" | ||
if not os.path.isdir(path): | ||
raise argparse.ArgumentTypeError( | ||
"""Directory '{}' doesn't exist in this directory. Check yourself!""". | ||
format(path)) | ||
return path | ||
|
||
|
||
def validated_file(path: str) -> str: | ||
"""This validates that the supplied file exists. Tilde expansion is supported. | ||
|
||
""" | ||
expanded = os.path.expanduser(path) | ||
if not os.path.isfile(expanded): | ||
raise argparse.ArgumentTypeError( | ||
"""File '{}' isn't a valid file on your system. Try again!""".format( | ||
path)) | ||
return path |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
#!/usr/bin/python | ||
# | ||
# Copyright 2020 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
""" | ||
Useful shared schemas. | ||
""" | ||
import os | ||
import sys | ||
from contextlib import contextmanager | ||
from typing import Optional | ||
|
||
import commentjson | ||
|
||
import caliban.util as u | ||
import schema as s | ||
|
||
|
||
class FatalSchemaError(Exception): | ||
"""Wrapper for an exception that can bubble itself up to the top level of the | ||
program.""" | ||
|
||
def __init__(self, message, context): | ||
self.message = message | ||
self.context = context | ||
super().__init__(self.message) | ||
|
||
|
||
@contextmanager | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great, context managers are very nice. |
||
def error_schema(context: Optional[str] = None): | ||
"""Wrap functions that check schemas in this context manager to throw an | ||
appropriate error with a nice message. | ||
|
||
""" | ||
prefix = "" | ||
if context is not None: | ||
prefix = f"\nValidation error while parsing {context}:\n" | ||
|
||
try: | ||
yield | ||
except s.SchemaError as e: | ||
raise FatalSchemaError(e.code, prefix) | ||
|
||
|
||
@contextmanager | ||
def fatal_errors(): | ||
"""Context manager meant to wrap an entire program and present schema errors in | ||
an easy-to-read way. | ||
|
||
""" | ||
try: | ||
yield | ||
except FatalSchemaError as e: | ||
u.err(f"{e.context}\n{e.message}\n\n") | ||
sys.exit(1) | ||
except s.SchemaError as e: | ||
u.err(f"\n{e.code}\n\n") | ||
sys.exit(1) | ||
|
||
|
||
def load_json(path): | ||
with open(path) as f: | ||
return commentjson.load(f) | ||
|
||
|
||
# TODO Once a release with this patch happens: | ||
# https://github.com/keleshev/schema/pull/238,, Change `Or` to `Schema`. This | ||
# problem only occurs for callable validators. | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The composition here is quite nice. |
||
Directory = s.Or( | ||
os.path.isdir, | ||
False, | ||
error="""Directory '{}' doesn't exist in this directory. Check yourself!""") | ||
|
||
File = s.Or(lambda path: os.path.isfile(os.path.expanduser(path)), | ||
False, | ||
error="""File '{}' isn't a valid file on your system. Try again!""") | ||
|
||
Json = s.And( | ||
File, | ||
s.Use(load_json, | ||
error="""File '{}' doesn't seem to contain valid JSON. Try again!""")) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typing annotations would be good here, just given the ambiguity of the argument.