diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 0000000000..d35e3c8702 --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,3 @@ +Release type: minor + +Adds a new flag to `export-schema` command, `--output`, which allows the user to specify the output file. If unset (current behavior), the command will continue to print to stdout. diff --git a/docs/guides/schema-export.md b/docs/guides/schema-export.md index d135afde0c..74e3fc6fe3 100644 --- a/docs/guides/schema-export.md +++ b/docs/guides/schema-export.md @@ -25,3 +25,9 @@ In order to store the exported schema in a file, pipes or redirection can be uti ```bash strawberry export-schema package.module:schema > schema.graphql ``` + +Alternatively, the `--output` option can be used: + +```bash +strawberry export-schema package.module:schema --output schema.graphql +``` diff --git a/strawberry/cli/commands/export_schema.py b/strawberry/cli/commands/export_schema.py index d5585a6bf3..9592f5a488 100644 --- a/strawberry/cli/commands/export_schema.py +++ b/strawberry/cli/commands/export_schema.py @@ -1,3 +1,5 @@ +from pathlib import Path + import typer from strawberry.cli.app import app @@ -18,7 +20,19 @@ def export_schema( "Works the same as `--app-dir` in uvicorn." ), ), + output: Path = typer.Option( + None, + "--output", + "-o", + help="File to save the exported schema. If not provided, prints to console.", + ), ) -> None: schema_symbol = load_schema(schema, app_dir) - print(print_schema(schema_symbol)) # noqa: T201 + schema_text = print_schema(schema_symbol) + + if output: + Path(output).write_text(schema_text) + typer.echo(f"Schema exported to {output}") + else: + print(schema_text) # noqa: T201 diff --git a/tests/cli/test_export_schema.py b/tests/cli/test_export_schema.py index f12c14c4c4..3f1b342b74 100644 --- a/tests/cli/test_export_schema.py +++ b/tests/cli/test_export_schema.py @@ -67,3 +67,25 @@ def test_invalid_schema_instance(cli_app: Typer, cli_runner: CliRunner): assert result.exit_code == 2 assert expected_error in result.stdout.replace("\n", "") + + +def test_output_option(cli_app: Typer, cli_runner: CliRunner, tmp_path): + selector = "tests.fixtures.sample_package.sample_module:schema" + output = tmp_path / "schema.graphql" + output_commands = ["--output", "-o"] + for output_command in output_commands: + result = cli_runner.invoke( + cli_app, ["export-schema", selector, output_command, str(output)] + ) + + assert result.exit_code == 0 + assert output.read_text() == ( + "type Query {\n" + " user: User!\n" + "}\n" + "\n" + "type User {\n" + " name: String!\n" + " age: Int!\n" + "}" + )