Skip to content

Support CLI arguments for cfn init #574

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 13 commits into from
Oct 2, 2020
91 changes: 80 additions & 11 deletions src/rpdk/core/init.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""This sub command generates IDE and build files for a given language.
"""
import argparse
import logging
import re
from argparse import SUPPRESS
from functools import wraps

from colorama import Fore, Style

from .exceptions import WizardAbortError, WizardValidationError
from .plugin_registry import PLUGIN_CHOICES
from .plugin_registry import PARSER_REGISTRY, get_plugin_choices
from .project import Project

LOG = logging.getLogger(__name__)
Expand Down Expand Up @@ -42,7 +42,7 @@ def validate_type_name(value):
return value
LOG.debug("'%s' did not match '%s'", value, TYPE_NAME_REGEX)
raise WizardValidationError(
"Please enter a value matching '{}'".format(TYPE_NAME_REGEX)
"Please enter a resource type name matching '{}'".format(TYPE_NAME_REGEX)
)


Expand Down Expand Up @@ -77,7 +77,7 @@ def __call__(self, value):


validate_plugin_choice = ValidatePluginChoice( # pylint: disable=invalid-name
PLUGIN_CHOICES
get_plugin_choices()
)


Expand Down Expand Up @@ -139,14 +139,39 @@ def init(args):

check_for_existing_project(project)

type_name = input_typename()
if args.type_name:
try:
type_name = validate_type_name(args.type_name)
except WizardValidationError as error:
print(Style.BRIGHT, Fore.RED, str(error), Style.RESET_ALL, sep="")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we do it a bit more generic and reusable?

type_name = input_typename()
else:
type_name = input_typename()

if args.language:
language = args.language
LOG.warning("Language plugin '%s' selected non-interactively", language)
language = args.language.lower()
if language not in get_plugin_choices():
print(
Style.BRIGHT,
Fore.RED,
"The plugin for {} is not installed.".format(language),
Copy link
Contributor

@johnttompkins johnttompkins Sep 15, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"The plugin for {} is not installed.".format(language),
"The plugin for {} cannot be found.".format(language),

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we probably should not always print colorama otherwise it will be really hard to maintain;
maybe we can use for an abstract exception which all will change color entry

Style.RESET_ALL,
sep="",
)
language = input_language()
else:
language = input_language()

project.init(type_name, language)
settings = {
arg: getattr(args, arg)
for arg in vars(args)
if not callable(getattr(args, arg))
}

print("--------------------\n", settings, "\n-----------------------")

project.init(type_name, language, settings)

project.generate()
project.generate_docs()

Expand All @@ -171,8 +196,52 @@ def setup_subparser(subparsers, parents):
parser = subparsers.add_parser("init", description=__doc__, parents=parents)
parser.set_defaults(command=ignore_abort(init))

language_subparsers = parser.add_subparsers(dest="subparser_name")
base_subparser = argparse.ArgumentParser(add_help=False)
for language_setup_subparser in PARSER_REGISTRY.values():
language_parser = language_setup_subparser()(language_subparsers, [base_subparser])
print(vars(language_parser.parse_args([])))

parser.add_argument(
"--force", action="store_true", help="Force files to be overwritten."
"-f",
"--force",
action="store_true",
help="Force files to be overwritten.",
)
# this is mainly for CI, so suppress it to keep it simple
parser.add_argument("--language", help=SUPPRESS)

parser.add_argument(
"-t",
"--type-name",
help="Select the name of the resource type.",
)

# parser.add_argument(
# "-d",
# "--use-docker",
# action="store_true",
# help="""Use docker for python platform-independent packaging.
# This is highly recommended unless you are experienced
# with cross-platform Python packaging.""",
# )

# parser.add_argument(
# "-n",
# "--namespace",
# nargs="?",
# const="default",
# help="""Select the name of the Java namespace.
# Passing the flag without argument select the default namespace.""",
# )

# parser.add_argument(
# "-c",
# "--codegen-model",
# choices=["default", "guided_aws"],
# help="Select a codegen model.",
# )

# parser.add_argument(
# "-p",
# "--import-path",
# help="Select the go language import path.",
# )
13 changes: 12 additions & 1 deletion src/rpdk/core/plugin_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,18 @@
for entry_point in pkg_resources.iter_entry_points("rpdk.v1.languages")
}

PLUGIN_CHOICES = sorted(PLUGIN_REGISTRY.keys())
PARSER_REGISTRY = {
entry_point.name: entry_point.load
for entry_point in pkg_resources.iter_entry_points("rpdk.v1.parsers")
}


def get_plugin_choices():
plugin_choices = [
entry_point.name
for entry_point in pkg_resources.iter_entry_points("rpdk.v1.languages")
]
Comment on lines +10 to +13
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would use set if you dont rely on element position

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before my changes the list of plugins was already being sorted which converts the set back to a list. I f this is not required anymore I'll be ok with making it a set.

return sorted(plugin_choices)


def load_plugin(language):
Expand Down
148 changes: 113 additions & 35 deletions tests/test_init.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from pathlib import Path
from unittest.mock import ANY, Mock, PropertyMock, patch

import pytest
Expand All @@ -17,65 +16,144 @@
)
from rpdk.core.project import Project

from .utils import add_dummy_language_plugin, get_args, get_mock_project

