Skip to content
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

Refine CLI for use with get_table as almanack <repo path> #136

Merged
merged 8 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jupyterlab-spellchecker = "^0.8.4"
jsonschema = "^4.23.0"

[tool.poetry.scripts]
almanack = "almanack.reporting.cli:trigger"
almanack = "almanack.cli:cli_get_table"

[tool.poetry-dynamic-versioning]
enable = true
Expand Down
48 changes: 48 additions & 0 deletions src/almanack/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
Setup almanack CLI through python-fire
"""

import json

import fire

from .metrics.data import get_table


def get_table_json_wrapper(repo_path: str) -> str:
"""
Converts the output of get_table to a proper JSON str.
Note: python-fire seems to convert lists of dictionaries
into individual dictionaries without distinction within list.

Args:
repo_path (str):
Path to the repository from which to retrieve and
convert the table data.

Returns:
str:
JSON string representation of the table data.
"""

return json.dumps(get_table(repo_path=repo_path))


def cli_get_table() -> None:
"""
Creates Fire CLI for get_table_json_wrapper.

This enables the use of CLI such as:
`almanck <repo path>`
"""
fire.Fire(get_table_json_wrapper)


if __name__ == "__main__":
"""
Setup the CLI with python-fire for the almanack package.

This allows the function `check` to be ran through the
command line interface.
"""
cli_get_table()
d33bs marked this conversation as resolved.
Show resolved Hide resolved
4 changes: 2 additions & 2 deletions src/almanack/metrics/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import shutil
import tempfile
from datetime import datetime, timezone
from typing import Any, Dict, Optional, Tuple
from typing import Any, Dict, List, Optional, Tuple

import pygit2
import yaml
Expand All @@ -20,7 +20,7 @@
METRICS_TABLE = f"{pathlib.Path(__file__).parent!s}/metrics.yml"


def get_table(repo_path: str) -> Dict[str, Any]:
def get_table(repo_path: str) -> List[Dict[str, Any]]:
d33bs marked this conversation as resolved.
Show resolved Hide resolved
"""
Gather metrics on a repository and return the results in a structured format.

Expand Down
24 changes: 0 additions & 24 deletions src/almanack/reporting/cli.py

This file was deleted.

57 changes: 57 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""
Tests CLI functionality.
"""

import json

import yaml

from almanack.metrics.data import METRICS_TABLE
from tests.data.almanack.repo_setup.create_repo import repo_setup

from .utils import run_cli_command


def test_cli_util():
"""
Test the run_cli_command for successful output
"""

command = """echo 'hello world'"""
_, _, returncode = run_cli_command(command)

assert returncode == 0
d33bs marked this conversation as resolved.
Show resolved Hide resolved


def test_cli_almanack(tmp_path):
"""
Tests running `almanack` as a CLI
"""

# create a repo with a single file and commit
repo = repo_setup(repo_path=tmp_path, files={"example.txt": "example"})

# gather output and return code from running a CLI command
stdout, _, returncode = run_cli_command(f"almanack {repo.path}")

# make sure we return 0 on success
assert returncode == 0

# gather result of CLI as json
results = json.loads(stdout)

# make sure we have a list of output
assert isinstance(results, list)

# open the metrics table
with open(METRICS_TABLE, "r") as f:
metrics_table = yaml.safe_load(f)

# check that all keys exist in the output from metrics table to cli str
assert all(
x == y
for x, y in zip(
sorted([result["name"] for result in results]),
sorted([metric["name"] for metric in metrics_table["metrics"]]),
)
)
18 changes: 18 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import subprocess
from typing import Tuple


def check_subproc_run_for_nonzero(completed_proc: subprocess.CompletedProcess) -> None:
Expand All @@ -17,3 +18,20 @@ def check_subproc_run_for_nonzero(completed_proc: subprocess.CompletedProcess) -
except Exception as exc:
# raise the exception with decoded output from linkchecker for readability
raise Exception(completed_proc.stdout.decode()) from exc


def run_cli_command(command: str) -> Tuple[str, str, int]:
"""
Run a CLI command using subprocess and capture the output and return code.

Args:
command (list): The command to run as a list of strings.

Returns:
tuple: (str: stdout, str: stderr, int: returncode)
"""

result = subprocess.run(
command.split(" "), capture_output=True, text=True, check=False
d33bs marked this conversation as resolved.
Show resolved Hide resolved
)
return result.stdout, result.stderr, result.returncode