-
Notifications
You must be signed in to change notification settings - Fork 39
Add support for add subcommand to scaffold devfile resources #305
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
ssbarnea
merged 25 commits into
ansible:main
from
tanwigeetika1618:Feature-add-subcommand
Nov 7, 2024
Merged
Changes from 5 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
a90d94f
Add support for add subcommand to scaffold devfile resources
tanwigeetika1618 51c0f05
chore: auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 46abfe8
Update formatting
tanwigeetika1618 755d5c3
Add Unit Tests for add Subcommand in ansible-creator
tanwigeetika1618 15c4bac
Merge branch 'main' into Feature-add-subcommand
cidrblock 1852063
Update add.py and test_add.py file to dynamically add name metavar in…
tanwigeetika1618 0a87827
test this change
tanwigeetika1618 bf321e0
Make add.py more generic
tanwigeetika1618 88cda0d
Add more tests in test_add.py
tanwigeetika1618 8155420
Add support for add subcommand to scaffold devfile resources
tanwigeetika1618 b8215c1
chore: auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1583b0b
Update formatting
tanwigeetika1618 f28ea9c
Add Unit Tests for add Subcommand in ansible-creator
tanwigeetika1618 9690591
Update add.py and test_add.py file to dynamically add name metavar in…
tanwigeetika1618 5956e40
test this change
tanwigeetika1618 fae1b14
Make add.py more generic
tanwigeetika1618 af08d15
Add more tests in test_add.py
tanwigeetika1618 d4d2bb3
Update add.py to make it more generic and test_add.py to full codecov…
tanwigeetika1618 08d73da
Add coverage in test_add.py for unsupported resource type
tanwigeetika1618 ce8d179
Add add_overwrite method to avoid duplicate code in arg_parser.py
tanwigeetika1618 eafc373
Merge branch 'main' into Feature-add-subcommand
tanwigeetika1618 cd56081
Merge branch 'main' into Feature-add-subcommand
tanwigeetika1618 db742a0
Merge branch 'Feature-add-subcommand' of https://github.com/tanwigeet…
tanwigeetika1618 9398bec
Merge branch 'main' into Feature-add-subcommand
ssbarnea 2edfa9e
Update arg_parser.py
ssbarnea 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 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,118 @@ | ||
"""Definitions for ansible-creator add action.""" | ||
|
||
from __future__ import annotations | ||
|
||
from pathlib import Path | ||
from typing import TYPE_CHECKING | ||
|
||
from ansible_creator.exceptions import CreatorError | ||
from ansible_creator.templar import Templar | ||
from ansible_creator.types import TemplateData | ||
from ansible_creator.utils import Copier, Walker, ask_yes_no | ||
|
||
|
||
if TYPE_CHECKING: | ||
from ansible_creator.config import Config | ||
from ansible_creator.output import Output | ||
|
||
|
||
class Add: | ||
"""Class to handle the add subcommand. | ||
|
||
Attributes: | ||
common_resources: List of common resources to copy. | ||
""" | ||
|
||
common_resources = ("common.devfile",) | ||
|
||
def __init__( | ||
self: Add, | ||
config: Config, | ||
) -> None: | ||
"""Initialize the add action. | ||
|
||
Args: | ||
config: App configuration object. | ||
""" | ||
self._resource_type: str = config.resource_type | ||
self._add_path: Path = Path(config.path) | ||
self._force = config.force | ||
self._overwrite = config.overwrite | ||
self._no_overwrite = config.no_overwrite | ||
self._creator_version = config.creator_version | ||
self._project = config.project | ||
self.output: Output = config.output | ||
self.templar = Templar() | ||
|
||
def run(self) -> None: | ||
"""Start scaffolding the resource file.""" | ||
self._check_add_path() | ||
self.output.debug(msg=f"final collection path set to {self._add_path}") | ||
|
||
self._scaffold() | ||
|
||
def _check_add_path(self) -> None: | ||
"""Validate the provided add path. | ||
|
||
Raises: | ||
CreatorError: If the add path does not exist. | ||
""" | ||
if not self._add_path.exists(): | ||
msg = f"The path {self._add_path} does not exist. Please provide an existing directory." | ||
raise CreatorError(msg) | ||
|
||
def _scaffold(self) -> None: | ||
"""Scaffold the specified resource file. | ||
|
||
Raises: | ||
CreatorError: If there are conflicts and overwriting is not allowed. | ||
""" | ||
self.output.debug(f"Started copying {self._project} resource to destination") | ||
|
||
# Set up template data | ||
template_data = TemplateData( | ||
resource_type=self._resource_type, | ||
creator_version=self._creator_version, | ||
tanwigeetika1618 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) | ||
|
||
# Initialize Walker and Copier for file operations | ||
|
||
walker = Walker( | ||
resources=self.common_resources, | ||
tanwigeetika1618 marked this conversation as resolved.
Show resolved
Hide resolved
tanwigeetika1618 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
resource_id="common.devfile", | ||
dest=self._add_path, | ||
output=self.output, | ||
template_data=template_data, | ||
templar=self.templar, | ||
) | ||
paths = walker.collect_paths() | ||
copier = Copier(output=self.output) | ||
|
||
if self._no_overwrite: | ||
msg = "The flag `--no-overwrite` restricts overwriting." | ||
if paths.has_conflicts(): | ||
msg += ( | ||
"\nThe destination directory contains files that can be overwritten." | ||
"\nPlease re-run ansible-creator with --overwrite to continue." | ||
) | ||
raise CreatorError(msg) | ||
|
||
if not paths.has_conflicts() or self._force or self._overwrite: | ||
copier.copy_containers(paths) | ||
self.output.note(f"Resource added to {self._add_path}") | ||
return | ||
|
||
if not self._overwrite: | ||
question = ( | ||
"Files in the destination directory will be overwritten. Do you want to proceed?" | ||
) | ||
if ask_yes_no(question): | ||
copier.copy_containers(paths) | ||
else: | ||
msg = ( | ||
"The destination directory contains files that will be overwritten." | ||
" Please re-run ansible-creator with --overwrite to continue." | ||
) | ||
raise CreatorError(msg) | ||
|
||
self.output.note(f"Resource added to {self._add_path}") |
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,15 @@ | ||
schemaVersion: 2.2.2 | ||
metadata: | ||
name: | ||
tanwigeetika1618 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
components: | ||
- name: tooling-container | ||
container: | ||
image: ghcr.io/ansible/ansible-workspace-env-reference:latest | ||
memoryRequest: 256M | ||
memoryLimit: 6Gi | ||
cpuRequest: 250m | ||
cpuLimit: 2000m | ||
args: ["tail", "-f", "/dev/null"] | ||
env: | ||
- name: KUBEDOCK_ENABLED | ||
value: "true" |
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,138 @@ | ||
# cspell: ignore dcmp, subdcmp | ||
"""Unit tests for ansible-creator add.""" | ||
|
||
from __future__ import annotations | ||
|
||
import re | ||
|
||
from filecmp import dircmp | ||
from typing import TYPE_CHECKING, TypedDict | ||
|
||
import pytest | ||
|
||
|
||
if TYPE_CHECKING: | ||
from pathlib import Path | ||
|
||
from ansible_creator.output import Output | ||
|
||
from ansible_creator.config import Config | ||
from ansible_creator.subcommands.add import Add | ||
from tests.defaults import FIXTURES_DIR | ||
|
||
|
||
class ConfigDict(TypedDict): | ||
"""Type hint for Config dictionary. | ||
|
||
Attributes: | ||
creator_version: The version of the creator. | ||
output: The output object to use for logging. | ||
subcommand: The subcommand to execute. | ||
resource_type: The type of resource to be scaffolded. | ||
type: The type of the project for which the resource is being scaffolded. | ||
path: The file path where the resource should be added. | ||
force: Force overwrite of existing directory. | ||
overwrite: To overwrite files in an existing directory. | ||
no_overwrite: To not overwrite files in an existing directory. | ||
""" | ||
|
||
creator_version: str | ||
output: Output | ||
subcommand: str | ||
resource_type: str | ||
type: str | ||
path: str | ||
force: bool | ||
overwrite: bool | ||
no_overwrite: bool | ||
|
||
|
||
@pytest.fixture(name="cli_args") | ||
def fixture_cli_args(tmp_path: Path, output: Output) -> ConfigDict: | ||
"""Create a dict to use for a Add class object as fixture. | ||
|
||
Args: | ||
tmp_path: Temporary directory path. | ||
output: Output class object. | ||
|
||
Returns: | ||
dict: Dictionary, partial Add class object. | ||
""" | ||
return { | ||
"creator_version": "0.0.1", | ||
"output": output, | ||
"subcommand": "add", | ||
"type": "resource", | ||
"resource_type": "devfile", | ||
"path": str(tmp_path), | ||
"force": False, | ||
"overwrite": False, | ||
"no_overwrite": False, | ||
} | ||
|
||
|
||
def has_differences(dcmp: dircmp[str], errors: list[str]) -> list[str]: | ||
"""Recursively check for differences in dircmp object. | ||
|
||
Args: | ||
dcmp: dircmp object. | ||
errors: List of errors. | ||
|
||
Returns: | ||
list: List of errors. | ||
""" | ||
errors.extend([f"Only in {dcmp.left}: {f}" for f in dcmp.left_only]) | ||
errors.extend([f"Only in {dcmp.right}: {f}" for f in dcmp.right_only]) | ||
errors.extend( | ||
[f"Differing files: {dcmp.left}/{f} {dcmp.right}/{f}" for f in dcmp.diff_files], | ||
) | ||
for subdcmp in dcmp.subdirs.values(): | ||
errors = has_differences(subdcmp, errors) | ||
return errors | ||
|
||
|
||
def test_run_success_add_devfile( | ||
capsys: pytest.CaptureFixture[str], | ||
tmp_path: Path, | ||
cli_args: ConfigDict, | ||
monkeypatch: pytest.MonkeyPatch, | ||
) -> None: | ||
"""Test Add.run(). | ||
|
||
Successfully add devfile to path | ||
|
||
Args: | ||
capsys: Pytest fixture to capture stdout and stderr. | ||
tmp_path: Temporary directory path. | ||
cli_args: Dictionary, partial Add class object. | ||
monkeypatch: Pytest monkeypatch fixture. | ||
""" | ||
add = Add( | ||
Config(**cli_args), | ||
) | ||
|
||
add.run() | ||
result = capsys.readouterr().out | ||
# check stdout | ||
print(result) | ||
assert re.search("Note: Resource added to", result) is not None | ||
|
||
# recursively assert files created | ||
cmp = dircmp(str(tmp_path), str(FIXTURES_DIR / "common" / "devfile")) | ||
diff = has_differences(dcmp=cmp, errors=[]) | ||
assert diff == [], diff | ||
|
||
conflict_file = tmp_path / "devfile.yaml" | ||
conflict_file.write_text("schemaVersion: 2.2.2") | ||
|
||
monkeypatch.setattr("builtins.input", lambda _: "y") | ||
add.run() | ||
result = capsys.readouterr().out | ||
assert ( | ||
re.search( | ||
"already exists", | ||
result, | ||
) | ||
is not None | ||
), result | ||
assert re.search("Note: Resource added to", result) is not None |
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.