-
-
Notifications
You must be signed in to change notification settings - Fork 13
Create a CLI #201
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
Merged
Merged
Create a CLI #201
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 was deleted.
Oops, something went wrong.
This file contains hidden or 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 hidden or 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,56 @@ | ||
| OpenAlchemy CLI | ||
| =============== | ||
|
|
||
| openalchemy build | ||
| ----------------- | ||
|
|
||
| Description | ||
| ^^^^^^^^^^^ | ||
|
|
||
| Build a Python package containing the models described in the OpenAPI | ||
| specification file. | ||
|
|
||
| Usage | ||
| ^^^^^ | ||
|
|
||
| .. program:: openalchemy | ||
|
|
||
| .. option:: openalchemy build [OPTIONS] SPECFILE PKG_NAME OUTPUT_DIR | ||
jdkandersson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| Extended Description | ||
| ^^^^^^^^^^^^^^^^^^^^ | ||
|
|
||
| The :samp:`openalchemy build` command builds a reusable Python package based off of | ||
| the specification file. | ||
|
|
||
| For instance, running the following command:: | ||
|
|
||
| openalchemy build openapi.yml simple dist | ||
|
|
||
| Produces the following artifacts:: | ||
|
|
||
| dist | ||
jdkandersson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| └── simple | ||
| ├── MANIFEST.in | ||
| ├── build | ||
| ├── dist | ||
| │ ├── simple-0.1-py3-none-any.whl | ||
| │ └── simple-0.1.tar.gz | ||
| ├── setup.py | ||
| ├── simple | ||
| │ ├── __init__.py | ||
| │ └── spec.json | ||
| └── simple.egg-info | ||
|
|
||
| By default, a source and a wheel package are built, but this behavior can be | ||
| adjusted by using the :samp:`--format` option. | ||
|
|
||
| Options | ||
| ^^^^^^^ | ||
|
|
||
| +-----------------+--------------+-------------------------------------------+ | ||
| | Name, shorthand | Default | Description | | ||
| +-----------------+--------------+-------------------------------------------+ | ||
| | --format, -f | sdist, wheel | limit the format to either sdist or wheel | | ||
| +-----------------+--------------+-------------------------------------------+ | ||
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -462,3 +462,11 @@ Examples | |
| :maxdepth: 3 | ||
|
|
||
| examples/index | ||
|
|
||
| CLI | ||
| --- | ||
|
|
||
| .. toctree:: | ||
| :maxdepth: 3 | ||
|
|
||
| cli | ||
This file contains hidden or 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 hidden or 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,105 @@ | ||
| """Define the CLI module.""" | ||
| import argparse | ||
| import logging | ||
| import pathlib | ||
|
|
||
| from open_alchemy import PackageFormat | ||
| from open_alchemy import build_json | ||
| from open_alchemy import build_yaml | ||
| from open_alchemy import exceptions | ||
|
|
||
| # Configure the logger. | ||
| logging.basicConfig(format="%(message)s", level=logging.INFO) | ||
|
|
||
| # Define constants. | ||
| VALID_EXTENSIONS = [".json", ".yml", ".yaml"] | ||
|
|
||
|
|
||
| def main() -> None: | ||
| """Define the CLI entrypoint.""" | ||
| args = build_application_parser() | ||
| try: | ||
| args.func(args) | ||
| except exceptions.CLIError as exc: | ||
| logging.error("Cannot perform the operation: %s.", exc) | ||
|
|
||
|
|
||
| def validate_specfile(specfile: pathlib.Path) -> None: | ||
| """ | ||
| Ensure the specfile is valid. | ||
|
|
||
| The specification file must: | ||
| * exist | ||
| * have a valid extension (.json, .yml, or .yaml) | ||
|
|
||
| Args: | ||
| specfile: Path object representing the specification file. | ||
| """ | ||
| # Ensure the file exists. | ||
| if not specfile.exists(): | ||
| raise exceptions.CLIError(f"the specfile '{specfile}' cannot be found") | ||
|
|
||
| # Ensure the extension is valid. | ||
| ext = specfile.suffix.lower() | ||
| if ext not in VALID_EXTENSIONS: | ||
| raise exceptions.CLIError( | ||
| f"specification format not supported: '{specfile}' " | ||
| f"(valid extensions are {', '.join(VALID_EXTENSIONS)}, " | ||
| "case insensitive)" | ||
| ) | ||
|
|
||
|
|
||
| def build_application_parser() -> argparse.Namespace: | ||
| """Build the main parser and subparsers.""" | ||
| # Define the top level parser. | ||
| parser = argparse.ArgumentParser() | ||
| subparsers = parser.add_subparsers(title="subcommands", help="subcommand help") | ||
|
|
||
| # Define the parser for the "build" subcommand. | ||
| build_parser = subparsers.add_parser( | ||
| "build", | ||
| description="Build a package with the SQLAlchemy models.", | ||
| help="build a package", | ||
| ) | ||
| build_parser.add_argument( | ||
| "specfile", type=str, help="specify the specification file" | ||
| ) | ||
| build_parser.add_argument("name", type=str, help="specify the package name") | ||
jdkandersson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| build_parser.add_argument("output", type=str, help="specify the output directory") | ||
jdkandersson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| build_parser.add_argument( | ||
jdkandersson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| "-f", | ||
| "--format", | ||
| type=str.lower, | ||
| choices=["sdist", "wheel"], | ||
| help="limit the format to either sdist or wheel, defaults to both", | ||
| ) | ||
| build_parser.set_defaults(func=build) | ||
|
|
||
| # Return the parsed arguments for a particular command. | ||
| return parser.parse_args() | ||
|
|
||
|
|
||
| def build(args: argparse.Namespace) -> None: | ||
| """ | ||
| Define the build subcommand. | ||
|
|
||
| Args: | ||
| args: CLI arguments from the parser. | ||
| """ | ||
| # Check the specfile. | ||
| specfile = pathlib.Path(args.specfile) | ||
| validate_specfile(specfile) | ||
|
|
||
| # Select the builder method. | ||
| builders = dict(zip(VALID_EXTENSIONS, [build_json, build_yaml, build_yaml])) | ||
|
|
||
| # Choose the distributable format. | ||
| fmt = { | ||
| None: PackageFormat.SDIST | PackageFormat.WHEEL, | ||
| "sdist": PackageFormat.SDIST, | ||
| "wheel": PackageFormat.WHEEL, | ||
| } | ||
|
|
||
| # Build the package. | ||
| builder = builders.get(specfile.suffix.lower()) | ||
jdkandersson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| builder(args.specfile, args.name, args.output, fmt.get(args.format)) # type: ignore | ||
This file contains hidden or 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 hidden or 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 hidden or 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,37 @@ | ||
| """Execute external commands.""" | ||
|
|
||
| import subprocess # nosec: we are aware of the implications. | ||
| import typing | ||
|
|
||
| from .. import exceptions | ||
|
|
||
|
|
||
| def run(cmd: typing.List[str], cwd: str) -> typing.Tuple[str, str]: | ||
| """ | ||
| Run a shell command. | ||
|
|
||
| Args: | ||
| cmd: The command to execute. | ||
| cwd: The path where the command must be executed from. | ||
|
|
||
| Returns: | ||
| A tuple containing (stdout, stderr). | ||
|
|
||
| """ | ||
| output = None | ||
| try: | ||
| # "nosec" is used here as we believe we followed the guidelines to use | ||
| # subprocess securely: | ||
| # https://security.openstack.org/guidelines/dg_use-subprocess-securely.html | ||
| output = subprocess.run( # nosec | ||
| cmd, | ||
| cwd=cwd, | ||
| check=True, | ||
| shell=False, | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| ) | ||
| except subprocess.CalledProcessError as exc: | ||
| raise exceptions.BuildError(str(exc)) from exc | ||
|
|
||
| return output.stdout.decode("utf-8"), output.stderr.decode("utf-8") |
This file contains hidden or 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 hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.