Skip to content

Commit

Permalink
Change: Improve error output
Browse files Browse the repository at this point in the history
Raise MattermostNotifyError instead of printing to terminal. This avoids
having to pass a terminal to the functions.
  • Loading branch information
bjoernricks committed Jul 19, 2023
1 parent a42918c commit 3489e00
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 38 deletions.
7 changes: 7 additions & 0 deletions mattermost_notify/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# SPDX-FileCopyrightText: 2023 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later


class MattermostNotifyError(Exception):
"""Base error for all errors originating from mattermost-notify"""
63 changes: 32 additions & 31 deletions mattermost_notify/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import httpx
from pontos.terminal.terminal import ConsoleTerminal

from mattermost_notify.errors import MattermostNotifyError
from mattermost_notify.parser import parse_args
from mattermost_notify.status import Status

Expand All @@ -34,7 +35,7 @@ def linker(name: str, url: Optional[str] = None) -> str:
return f"[{name}]({url})" if url else name


def get_github_event_json(term: ConsoleTerminal) -> dict[str, Any]:
def get_github_event_json() -> dict[str, Any]:
github_event_path = os.environ.get("GITHUB_EVENT_PATH")

if not github_event_path:
Expand All @@ -46,11 +47,9 @@ def get_github_event_json(term: ConsoleTerminal) -> dict[str, Any]:
with json_path.open("r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
term.error("Could not find GitHub Event JSON file.")
raise MattermostNotifyError("Could not find GitHub Event JSON file.")
except json.JSONDecodeError:
term.error("Could not decode the JSON object.")

return {}
raise MattermostNotifyError("Could not decode the JSON object.")


def fill_template(
Expand All @@ -64,12 +63,11 @@ def fill_template(
status: Optional[str] = None,
workflow_id: Optional[str] = None,
workflow_name: Optional[str] = None,
terminal: ConsoleTerminal,
) -> str:
template = SHORT_TEMPLATE if short else LONG_TEMPLATE

# try to get information from the GiTHUB_EVENT json
event = get_github_event_json(terminal)
event = get_github_event_json()
workflow_info: dict[str, Any] = event.get("workflow_run", {})

status = status if status else workflow_info.get("conclusion")
Expand Down Expand Up @@ -130,30 +128,33 @@ def main() -> None:

term = ConsoleTerminal()

if not parsed_args.free:
body = fill_template(
highlight=parsed_args.highlight,
short=parsed_args.short,
branch=parsed_args.branch,
commit=parsed_args.commit,
repository=parsed_args.repository,
status=parsed_args.status,
workflow_id=parsed_args.workflow,
workflow_name=parsed_args.workflow_name,
terminal=term,
)

data = {"channel": parsed_args.channel, "text": body}
else:
data = {"channel": parsed_args.channel, "text": parsed_args.free}

response = httpx.post(url=parsed_args.url, json=data)
if response.is_success:
term.ok(
f"Successfully posted on Mattermost channel {parsed_args.channel}"
)
else:
term.error("Failed to post on Mattermost")
try:
if not parsed_args.free:
body = fill_template(
highlight=parsed_args.highlight,
short=parsed_args.short,
branch=parsed_args.branch,
commit=parsed_args.commit,
repository=parsed_args.repository,
status=parsed_args.status,
workflow_id=parsed_args.workflow,
workflow_name=parsed_args.workflow_name,
)

data = {"channel": parsed_args.channel, "text": body}
else:
data = {"channel": parsed_args.channel, "text": parsed_args.free}

response = httpx.post(url=parsed_args.url, json=data)
if response.is_success:
term.ok(
"Successfully posted on Mattermost channel "
f"{parsed_args.channel}"
)
else:
term.error("Failed to post on Mattermost")
except MattermostNotifyError as e:
term.error(f"❌ Error: {e}")


if __name__ == "__main__":
Expand Down
8 changes: 1 addition & 7 deletions tests/test_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def test_success_no_highlight(self):
actual = fill_template(
highlight=["user1", "user2"],
status=Status.SUCCESS.name,
terminal=MagicMock(),
)
expected = """#### Status: :white_check_mark: success
Expand All @@ -42,7 +41,6 @@ def test_failure_highlight(self):
actual = fill_template(
highlight=["user1", "user2"],
status=Status.FAILURE.name,
terminal=MagicMock(),
)
expected = """#### Status: :x: failure
Expand All @@ -66,7 +64,6 @@ def test_short_template(self):
commit_message="Add foo",
repository="foo/bar",
branch="main",
terminal=MagicMock(),
)
expected = (
":white_check_mark: success: [SomeWorkflow](https://github.com/foo/bar/actions/runs/w1) "
Expand All @@ -85,7 +82,6 @@ def test_template(self):
commit_message="Add foo",
repository="foo/bar",
branch="main",
terminal=MagicMock(),
)
expected = """#### Status: :white_check_mark: success
Expand Down Expand Up @@ -114,9 +110,7 @@ def test_template_data_from_github_event(self, mock: MagicMock):
}
mock.return_value = event

actual = fill_template(
terminal=MagicMock(),
)
actual = fill_template()
expected = """#### Status: :white_check_mark: success
| Workflow | [SomeWorkflow](https://github.com/foo/bar/actions/runs/w1) |
Expand Down

0 comments on commit 3489e00

Please sign in to comment.