Skip to content

Commit

Permalink
add write schema and project to folder
Browse files Browse the repository at this point in the history
  • Loading branch information
jhnnsrs committed Nov 12, 2024
1 parent 9c9ea25 commit 178673a
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 18 deletions.
16 changes: 12 additions & 4 deletions turms/cli/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from enum import Enum
import os
from turms.run import generate, write_code_to_file
from typing import Dict
from turms.config import GraphQLProject
from turms.run import generate, write_code_to_file, write_project, write_schema_to_file
from rich import get_console
from rich.panel import Panel
from rich.live import Live
Expand Down Expand Up @@ -63,7 +65,7 @@ class TurmsOptions(str, Enum):
"""


def generate_projects(projects, title="Turms"):
def generate_projects(projects: Dict[str, GraphQLProject], title="Turms"):
generation_message = f"Generating the {'.'.join(projects.keys())} projects. This may take a while...\n"

tree = Tree("Generating projects", style="bold green")
Expand All @@ -90,7 +92,7 @@ def log(message, level):
project_tree.add(Tree(message, style="yellow"))

try:
generated_code = generate(project, log=log)
generated_code, schema = generate(project, log=log)

project_tree.label = f"{key} ✔️"
live.update(panel)
Expand All @@ -101,6 +103,12 @@ def log(message, level):
project.extensions.turms.generated_name,
)

if project.extensions.turms.dump_schema:
write_schema_to_file(schema, project.extensions.turms.out_dir, project.extensions.turms.schema_name)

if project.extensions.turms.dump_configuration:
write_project(project, project.extensions.turms.out_dir, project.extensions.turms.configuration_name)

except Exception as e:
project_tree.style = "red"
project_tree.label = f"{key} 💥"
Expand Down Expand Up @@ -190,7 +198,7 @@ def watch_projects(projects, title="Turms"): # pragma: no cover
tree.style = "blue"
live.update(panel)

generated_code = generate(
generated_code, schema = generate(
project,
)

Expand Down
19 changes: 18 additions & 1 deletion turms/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ class GeneratorConfig(BaseSettings):
"""The domain of the GraphQL API ( will be set as a config variable)"""
out_dir: str = "api"
"""The output directory for the generated models"""
dump_configuration: bool = False
configuration_name: str = "project.json"
dump_schema: bool = False
schema_name: str = "schema.graphql"
generated_name: str = "schema.py"
""" The name of the generated file within the output directory"""
documents: Optional[str] = None
Expand Down Expand Up @@ -249,7 +253,7 @@ class GeneratorConfig(BaseSettings):
skip_forwards: bool = False
"""Skip generating automatic forwards reference for the generated models"""

additional_bases: Dict[str, List[PythonType]] = Field(
additional_bases: Dict[str, List[str]] = Field(
default_factory=dict,
description="Additional bases for the generated models as map of GraphQL Type to importable base class (e.g. module.package.Class)",
)
Expand Down Expand Up @@ -294,6 +298,19 @@ def validate_importable(cls, v):
raise ValueError(f"Invalid import: {parser.type} {e}") from e

return v


@field_validator("additional_bases")
def validate_additional_bases(cls, v):
for key, value_list in v.items():
for value in value_list:
if not isinstance(value, str):
raise ValueError("string required")
if value not in dir(builtins):
if "." not in value:
raise ValueError("You need to point to a module if its not a builtin type")
return v



class Extensions(BaseModel):
Expand Down
73 changes: 60 additions & 13 deletions turms/run.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import ast
import os
from typing import Dict, List, Optional, Callable
from typing import Dict, List, Optional, Callable, Tuple

import yaml
from graphql import GraphQLSchema, parse, build_ast_schema, build_client_schema
from graphql import GraphQLSchema, parse, build_ast_schema, build_client_schema, print_ast, print_schema
from pydantic import AnyHttpUrl, ValidationError
from rich import get_console

Expand Down Expand Up @@ -175,6 +175,44 @@ def write_code_to_file(code: str, outdir: str, filepath: str):
return generated_file


def write_schema_to_file(schema: GraphQLSchema, outdir: str, filepath: str):
if not os.path.isdir(outdir): # pragma: no cover
os.makedirs(outdir)

generated_file = os.path.join(
outdir,
filepath,
)

with open(
generated_file,
"w",
encoding="utf-8",
) as file:
file.write(print_schema(schema))

return generated_file


def write_project(project: GraphQLProject, outdir: str, filepath: str):
if not os.path.isdir(outdir): # pragma: no cover
os.makedirs(outdir)

generated_file = os.path.join(
outdir,
filepath,
)

with open(
generated_file,
"w",
encoding="utf-8",
) as file:
file.write(project.model_dump_json(indent=4))

return generated_file


def gen(
filepath: Optional[str] = None,
project_name: Optional[str] = None,
Expand Down Expand Up @@ -207,6 +245,22 @@ def gen(
project.extensions.turms.generated_name,
)

if project.extensions.turms.dump_schema:
schema = build_schema_from_schema_type(
project.schema_url,
allow_introspection=project.extensions.turms.allow_introspection,
)

write_schema_to_file(schema, project.extensions.turms.out_dir, project.extensions.turms.schema_name)

if project.extensions.turms.dump_configuration:
write_project(project, project.extensions.turms.out_dir, project.extensions.turms.configuration_name)






get_console().print("Sucessfull!! :right-facing_fist::left-facing_fist:")
except Exception as e:
get_console().print(
Expand Down Expand Up @@ -310,7 +364,7 @@ def build_schema_from_schema_type(
raise GenerationError("Could not build schema with type " + str(type(schema)))


def generate(project: GraphQLProject, log: Optional[LogFunction] = None) -> str:
def generate(project: GraphQLProject, log: Optional[LogFunction] = None) -> Tuple[str, GraphQLSchema ]:
"""Genrates the code according to the configugration
The code is generated in the following order:
Expand Down Expand Up @@ -378,16 +432,7 @@ def log(x, **kwargs):
get_console().print(f"Using Processor {styler}")
processors.append(styler)

generated_ast = generate_ast(
gen_config,
schema,
plugins=plugins,
stylers=stylers,
skip_forwards=gen_config.skip_forwards,
log=log,
)

return generate_code(
code = generate_code(
gen_config,
schema,
plugins=plugins,
Expand All @@ -397,6 +442,8 @@ def log(x, **kwargs):
log=log,
)

return code, schema


def parse_asts_to_string(generated_ast: List[ast.AST]) -> str:
module = ast.Module(body=generated_ast, type_ignores=[])
Expand Down

0 comments on commit 178673a

Please sign in to comment.