Skip to content

Commit

Permalink
Usability improvements to the Canvas CLI output.
Browse files Browse the repository at this point in the history
  • Loading branch information
aduane committed May 31, 2024
1 parent e77c1ff commit 77d38f1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 31 deletions.
20 changes: 13 additions & 7 deletions canvas_cli/apps/logs/logs.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,33 @@
import json
from typing import Optional
from urllib.parse import urlparse

import typer
import websocket

from canvas_cli.apps.auth.utils import get_default_host, get_or_request_api_token
from canvas_cli.utils.print import print


def _on_message(ws: websocket.WebSocketApp, message: str) -> None:
print.json(message)
message_to_print = message
try:
message_json = json.loads(message)
message_to_print = f"{message_json['timestamp']} | {message_json['message']}"
except ValueError:
pass
print(message_to_print)


def _on_error(ws: websocket.WebSocketApp, error: str) -> None:
print.json(f"Error: {error}", success=False)
print(f"Error: {error}")


def _on_close(ws: websocket.WebSocketApp, close_status_code: str, close_msg: str) -> None:
print.json(f"Connection closed with status code {close_status_code}: {close_msg}")
print(f"Connection closed with status code {close_status_code}: {close_msg}")


def _on_open(ws: websocket.WebSocketApp) -> None:
print.json("Connected to the logging service")
print("Connected to the logging service")


def logs(
Expand All @@ -40,8 +46,8 @@ def logs(
hostname = urlparse(host).hostname
instance = hostname.removesuffix(".canvasmedical.com")

print.json(
f"Connecting to the log stream. Please be patient as there may be a delay before log messages appear."
print(
"Connecting to the log stream. Please be patient as there may be a delay before log messages appear."
)
websocket_uri = f"wss://logs.console.canvasmedical.com/{instance}?token={token}"

Expand Down
43 changes: 21 additions & 22 deletions canvas_cli/apps/plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

from canvas_cli.apps.auth.utils import get_default_host, get_or_request_api_token
from canvas_cli.utils.context import context
from canvas_cli.utils.print import print
from canvas_cli.utils.validators import validate_manifest_file


Expand Down Expand Up @@ -59,11 +58,11 @@ def _get_name_from_metadata(host: str, token: str, package: Path) -> Optional[st
files={"package": open(package, "rb")},
)
except requests.exceptions.RequestException:
print.json(f"Failed to connect to {host}", success=False)
print(f"Failed to connect to {host}")
raise typer.Exit(1)

if metadata_response.status_code != requests.codes.ok:
print.response(metadata_response, success=False)
print(f"Status code {metadata_response.status_code}: {metadata_response.text}")
raise typer.Exit(1)

metadata = metadata_response.json()
Expand All @@ -83,7 +82,7 @@ def init() -> None:
except OutputDirExistsException:
raise typer.BadParameter(f"The supplied directory already exists")

print.json(f"Project created in {project_dir}", project_dir=project_dir)
print(f"Project created in {project_dir}")


def install(
Expand Down Expand Up @@ -123,19 +122,19 @@ def install(
headers={"Authorization": f"Bearer {token}"},
)
except requests.exceptions.RequestException:
print.json(f"Failed to connect to {host}", success=False)
print(f"Failed to connect to {host}")
raise typer.Exit(1)

if r.status_code == requests.codes.created:
print.response(r)
print("Plugin successfully installed!")

# If we got a bad_request, means there's a duplicate plugin and install can't handle that.
# So we need to get the plugin-name from the package and call `update` directly
elif r.status_code == requests.codes.bad_request:
plugin_name = _get_name_from_metadata(host, token, built_package_path)
update(plugin_name, built_package_path, is_enabled=True, host=host)
else:
print.response(r, success=False)
print(f"Status code {r.status_code}: {r.text}")
raise typer.Exit(1)


Expand Down Expand Up @@ -165,13 +164,13 @@ def uninstall(
},
)
except requests.exceptions.RequestException:
print.json(f"Failed to connect to {host}", success=False)
print(f"Failed to connect to {host}")
raise typer.Exit(1)

if r.status_code == requests.codes.no_content:
print.response(r)
print(r.text)
else:
print.response(r, success=False)
print(f"Status code {r.status_code}: {r.text}")
raise typer.Exit(1)


Expand All @@ -196,13 +195,16 @@ def list(
headers={"Authorization": f"Bearer {token}"},
)
except requests.exceptions.RequestException:
print.json(f"Failed to connect to {host}", success=False)
print(f"Failed to connect to {host}")
raise typer.Exit(1)

if r.status_code == requests.codes.ok:
print.response(r)
for plugin in r.json().get("results", []):
print(
f"{plugin['name']}@{plugin['version']}\t{'enabled' if plugin['is_enabled'] else 'not enabled'}"
)
else:
print.response(r, success=False)
print(f"Status code {r.status_code}: {r.text}")
raise typer.Exit(1)


Expand All @@ -226,16 +228,12 @@ def validate_manifest(
try:
manifest_json = json.loads(manifest.read_text())
except json.JSONDecodeError:
print.json(
"There was a problem loading the manifest file, please ensure it's valid JSON",
success=False,
path=str(plugin_name),
)
print("There was a problem loading the manifest file, please ensure it's valid JSON")
raise typer.Abort()

validate_manifest_file(manifest_json)

print.json(f"Plugin '{plugin_name}' has a valid CANVAS_MANIFEST.json file")
print(f"Plugin '{plugin_name}' has a valid CANVAS_MANIFEST.json file")


def update(
Expand Down Expand Up @@ -276,11 +274,12 @@ def update(
headers={"Authorization": f"Bearer {token}"},
)
except requests.exceptions.RequestException:
print.json(f"Failed to connect to {host}", success=False)
print(f"Failed to connect to {host}")
raise typer.Exit(1)

if r.status_code == requests.codes.ok:
print.response(r)
print("Plugin successfully updated!")

else:
print.response(r, success=False)
print(f"Status code {r.status_code}: {r.text}")
raise typer.Exit(1)
3 changes: 1 addition & 2 deletions canvas_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from canvas_cli.apps import plugin
from canvas_cli.apps.logs import logs as logs_command
from canvas_cli.utils.context import context
from canvas_cli.utils.print import print

APP_NAME = "canvas_cli"

Expand All @@ -29,7 +28,7 @@
def version_callback(value: bool) -> None:
"""Method called when the `--version` flag is set. Prints the version and exits the CLI."""
if value:
print.json(f"{APP_NAME} Version: {__version__}", version=__version__)
print(f"{APP_NAME} Version: {__version__}")
raise typer.Exit()


Expand Down

0 comments on commit 77d38f1

Please sign in to comment.