-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: validate schemas using pydantic_schemaorg (#69)
Validates front matter as a pydantic_schemaorg schema, printing warnings when schema validation errors are found.
- Loading branch information
1 parent
ac36f48
commit 91702a2
Showing
6 changed files
with
448 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import importlib | ||
from collections.abc import MutableMapping | ||
from pathlib import Path | ||
|
||
from pydantic.v1 import ValidationError | ||
from rich.console import Console | ||
|
||
from blurry.settings import SETTINGS | ||
from blurry.settings import update_settings | ||
|
||
|
||
class Config: | ||
extra = "forbid" | ||
|
||
|
||
def validate_front_matter_as_schema( | ||
path: Path, front_matter: MutableMapping, console: Console | ||
): | ||
""" | ||
Validates schema data using pydantic_schemaorg, disallowing extra fields | ||
""" | ||
update_settings() | ||
|
||
schema_type = front_matter["@type"] | ||
|
||
# Import pydantic_schemaorg model | ||
try: | ||
pydantic_schemaorg_model_module = importlib.import_module( | ||
f"pydantic_schemaorg.{schema_type}" | ||
) | ||
except ModuleNotFoundError: | ||
console.print( | ||
f"{path}: Could not find Schema type for {schema_type}. Skipping." | ||
) | ||
return | ||
|
||
schema_model = getattr(pydantic_schemaorg_model_module, schema_type) | ||
|
||
# Create new Pydantic model that forbids extra fields | ||
class NonExtraSchemaModel(schema_model, extra="forbid"): # type: ignore | ||
pass | ||
|
||
# Validate model and print errors | ||
try: | ||
non_schema_variable_prefix = SETTINGS["FRONTMATTER_NON_SCHEMA_VARIABLE_PREFIX"] | ||
schema_front_matter = { | ||
k: v | ||
for k, v in front_matter.items() | ||
if not k.startswith(non_schema_variable_prefix) | ||
} | ||
NonExtraSchemaModel(**schema_front_matter) | ||
except ValidationError as e: | ||
for error in e.errors(): | ||
msg = error["msg"] | ||
loc = error["loc"] | ||
console.print( | ||
f"{path}: {schema_type} schema validation error: {msg}: {loc}" | ||
) |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.