Skip to content

Commit

Permalink
Merge branch 'jhnnsrs:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
deyton authored Jul 24, 2024
2 parents ec79514 + c7b9117 commit e771dbe
Show file tree
Hide file tree
Showing 16 changed files with 232 additions and 105 deletions.
1 change: 0 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
},

"files.exclude": {
"**/venv": true,
"**/__pycache__": true,
"**/.pytest_cache": true
},
Expand Down
4 changes: 2 additions & 2 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
{
"label": "Patch",
"type": "shell",
"command": "source venv/bin/activate && poetry version patch && poetry build "
"command": " poetry version patch && poetry build "
},
{
"label": "Publish",
"type": "shell",
"command": "source venv/bin/activate && poetry publish"
"command": " poetry publish"
},
{
"type": "shell",
Expand Down
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2024 Johannes Roos <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
[tool.poetry]
name = "turms"
version = "0.4.2"
version = "0.5.0"
description = "graphql-codegen powered by pydantic"
authors = ["jhnnsrs <[email protected]>"]
license = "CC BY-NC 3.0"
license = "MIT"
readme = "README.md"
packages = [{ include = "turms" }]
homepage = "https://jhnnsrs.github.io/turms"
Expand Down
47 changes: 47 additions & 0 deletions tests/test_optional_input_fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import ast
from graphql import parse, build_ast_schema
from turms.config import GeneratorConfig
from turms.run import generate_ast
from turms.stylers.snake_case import SnakeCaseStyler
from turms.plugins.inputs import InputsPlugin
from turms.plugins.objects import ObjectsPlugin
from .utils import unit_test_with

inputs = '''
input X {
mandatory: String!
otherMandatory: String!
optional: String
otherOptional: String
}
'''


expected = '''class X(BaseModel):
mandatory: str
other_mandatory: str = Field(alias='otherMandatory')
optional: Optional[str] = None
other_optional: Optional[str] = Field(alias='otherOptional', default=None)'''


def test_generates_schema(snapshot):
config = GeneratorConfig()

schema = build_ast_schema(parse(inputs))

generated_ast = generate_ast(
config,
schema,
stylers=[SnakeCaseStyler()],
plugins=[
InputsPlugin(),
ObjectsPlugin(),
],
)

unit_test_with(generated_ast, '')

without_imports = [node for node in generated_ast if not isinstance(node, ast.ImportFrom)]
md = ast.Module(body=without_imports, type_ignores=[])
generated = ast.unparse(ast.fix_missing_locations(md))
assert generated == expected
8 changes: 3 additions & 5 deletions turms/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class TurmsOptions(str, Enum):

welcome = """
Welcome to Turms! Turms is a GraphQL code generator that generates code from your GraphQL schema and documents. For more information, visit
https://gihub.com/jhnnsrs/turms
https://github.com/jhnnsrs/turms
"""


Expand Down Expand Up @@ -81,7 +81,6 @@ def generate_projects(projects, title="Turms"):

with Live(panel, screen=False) as live:
for key, project in projects.items():

project_tree = Tree(f"{key}", style="not bold white")
tree.add(project_tree)
live.update(panel)
Expand Down Expand Up @@ -172,7 +171,6 @@ def watch_projects(projects, title="Turms"): # pragma: no cover
)

with Live(panel, screen=False) as live:

tree.renderable = f"Watching {project.documents}..."
live.update(panel)

Expand Down Expand Up @@ -201,7 +199,6 @@ def watch_projects(projects, title="Turms"): # pragma: no cover
live.update(panel)

except Exception as e:

