Skip to content

Commit

Permalink
[LOGGER] Separate logger instance by module and fix force remove bug (#…
Browse files Browse the repository at this point in the history
…184)

* feat (logger): separate logger instance by module and fix force remove bug

* fix: types
  • Loading branch information
seyLu authored Jun 17, 2024
1 parent 44f1c61 commit ad0e5af
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 70 deletions.
50 changes: 50 additions & 0 deletions src/ghlabel/__logger__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import logging
import os
from logging import Logger
from logging.config import fileConfig

import rich

from ghlabel.config import is_ghlabel_debug_mode

GHLABEL_LOGS_DIR: str = os.path.join("logs")


class GhlabelLogger:
def __init__(self) -> None:
self.logger: GhlabelLogger

if not os.path.isdir(GHLABEL_LOGS_DIR):
os.makedirs(GHLABEL_LOGS_DIR)
fileConfig(os.path.join(os.path.dirname(__file__), "logging.ini"))

def init(self, module_name: str) -> "GhlabelLogger":
"""NOTE: pass in __name__ as module name"""
logger: Logger = logging.getLogger(module_name)

if is_ghlabel_debug_mode():
logger.setLevel(level=logging.DEBUG)
else:
logger.setLevel(level=logging.ERROR)

self.logger = logger # type: ignore[assignment]
return self.logger

def exception(self, ex: Exception) -> None:
rich.print(
f"\nSomething went wrong. See logs ([blue underline]{GHLABEL_LOGS_DIR}[/blue underline]) for more details.\n"
)
rich.print(" [[red]Exception[/red]]:", str(ex))
self.logger.exception(ex)

def error(self, message: str) -> None:
self.logger.error(message)

def warning(self, message: str) -> None:
self.logger.warning(message)

def info(self, message: str) -> None:
self.logger.info(message)


ghlabel_logger: GhlabelLogger = GhlabelLogger()
21 changes: 12 additions & 9 deletions src/ghlabel/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
__status__ = "Prototype"

import json
import logging
import os
import time
from enum import Enum
Expand All @@ -21,11 +20,9 @@
from rich.progress import Progress, SpinnerColumn, TextColumn

from ghlabel.__about__ import __version__
from ghlabel.utils.dump_label import DumpLabel
from ghlabel.utils.github_api import GithubApi
from ghlabel.config import set_ghlabel_debug_mode
from ghlabel.utils.github_api_types import GithubLabel
from ghlabel.utils.helpers import clear_screen, validate_env
from ghlabel.utils.setup_github_label import SetupGithubLabel


def parse_remove_labels(label_names: str | None) -> set[str] | None:
Expand Down Expand Up @@ -70,6 +67,7 @@ class RemoveAllChoices(str, Enum):
context_settings={
"help_option_names": ["-h", "--help"],
},
no_args_is_help=True,
)


Expand Down Expand Up @@ -153,6 +151,9 @@ def setup_labels( # noqa: PLR0913
),
] = False,
) -> None:
from ghlabel.utils.github_api import GithubApi
from ghlabel.utils.setup_github_label import SetupGithubLabel

if not token:
token = validate_env("GITHUB_TOKEN")
if not repo_owner:
Expand Down Expand Up @@ -244,6 +245,8 @@ def app_dump(
),
] = AppChoices.app.value, # type: ignore[assignment]
) -> None:
from ghlabel.utils.dump_label import DumpLabel