PROMPT = "MECVGD"
ERROR = "TUJFEL"


def test_init_method_interactive_language():
type_name = object()
language = object()
# def test_init_method_interactive():
# type_name = object()
# language = object()

args = Mock(spec_set=["force", "language"])
args.force = False
args.language = None
# args = get_args(interactive=True)
# mock_project, patch_project = get_mock_project()

mock_project = Mock(spec=Project)
mock_project.load_settings.side_effect = FileNotFoundError
mock_project.settings_path = ""
mock_project.root = Path(".")
# patch_tn = patch("rpdk.core.init.input_typename", return_value=type_name)
# patch_l = patch("rpdk.core.init.input_language", return_value=language)

patch_project = patch("rpdk.core.init.Project", return_value=mock_project)
patch_tn = patch("rpdk.core.init.input_typename", return_value=type_name)
patch_l = patch("rpdk.core.init.input_language", return_value=language)
# with patch_project, patch_tn as mock_tn, patch_l as mock_l:
# init(args)

with patch_project, patch_tn as mock_tn, patch_l as mock_l:
init(args)
# mock_tn.assert_called_once_with()
# mock_l.assert_called_once_with()

mock_tn.assert_called_once_with()
mock_l.assert_called_once_with()
# mock_project.load_settings.assert_called_once_with()
# mock_project.init.assert_called_once_with(
# type_name,
# language,
# {
# "use_docker": args.use_docker,
# "namespace": args.namespace,
# "codegen_template_path": args.codegen_model,
# "importpath": args.import_path,
# },
# )
# mock_project.generate.assert_called_once_with()

mock_project.load_settings.assert_called_once_with()
mock_project.init.assert_called_once_with(type_name, language)
mock_project.generate.assert_called_once_with()

def test_init_method_noninteractive():
add_dummy_language_plugin()

def test_init_method_noninteractive_language():
type_name = object()
args = get_args()
mock_project, patch_project = get_mock_project()

args = Mock(spec_set=["force", "language"])
args.force = False
args.language = "rust1.39"
print(args)

mock_project = Mock(spec=Project)
mock_project.load_settings.side_effect = FileNotFoundError
mock_project.settings_path = ""
mock_project.root = Path(".")

patch_project = patch("rpdk.core.init.Project", return_value=mock_project)
patch_tn = patch("rpdk.core.init.input_typename", return_value=type_name)
patch_tn = patch("rpdk.core.init.input_typename")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do these need to be patched if we are going the non-interactive route?

patch_l = patch("rpdk.core.init.input_language")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here. no reason to patch if we are just asserting we aren't calling


with patch_project, patch_tn as mock_tn, patch_l as mock_l:
init(args)

mock_tn.assert_called_once_with()
mock_tn.assert_not_called()
mock_l.assert_not_called()

mock_project.load_settings.assert_called_once_with()
mock_project.init.assert_called_once_with(type_name, args.language)
mock_project.init.assert_called_once_with(
args.type_name,
args.language,
{
# "use_docker": args.use_docker,
# "namespace": args.namespace,
# "codegen_template_path": args.codegen_model,
# "importpath": args.import_path,
# "version": args.version,
# "subparser_name": args.subparser_name,
# "verbose": args.verbose,
# "force": args.force,
# "type_name": args.type_name,
# "language": args.language,
},
)
mock_project.generate.assert_called_once_with()


# def test_init_method_noninteractive_invalid_type_name():
# add_dummy_language_plugin()
# type_name = object()

# args = get_args(type_name=False)
# mock_project, patch_project = get_mock_project()

# patch_tn = patch("rpdk.core.init.input_typename", return_value=type_name)
# patch_l = patch("rpdk.core.init.input_language")

# with patch_project, patch_tn as mock_tn, patch_l as mock_l:
# init(args)

# mock_tn.assert_called_once_with()
# mock_l.assert_not_called()

# mock_project.load_settings.assert_called_once_with()
# mock_project.init.assert_called_once_with(
# type_name,
# args.language,
# {
# "use_docker": args.use_docker,
# "namespace": args.namespace,
# "codegen_template_path": args.codegen_model,
# "importpath": args.import_path,
# },
# )
# mock_project.generate.assert_called_once_with()


# def test_init_method_noninteractive_invalid_language():
# language = object()

# args = get_args(language=False)
# mock_project, patch_project = get_mock_project()

# patch_tn = patch("rpdk.core.init.input_typename")
# patch_l = patch("rpdk.core.init.input_language", return_value=language)

# with patch_project, patch_tn as mock_tn, patch_l as mock_l:
# init(args)

# mock_tn.assert_not_called()
# mock_l.assert_called_once_with()

# mock_project.load_settings.assert_called_once_with()
# mock_project.init.assert_called_once_with(
# args.type_name,
# language,
# {
# "use_docker": args.use_docker,
# # "namespace": args.namespace,
# # "codegen_template_path": args.codegen_model,
# # "importpath": args.import_path,
# "version": False,
# "subparser_name": "python37",
# "verbose": 0,
# "force": False,
# "type_name": "TT::TT::TT",
# "language": "python37",
# },
# )
# mock_project.generate.assert_called_once_with()


def test_input_with_validation_valid_first_try(capsys):
sentinel1 = object()
sentinel2 = object()
Expand Down
Loading