tree.renderable = f"[red] {str(e)} [/],"
tree.border_style = "not bold red"
tree.style = "not bold red"
Expand All @@ -216,7 +213,8 @@ def cli(ctx):
Welcome to Turms! Turms is a GraphQL code generator that generates code from your GraphQL schema and documents.
For more information, visit [link=https://gihub.com/jhnnsrs/turms] https://gihub.com/jhnnsrs/turms [/link]"""
For more information, visit [link=https://github.com/jhnnsrs/turms] https://github.com/jhnnsrs/turms [/link]
"""


@cli.command()
Expand Down
6 changes: 6 additions & 0 deletions turms/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ def load_introspection_from_url(
raise GenerationError(
f"Failed to fetch schema from {url} Graphql error: {x['errors']}"
)

if "data" not in x:
raise GenerationError(f"Failed to fetch schema from {url}. Did not receive data attripute: {x}")



return x["data"]


Expand Down
8 changes: 2 additions & 6 deletions turms/plugins/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class EnumsPluginConfig(PluginConfig):
type = "turms.plugins.enums.EnumsPlugin"
skip_underscore: bool = False
skip_double_underscore: bool = True
skip_unreferenced: bool = False
skip_unreferenced: bool = True
prepend: str = ""
append: str = ""

Expand All @@ -35,7 +35,6 @@ def generate_enums(
plugin_config: EnumsPluginConfig,
registry: ClassRegistry,
):

tree = []

enum_types = {
Expand All @@ -44,15 +43,14 @@ def generate_enums(
if isinstance(value, GraphQLEnumType)
}

if plugin_config.skip_unreferenced:
if plugin_config.skip_unreferenced and config.documents:
ref_registry = create_reference_registry_from_documents(
client_schema, parse_documents(client_schema, config.documents)
)
else:
ref_registry = None

for key, type in enum_types.items():

if ref_registry and key not in ref_registry.enums:
continue

Expand All @@ -71,7 +69,6 @@ def generate_enums(
)

for value_key, value in type.values.items():

if isinstance(value.value, str):
servalue = value.value
else:
Expand Down Expand Up @@ -129,7 +126,6 @@ def generate_ast(
config: GeneratorConfig,
registry: ClassRegistry,
) -> List[ast.AST]:

registry.register_import("enum.Enum")

return generate_enums(client_schema, config, self.config, registry)
59 changes: 43 additions & 16 deletions turms/plugins/funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,24 @@ def generate_parameters(

for kwarg in extra_kwargs:
registry.register_import(kwarg.type)

annotation = ast.Name(
id=kwarg.type.split(".")[-1],
ctx=ast.Load(),
)

if kwarg.default is None:
# if we set the default to None, we need to make the annotation optional
# complies with PEP 484
annotation = ast.Subscript(
value=ast.Name(id="Optional", ctx=ast.Load()),
slice=annotation,
)

kw_args.append(
ast.arg(
arg=kwarg.key,
annotation=ast.Name(
id=kwarg.type.split(".")[-1],
ctx=ast.Load(),
),
annotation=annotation,
)
)
kw_values.append(ast.Constant(value=kwarg.default))
Expand Down Expand Up @@ -503,6 +514,12 @@ def genereate_async_call(
)
)
else:
correct_attr = (
o.selection_set.selections[0].alias.value
if o.selection_set.selections[0].alias
else o.selection_set.selections[0].name.value
)

return ast.Return(
value=ast.Attribute(
value=ast.Await(
Expand All @@ -523,9 +540,7 @@ def genereate_async_call(
],
)
),
attr=registry.generate_node_name(
o.selection_set.selections[0].name.value
),
attr=registry.generate_node_name(correct_attr),
ctx=ast.Load(),
)
)
Expand Down Expand Up @@ -559,6 +574,12 @@ def genereate_sync_call(
)
)
else:
correct_attr = (
o.selection_set.selections[0].alias.value
if o.selection_set.selections[0].alias
else o.selection_set.selections[0].name.value
)

return ast.Return(
value=ast.Attribute(
value=ast.Call(
Expand All @@ -577,9 +598,7 @@ def genereate_sync_call(
generate_variable_dict(o, plugin_config, registry),
],
),
attr=registry.generate_node_name(
o.selection_set.selections[0].name.value
),
attr=registry.generate_node_name(correct_attr),
ctx=ast.Load(),
)
)
Expand Down Expand Up @@ -618,6 +637,12 @@ def genereate_async_iterator(
orelse=[],
)
else:
correct_attr = (
o.selection_set.selections[0].alias.value
if o.selection_set.selections[0].alias
else o.selection_set.selections[0].name.value
)

return ast.AsyncFor(
target=ast.Name(id="event", ctx=ast.Store()),
iter=ast.Call(
Expand All @@ -640,9 +665,7 @@ def genereate_async_iterator(
value=ast.Attribute(
value=ast.Name(id="event", ctx=ast.Load()),
ctx=ast.Load(),
attr=registry.generate_node_name(
o.selection_set.selections[0].name.value
),
attr=registry.generate_node_name(correct_attr),
)
)
),
Expand Down Expand Up @@ -684,6 +707,12 @@ def genereate_sync_iterator(
orelse=[],
)
else:
correct_attr = (
o.selection_set.selections[0].alias.value
if o.selection_set.selections[0].alias
else o.selection_set.selections[0].name.value
)

return ast.For(
target=ast.Name(id="event", ctx=ast.Store()),
iter=ast.Call(
Expand All @@ -706,9 +735,7 @@ def genereate_sync_iterator(
value=ast.Attribute(
value=ast.Name(id="event", ctx=ast.Load()),
ctx=ast.Load(),
attr=registry.generate_node_name(
o.selection_set.selections[0].name.value
),
attr=registry.generate_node_name(correct_attr),
)
)
),
Expand Down
Loading

0 comments on commit e771dbe

Please sign in to comment.