Skip to content

Commit

Permalink
Print status output in manage-cookie commands using loguru
Browse files Browse the repository at this point in the history
  • Loading branch information
smkent committed Feb 21, 2023
1 parent e9c0b0f commit 685a6ae
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 9 deletions.
19 changes: 19 additions & 0 deletions cookie_python/manage/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
from __future__ import annotations

import argparse
import sys
from enum import Enum
from pathlib import Path
from typing import Callable, Optional

from loguru import logger

from .release import release_action
from .update import update_action

Expand Down Expand Up @@ -33,7 +37,22 @@ def __new__(
return obj


def configure_logging() -> None:
logger.remove()
logger.add(
sys.stderr,
colorize=True,
format=(
f"<b>[{Path(sys.argv[0]).name}]</b>"
" <light-blue>{time:YYYY-MM-DD HH:mm:ss}</light-blue>"
" <light-magenta>{extra[repo]}</light-magenta>"
" <level>{message}</level>"
),
)


def main() -> None:
configure_logging()
ap = argparse.ArgumentParser()
ap.add_argument(
"action",
Expand Down
7 changes: 4 additions & 3 deletions cookie_python/manage/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def release_patch_version(repo: RepoSandbox) -> None:
latest_tag = tag
break
if not latest_tag:
print("Unable to find latest version")
repo.logger.warning("Unable to find latest version")
return None
check_refs = ["origin/main", latest_tag]
refs = []
Expand All @@ -33,14 +33,15 @@ def release_patch_version(repo: RepoSandbox) -> None:
.strip()
)
if len(refs) == len(check_refs) and len(set(refs)) == 1:
print(f"No new changes since latest release {latest_tag}")
repo.logger.info(f"No new changes since latest release {latest_tag}")
return None
sv = semver.VersionInfo.parse(latest_tag.lstrip("v"))
next_patch_ver = sv.bump_patch()
new_tag = f"v{next_patch_ver}"
if repo.dry_run:
print(f"Would release new version {new_tag}")
repo.logger.info(f"Would release new version {new_tag}")
return None
repo.logger.info(f"Releasing new version {new_tag}")
repo.run(["gh", "release", "create", new_tag, "--generate-notes"])
return None

Expand Down
14 changes: 11 additions & 3 deletions cookie_python/manage/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from types import TracebackType
from typing import Any, Optional

import loguru


class RepoSandbox:
def __init__(self, repo: str, dry_run: bool = False) -> None:
Expand All @@ -30,6 +32,10 @@ def __exit__(
) -> None:
self._stack.close()

@cached_property
def logger(self) -> "loguru.Logger":
return loguru.logger.bind(repo=self.repo)

@cached_property
def tempdir(self) -> Path:
return Path(
Expand Down Expand Up @@ -73,7 +79,7 @@ def run(

def shell(self) -> None:
if sys.__stdin__.isatty():
print('Starting shell. Run "exit 1" to abort.')
self.logger.info('Starting shell. Run "exit 1" to abort.')
self.run([os.environ.get("SHELL", "/bin/bash")])

def commit_changes(self, message: str) -> None:
Expand All @@ -95,6 +101,7 @@ def commit_changes(self, message: str) -> None:
]
)
self.lint_test()
self.logger.info("Committed changes")

def lint_test(self) -> None:
self.run(["poetry", "run", "poe", "lint"], check=False)
Expand All @@ -104,8 +111,8 @@ def lint_test(self) -> None:
try:
self.run(["poetry", "run", "poe", "test"])
except subprocess.CalledProcessError as e:
print(e)
print("Resolve errors and exit shell to continue")
self.logger.error(str(e))
self.logger.error("Resolve errors and exit shell to continue")
self.shell()

def open_pr(self, message: str) -> None:
Expand All @@ -129,3 +136,4 @@ def open_pr(self, message: str) -> None:
],
input=os.linesep.join(commit_body).encode("utf-8"),
)
self.logger.info("Opened PR")
12 changes: 9 additions & 3 deletions cookie_python/manage/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ def update_cruft(repo: RepoSandbox) -> Optional[str]:
)
if rej_files or conflicts:
if try_count == 0:
print(f">>> Conflicts found: {rej_files}")
print("Resolve conflicts and exit shell to continue")
repo.logger.error(f"Conflicts found: {rej_files}")
repo.logger.error(
"Resolve conflicts and exit shell to continue"
)
repo.shell()
continue
raise Exception(f"Unresolved conflicts: {rej_files}")
Expand Down Expand Up @@ -102,6 +104,7 @@ def update_dependencies(repo: RepoSandbox) -> Optional[str]:
def update_action(args: Namespace) -> None:
for repo_url in args.repo:
with RepoSandbox(repo_url, args.dry_run) as repo:
repo.logger.info("Starting update")
actions = []
msg_body = ""
cruft_msg = update_cruft(repo)
Expand All @@ -113,7 +116,10 @@ def update_action(args: Namespace) -> None:
msg_body += deps_msg
actions.append("dependencies")
if not msg_body:
repo.logger.info("Already up to date")
return None
message = f"Update {', '.join(actions)}\n\n{msg_body}"
actions_str = ", ".join(actions)
message = f"Update {actions_str}\n\n{msg_body}"
repo.logger.info(f"Updated {actions_str}")
repo.commit_changes(message)
repo.open_pr(message)

0 comments on commit 685a6ae

Please sign in to comment.