clear_screen()
with Progress(
SpinnerColumn(),
Expand All @@ -255,7 +258,9 @@ def app_dump(
DumpLabel.dump(labels_dir=labels_dir, new=new, ext=ext.value, app=app.value)
time.sleep(0.5)

rich.print(f"[green]Successfully[/green] dumped labels config to `{labels_dir}`.")
rich.print(
f"[green]Successfully[/green] dumped labels config to {os.path.join(os.getcwd(), labels_dir)}"
)


@app.callback() # type: ignore[misc]
Expand All @@ -275,15 +280,13 @@ def app_callback(
typer.Option(
"--debug",
"-D",
is_eager=True,
help="Enable debug mode and show logs.",
),
] = False,
) -> None:
"""Setup Github Labels from a yaml/json config file."""

if not debug:
logger = logging.getLogger("root")
logger.setLevel(logging.ERROR)
set_ghlabel_debug_mode(debug)


if __name__ == "__main__":
Expand Down
11 changes: 11 additions & 0 deletions src/ghlabel/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
g_GHLABEL_DEBUG_MODE = False


def set_ghlabel_debug_mode(is_debug: bool) -> None:
global g_GHLABEL_DEBUG_MODE # noqa: PLW0603
g_GHLABEL_DEBUG_MODE = is_debug


def is_ghlabel_debug_mode() -> bool:
global g_GHLABEL_DEBUG_MODE # noqa: PLW0602
return g_GHLABEL_DEBUG_MODE
2 changes: 1 addition & 1 deletion src/ghlabel/logging.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
keys=root

[logger_root]
level=DEBUG
level=INFO
handlers=screen,file

[formatters]
Expand Down
13 changes: 6 additions & 7 deletions src/ghlabel/utils/dump_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@
__status__ = "Prototype"

import json
import logging
import os
from dataclasses import dataclass
from logging.config import fileConfig
from pathlib import Path
from typing import TypedDict

import yaml

Path("logs").mkdir(exist_ok=True)
fileConfig(os.path.join(os.path.dirname(__file__), "../logging.ini"))
from ghlabel.__logger__ import GhlabelLogger, ghlabel_logger

logger: GhlabelLogger = ghlabel_logger.init(__name__)


@dataclass(frozen=True)
Expand Down Expand Up @@ -267,7 +266,7 @@ class GameDevLabels(Labels):
class DumpLabel:
@staticmethod
def _init_labels_dir(labels_dir: str = "labels") -> None:
logging.info(f"Initializing {labels_dir} dir.")
logger.info(f"Initializing {os.path.join(os.getcwd(), labels_dir)} dir.")
Path(labels_dir).mkdir(exist_ok=True)
for filename in os.listdir(labels_dir):
file_path: str = os.path.join(labels_dir, filename)
Expand All @@ -293,7 +292,7 @@ def dump(
label_file: str = os.path.join(labels_dir, f"{field.lower()}_labels.{ext}")

with open(label_file, "w+") as f:
logging.info(f"Dumping to {f.name}.")
logger.info(f"Dumping to {f.name}.")

if ext == "yaml":
print(
Expand All @@ -307,7 +306,7 @@ def dump(
elif ext == "json":
json.dump(labels, f, indent=2)

logging.info("Finished dumping of labels.")
logger.info("Finished dumping of labels.")


if __name__ == "__main__":
Expand Down
45 changes: 20 additions & 25 deletions src/ghlabel/utils/github_api.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import logging
import os
import sys
from logging.config import fileConfig
from pathlib import Path

import requests
from requests.exceptions import HTTPError, Timeout
from requests.models import Response

from ghlabel.__logger__ import GhlabelLogger, ghlabel_logger
from ghlabel.utils.github_api_types import (
GithubIssue,
GithubIssueParams,
Expand All @@ -17,8 +14,7 @@
)
from ghlabel.utils.helpers import STATUS_OK, validate_env

Path("logs").mkdir(exist_ok=True)
fileConfig(os.path.join(os.path.dirname(__file__), "../logging.ini"))
logger: GhlabelLogger = ghlabel_logger.init(__name__)


class GithubApi:
Expand Down Expand Up @@ -62,13 +58,13 @@ def list_labels(self) -> tuple[list[GithubLabel], StatusCode]:
per_page: int = 100
res: Response

logging.info(
logger.info(
f"Fetching list of github labels from `{self.repo_owner}/{self.repo_name}`."
)
github_labels: list[GithubLabel] = []
while True:
params: dict[str, int] = {"page": page, "per_page": per_page}
logging.info(f"Fetching page {page}.")
logger.info(f"Fetching page {page}.")
try:
res = requests.get(
url,
Expand All @@ -78,12 +74,12 @@ def list_labels(self) -> tuple[list[GithubLabel], StatusCode]:
)
res.raise_for_status()
except Timeout:
logging.error(
logger.error(
"The site can't be reached, `github.com` took to long to respond. Try checking the connection."
)
break
except HTTPError:
logging.error(
logger.error(
f"Failed to fetch list of github labels. Check if token has permission to access `{self.repo_owner}/{self.repo_name}`."
)
break
Expand All @@ -109,16 +105,16 @@ def create_label(self, label: GithubLabel) -> tuple[GithubLabel, StatusCode]:
)
res.raise_for_status()
except Timeout:
logging.error(
logger.error(
"The site can't be reached, `github.com` took to long to respond. Try checking the connection."
)
sys.exit()
except HTTPError:
logging.error(
logger.error(
f"Failed to add label `{label['name']}`. Check the label format."
)
else:
logging.info(f"Label `{label['name']}` added successfully.")
logger.info(f"Label `{label['name']}` added successfully.")

return res.json(), res.status_code

Expand All @@ -136,17 +132,16 @@ def update_label(self, label: GithubLabel) -> tuple[GithubLabel, StatusCode]:
)
res.raise_for_status()
except Timeout:
logging.error(
logger.error(
"The site can't be reached, `github.com` took to long to respond. Try checking the connection."
)
sys.exit()
except HTTPError as ex:
logging.exception(ex)
logging.error(
except HTTPError:
logger.error(
f"Failed to update label `{label['new_name']}`. Check the label format."
)
else:
logging.info(f"Label `{label['new_name']}` updated successfully.")
logger.info(f"Label `{label['new_name']}` updated successfully.")

return res.json(), res.status_code

Expand All @@ -162,14 +157,14 @@ def delete_label(self, label_name: str) -> tuple[None, StatusCode]:
)
res.raise_for_status()
except Timeout:
logging.error(
logger.error(
"The site can't be reached, `github.com` took to long to respond. Try checking the connection."
)
sys.exit()
except HTTPError:
logging.error(f"Failed to delete label `{label_name}`.")
logger.error(f"Failed to delete label `{label_name}`.")
else:
logging.info(f"Label `{label_name}` deleted successfully.")
logger.info(f"Label `{label_name}` deleted successfully.")

return None, res.status_code

Expand All @@ -193,14 +188,14 @@ def list_issues(
page: int = 1
per_page: int = 100

logging.info(
logger.info(
f"Fetching list of github issues from `{self.repo_owner}/{self.repo_name}`."
)
github_issues: list[GithubIssue] = []
while True:
params["page"] = page
params["per_page"] = per_page
logging.info(f"Fetching page {page}.")
logger.info(f"Fetching page {page}.")
try:
res = requests.get(
url,
Expand All @@ -210,12 +205,12 @@ def list_issues(
)
res.raise_for_status()
except Timeout:
logging.error(
logger.error(
"The site can't be reached, `github.com` took to long to respond. Try checking the connection."
)
sys.exit()
except HTTPError:
logging.error(
logger.error(
f"Failed to fetch list of github issues. Check if token has permission to access `{self.repo_owner}/{self.repo_name}`."
)
sys.exit()
Expand Down
24 changes: 12 additions & 12 deletions src/ghlabel/utils/helpers.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
import logging
import os
import platform
import subprocess
import sys
from logging.config import fileConfig
from pathlib import Path

from dotenv import load_dotenv
from dotenv import find_dotenv, load_dotenv

load_dotenv()
Path("logs").mkdir(exist_ok=True)
fileConfig(os.path.join(os.path.dirname(__file__), "../logging.ini"))
from ghlabel.__logger__ import GhlabelLogger, ghlabel_logger
from ghlabel.config import is_ghlabel_debug_mode

logger: GhlabelLogger = ghlabel_logger.init(__name__)
load_dotenv(find_dotenv(usecwd=True))

STATUS_OK: int = 200


def validate_env(env: str) -> str:
_env: str | None = os.getenv(env)
if not _env:
logging.error(f"{env} environment variable not set.")
logger.error(f"{env} environment variable not set.")
sys.exit()
return _env


def clear_screen() -> None:
if platform.system() == "Windows":
subprocess.run("cls", shell=True, check=False) # noqa: S607, S602
else:
subprocess.run("clear", shell=True, check=False) # noqa: S607, S602
if not is_ghlabel_debug_mode():
if platform.system() == "Windows":
subprocess.run("cls", shell=True, check=False) # noqa: S607, S602
else:
subprocess.run("clear", shell=True, check=False) # noqa: S607, S602
Loading

0 comments on commit ad0e5af

Please sign in to comment.