Skip to content

Commit

Permalink
[SCRIPT-14] Add loaders for frontend CLI (#50)
Browse files Browse the repository at this point in the history
* feat: add spinner

* feat: autocreate labels and logs dir if not exist
  • Loading branch information
seyLu authored Sep 8, 2023
1 parent 304ded4 commit cef3a38
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 36 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# logging
log/*
!log/.gitignore
logs

# VS Code config
.vscode/
Expand Down
72 changes: 51 additions & 21 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
import json
import logging
import os
import time
from enum import Enum
from typing import Annotated, Optional

import typer
from rich.progress import Progress, SpinnerColumn, TextColumn

from scripts.dump_label import DumpLabel
from scripts.setup_github_label import GithubConfig, GithubLabel
Expand Down Expand Up @@ -125,25 +127,44 @@ def setup_labels(
),
] = RemoveAllChoices.disable.value, # type: ignore[assignment]
) -> None:
if token:
GithubConfig.set_PERSONAL_ACCESS_TOKEN(token)
if repo_owner:
GithubConfig.set_REPO_OWNER(repo_owner)
if repo_name:
GithubConfig.set_REPO_NAME(repo_name)

github_config = GithubConfig()

github_label = GithubLabel(github_config=github_config, dir=dir)
if remove_all.value == "enable":
github_label.remove_all_labels()
elif remove_all.value == "silent":
github_label.remove_all_labels(silent=True)
elif remove_all.value == "disable":
github_label.remove_labels(
strict=strict, labels=parse_remove_labels(remove_labels)
)
github_label.create_labels(labels=parse_add_labels(add_labels))
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
progress.add_task(description="[green]Fetching...", total=None)
if token:
GithubConfig.set_PERSONAL_ACCESS_TOKEN(token)
if repo_owner:
GithubConfig.set_REPO_OWNER(repo_owner)
if repo_name:
GithubConfig.set_REPO_NAME(repo_name)
github_config = GithubConfig()

github_label = GithubLabel(github_config=github_config, dir=dir)

with Progress(
SpinnerColumn(style="[magenta]"),
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
progress.add_task(description="[magenta]Removing...", total=None)
if remove_all.value == "enable":
github_label.remove_all_labels()
elif remove_all.value == "silent":
github_label.remove_all_labels(silent=True)
elif remove_all.value == "disable":
github_label.remove_labels(
strict=strict, labels=parse_remove_labels(remove_labels)
)

with Progress(
SpinnerColumn(style="[cyan]"),
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
progress.add_task(description="[cyan]Adding...", total=None)
github_label.add_labels(labels=parse_add_labels(add_labels))


@app.command("dump") # type: ignore[misc]
Expand Down Expand Up @@ -183,7 +204,15 @@ def app_dump(
),
] = AppChoices.app.value, # type: ignore[assignment]
) -> None:
DumpLabel.dump(dir=dir, new=new, ext=ext.value, app=app.value)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
progress.add_task(description="Dumping...", total=None)
time.sleep(0.5)
DumpLabel.dump(dir=dir, new=new, ext=ext.value, app=app.value)
time.sleep(0.5)


@app.callback() # type: ignore[misc]
Expand All @@ -206,7 +235,8 @@ def app_callback(
] = False,
) -> None:
if not debug:
logging.getLogger("root").setLevel(logging.ERROR)
logger = logging.getLogger("root")
logger.setLevel(logging.ERROR)


if __name__ == "__main__":
Expand Down
2 changes: 0 additions & 2 deletions log/.gitignore

This file was deleted.

4 changes: 2 additions & 2 deletions logging.ini
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ handlers=screen,file
keys=simple,verbose

[formatter_simple]
format=%(asctime)s [%(levelname)s] %(name)s: %(message)s
format=[%(levelname)s]: %(message)s

[formatter_verbose]
format=[%(asctime)s] %(levelname)s [%(filename)s %(name)s %(funcName)s (%(lineno)d)]: %(message)s
Expand All @@ -23,7 +23,7 @@ interval=midnight
backupCount=5
formatter=verbose
level=WARNING
args=('log/debug.log',)
args=('logs/debug.log',)

[handler_screen]
class=StreamHandler
Expand Down
3 changes: 3 additions & 0 deletions scripts/dump_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
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("logging.ini")


Expand Down Expand Up @@ -266,6 +268,7 @@ class DumpLabel:
@staticmethod
def _init_dir(dir: str = "labels") -> None:
logging.info(f"Initializing {dir} dir.")
Path(dir).mkdir(exist_ok=True)
for filename in os.listdir(dir):
file_path: str = os.path.join(dir, filename)
if os.path.isfile(file_path):
Expand Down
22 changes: 13 additions & 9 deletions scripts/setup_github_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import os
import sys
from logging.config import fileConfig
from pathlib import Path
from typing import Any

import requests
Expand All @@ -26,6 +27,7 @@
from requests.models import Response

load_dotenv()
Path("logs").mkdir(exist_ok=True)
fileConfig("logging.ini")


Expand Down Expand Up @@ -89,8 +91,10 @@ def __init__(
self._github_label_names: list[str] = [
github_label["name"] for github_label in self.github_labels
]
self._labels: list[dict[str, str]] = self._load_labels_from_config()
self._labels_to_remove: list[str] = self._load_labels_to_remove_from_config()
self._labels: list[dict[str, str]] = self._load_labels_from_config() or []
self._labels_to_remove: list[str] = (
self._load_labels_to_remove_from_config() or []
)

@property
def dir(self) -> str:
Expand Down Expand Up @@ -317,8 +321,8 @@ def remove_labels(
else:
logging.info(f"Label `{remove_label}` deleted successfully.")

def create_labels(self, labels: list[dict[str, str]] | None = None) -> None:
create_labels: list[dict[str, str]] = self.labels
def add_labels(self, labels: list[dict[str, str]] | None = None) -> None:
add_labels: list[dict[str, str]] = self.labels

if labels:
for _i, label in enumerate(labels, start=1):
Expand All @@ -328,15 +332,15 @@ def create_labels(self, labels: list[dict[str, str]] | None = None) -> None:
)
sys.exit()

create_labels.append(
add_labels.append(
{
"name": label["name"],
"color": label.get("color", "").replace("#", ""),
"description": label.get("description", ""),
}
)

for label in create_labels:
for label in add_labels:
if label["name"] not in self.labels_to_remove:
if label["name"] in self.github_label_names:
i: int = self.github_label_names.index(label["name"])
Expand All @@ -356,18 +360,18 @@ def create_labels(self, labels: list[dict[str, str]] | None = None) -> None:

if res.status_code != 201:
logging.error(
f"Status {res.status_code}. Failed to create label `{label['name']}`."
f"Status {res.status_code}. Failed to add label `{label['name']}`."
)
else:
logging.info(f"Label `{label['name']}` created successfully.")
logging.info(f"Label `{label['name']}` added successfully.")

logging.info("Label creation process completed.")


def main() -> None:
github_label = GithubLabel()
github_label.remove_labels(strict=True)
github_label.create_labels()
github_label.add_labels()


if __name__ == "__main__":
Expand Down

0 comments on commit cef3a38

Please sign in to comment.