Skip to content
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

Allow to override source code header #19

Merged
merged 1 commit into from
May 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions pydantic2zod/_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,19 @@ def __init__(
self,
model_rename_rules: dict[str, str] | None = None,
modify_models: Callable[[list[ClassDecl]], list[ClassDecl]] | None = None,
gen_header: Callable[[], str] | None = None,
) -> None:
self._model_rename_rules = model_rename_rules or {}
self._modify_models = modify_models or (lambda m: m)
self._gen_header = gen_header or (lambda: "")

def to_zod(self, pydantic_models: list[ClassDecl]) -> str:
self._apply_model_rename_rules(pydantic_models)
models = self._modify_models(pydantic_models)
_warn_about_duplicate_models(models)

code = Lines()
self._gen_header(code)
code.add(self._gen_header())

for cls in models:
if not cls.name.startswith("_"):
Expand All @@ -52,16 +54,6 @@ def to_zod(self, pydantic_models: list[ClassDecl]) -> str:

return str(code)

def _gen_header(self, code: "Lines") -> None:
header = """
/**
* NOTE: automatically generated by the pydantic2zod compiler.
*/

import { z } from "zod";
"""
code.add(header)

def _apply_model_rename_rules(self, pydantic_models: list[ClassDecl]) -> None:
for model in pydantic_models:
if new_name := self._model_rename_rules.get(model.full_path):
Expand Down
14 changes: 13 additions & 1 deletion pydantic2zod/_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ class Compiler:
"""

def __init__(self) -> None:
self._codegen = Codegen(self.MODEL_RENAME_RULES, self._modify_models)
self._codegen = Codegen(
self.MODEL_RENAME_RULES, self._modify_models, self._gen_header
)
self._pydantic_models: list[ClassDecl] = []

def parse(self, module_name: str) -> Self:
Expand All @@ -52,3 +54,13 @@ def _modify_models(self, pydantic_models: list[ClassDecl]) -> list[ClassDecl]:
e.g. remove default field values.
"""
return pydantic_models

def _gen_header(self) -> str:
"""Override in case you want to add some header to the generated code."""
return """
/**
* NOTE: automatically generated by the pydantic2zod compiler.
*/

import { z } from "zod";
"""