Skip to content

Commit

Permalink
refactor: bless codebase (#3)
Browse files Browse the repository at this point in the history
* chore: snake_case

* chore: remove unneeded f-strings

* chore: typos

* chore: bless codebase

* fix: oooopsss

* refactor: update logging
  • Loading branch information
hexiro authored Oct 31, 2021
1 parent e4f01f4 commit 224c328
Show file tree
Hide file tree
Showing 9 changed files with 129 additions and 121 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
__pycache__
__pycache__
.idea
.vscode
60 changes: 30 additions & 30 deletions __main__.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
from anilist_readme.graphql import grapql
from anilist_readme.actions_utils import actions_input, add_secret
from anilist_readme.config import ANILIST_QUERY
from anilist_readme.actions_utils import actionsInput, add_secret
from anilist_readme.list_activity import ListActivity, validLanguage
from anilist_readme.readme_actions import find_readme, open_readme, update_readme
from anilist_readme.git import git_add_commit_push
from anilist_readme.graphql import grapql
from anilist_readme.list_activity import ListActivity, validate_language
from anilist_readme.readme_actions import find_readme, open_readme, update_readme


def main(
user_id: str,
preferred_language: str,
max_post_count: str,
readme_path: str,
commit_message: str,
gh_token: str,
commit_email: str,
commit_username: str,
user_id: str,
preferred_language: str,
max_post_count: str,
readme_path: str,
commit_message: str,
gh_token: str,
commit_email: str,
commit_username: str,
):
validLanguage(preferred_language)
language = validate_language(preferred_language)

response = grapql(ANILIST_QUERY, {"id": int(user_id), "post_count": int(max_post_count)})
parsed = [ListActivity(activity, preferred_language) for activity in response["data"]["Page"]["activities"]]
parsed = [ListActivity(activity, language) for activity in response["data"]["Page"]["activities"]]
readme = open_readme(readme_path)
update_readme(readme, readme_path, parsed)
add_secret(gh_token)
git_add_commit_push(readme_path, commit_message, gh_token, commit_email, commit_username)


if __name__ == "__main__":
user_id: str = actionsInput("USER_ID", False)
preferred_language = actionsInput("PREFERRED_LANGUAGE", False)
max_post_count = int(actionsInput("MAX_POST_COUNT", False))
readme_path = actionsInput("README_PATH") or find_readme()
commit_message = actionsInput("COMMIT_MESSAGE", False)
gh_token = actionsInput("GH_TOKEN", False)
commit_email = actionsInput("COMMIT_EMAIL", False)
commit_username = actionsInput("COMMIT_USERNAME", False)
user_id = actions_input("USER_ID", optional=False)
preferred_language = actions_input("PREFERRED_LANGUAGE", optional=False)
max_post_count = actions_input("MAX_POST_COUNT", optional=False)
readme_path = actions_input("README_PATH", optional=True) or find_readme()
commit_message = actions_input("COMMIT_MESSAGE", optional=False)
gh_token = actions_input("GH_TOKEN", optional=False)
commit_email = actions_input("COMMIT_EMAIL", optional=False)
commit_username = actions_input("COMMIT_USERNAME", optional=False)

main(
user_id,
preferred_language,
max_post_count,
readme_path,
commit_message,
gh_token,
commit_email,
commit_username,
user_id=user_id,
preferred_language=preferred_language,
max_post_count=max_post_count,
readme_path=readme_path,
commit_message=commit_message,
gh_token=gh_token,
commit_email=commit_email,
commit_username=commit_username,
)
Empty file added anilist_readme/__init__.py
Empty file.
30 changes: 11 additions & 19 deletions anilist_readme/actions_utils.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,28 @@
from os import environ
import json
from typing import Union
from os import environ
from typing import Optional

from .config import CMD_STR


def actionsInput(value: str, optional: bool = True) -> Union[str, None]:
# remove all spaces to undersocres
def actions_input(value: str, optional: bool) -> Optional[str]:
# remove all spaces to underscores
value = value.replace(" ", "_")

# get the value in uppercase from env prefixed with INPUT_
try:
return environ[f"INPUT_{value.upper()}"]
except:
if optional:
return None
else:
raise ValueError(f"{value} is required")


def info(msg: str) -> None:
print(f"[INFO] {msg}")
output = environ.get(f"INPUT_{value.upper()}", default=None)

if output or optional:
return output

def error(msg: str) -> None:
print(f"[ERROR] {msg}")
raise ValueError(f"{value} is required")


def add_secret(secret: str) -> None:
print(f"{CMD_STR}add-mask{CMD_STR}{escapeData(secret)}")
print(f"{CMD_STR}add-mask{CMD_STR}{escape_data(secret)}")


def escapeData(data: str) -> str:
def escape_data(data: str) -> str:
data = json.dumps(data)
data = data.replace("%", "%25")
data = data.replace("\n", "%0A")
Expand Down
6 changes: 3 additions & 3 deletions anilist_readme/git.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from os import environ, system
from shlex import quote

from .actions_utils import info
from .logger import logger


def git_add_commit_push(readme_path: str, message: str, gh_token: str, email: str, username: str) -> None:
# commit the change and push to your repo
info(f"Commiting the changes")
logger.info("Committing the changes")

if environ.get("DEV") == "true":
# if we are in dev mode, we don't commit
Expand All @@ -17,4 +17,4 @@ def git_add_commit_push(readme_path: str, message: str, gh_token: str, email: st
system(f"git remote set-url origin https://{gh_token}@github.com/{environ['GITHUB_REPOSITORY']}.git")
system(f"git add {readme_path}")
system(f"git commit -m {quote(message)}")
system(f"git push")
system("git push")
48 changes: 25 additions & 23 deletions anilist_readme/graphql.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import httpx
from time import sleep
from .actions_utils import error, info

import httpx

from .logger import logger
from .config import ANILIST_ENDPOINT


Expand All @@ -9,27 +11,27 @@ def grapql(query: str, variables: "dict[str]" = None, retry: int = 5, delay: flo
Makes a graphql request to the ANILIST_ENDPOINT, and returns the response.
Uses query and variables in body
"""
info("Making a POST request to ANILIST_ENDPOINT")
logger.info("Making a POST request to ANILIST_ENDPOINT")

# make the requets
# make the requests
res = httpx.post(ANILIST_ENDPOINT, json={"query": query, "variables": variables})

if res.is_error:
# if the request is not ok, retry
if retry > 0:
# wait for a while
sleep(delay)
error(f"Error making graphql request: {res.status_code}, tries left: {retry}")

# retry
return grapql(
query,
variables,
retry - 1,
delay * 2,
)
# if the request is not ok, and retry is 0, return the error
else:
raise Exception(f"Error making graphql request: {res.status_code}")

return res.json()
if not res.is_error:
return res.json()

# if the request is not ok, and retry is 0, return the error
if retry <= 0:
res.raise_for_status()

# if the request is not ok, retry
# wait for a while
sleep(delay)
logger.error(f"Error making graphql request: {res.status_code}, tries left: {retry}")

# retry
return grapql(
query=query,
variables=variables,
retry=retry - 1,
delay=delay * 2,
)
25 changes: 16 additions & 9 deletions anilist_readme/list_activity.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
from typing import Literal
from .config import EMOJI_DICT
from datetime import datetime
from enum import auto, Enum

from .config import EMOJI_DICT


prefferd_lang_type = Literal["romaji", "english", "native"]
prefferd_lang_tuple = ("romaji", "english", "native")
class Language(Enum):
romanji = auto()
english = auto()
native = auto()


def validLanguage(lang: str):
def validate_language(lang: str) -> Language:
"""
Check if the language is valid.
"""
if lang not in prefferd_lang_tuple:
raise ValueError(f"'{lang}'' is not a valid language. Must be: '{', '.join(prefferd_lang_tuple)}'")
languages = [x.name for x in Language]
if lang in languages:
return Language[lang]
raise ValueError(f"'{lang}'' is not a valid language. Must be: '{', '.join(languages)}'")


class ListActivity:
def __init__(self, activity_data: dict, preffered_lang: prefferd_lang_type = None) -> None:
def __init__(self, activity_data: dict, preferred_lang: Language = None) -> None:
self.type: str = activity_data["type"]
self.created_at = datetime.utcfromtimestamp(activity_data["createdAt"]).strftime("%H:%M, %d %B %Y")
self.progress: str = activity_data["progress"]
self.status: str = activity_data["status"]
self.title: str = (
activity_data["media"]["title"][preffered_lang or "english"] or activity_data["media"]["title"]["romaji"]
activity_data["media"]["title"][preferred_lang.name or "english"] or
activity_data["media"]["title"]["romaji"]
)
self.url: str = activity_data["media"]["siteUrl"]

Expand Down
10 changes: 10 additions & 0 deletions anilist_readme/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import logging

logger = logging.getLogger("AniList")
logger.setLevel(logging.INFO)

handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(fmt='%(asctime)s [%(levelname)s] - %(name)s: %(message)s',
datefmt="%x %X"))

logger.addHandler(handler)
67 changes: 31 additions & 36 deletions anilist_readme/readme_actions.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,64 @@
from os import environ, walk, path
from .list_activity import ListActivity
from .actions_utils import info
import pathlib
from os import environ

from .logger import logger
from .config import COMMENT_TEMPLATE
from .list_activity import ListActivity


def find_readme():
def find_readme() -> str:
"""
Find the readme file in the given current directory.
"""
info("Searching for the readme file...")
readme_path = None
logger.info("Searching for the readme file...")

for root, dirs, files in walk("."):
for file in files:
if file.lower() == "readme.md":
readme_path = path.join(root, file)
break
path = pathlib.Path(".")
files = list(path.rglob("readme.*"))

if readme_path:
info(f"Found readme file at: '{readme_path}'")
return readme_path
else:
raise FileNotFoundError("Unable to find readme file.")
if files:
return str(files[0])

raise FileNotFoundError("Unable to find readme file.")

def open_readme(readme: str):

def open_readme(readme: str) -> "list[str]":
"""
Open the readme file and return the contents as a string.
"""
info(f"Opening readme in '{readme}'")
logger.info(f"Opening readme in '{readme}'")

with open(readme, "r") as file:
opened = file.read()
readme_contents = opened.splitlines()

return readme_contents
return opened.splitlines()


def update_readme(readme_content: "list[str]", readme_path: str, activity_list: "list[ListActivity]"):
def update_readme(readme_content: "list[str]", readme_path: str, activity_list: "list[ListActivity]") -> None:
"""
Update the readme file with the given contents.
"""
info(f"Updating the readme contents")
logger.info("Updating the readme contents")

if environ.get("DEV") == "true":
# if we are in dev mode, we don't commit
return

indexes = readme_comment_indexes(readme_content)
top_part = "\n".join(readme_content[: (indexes[0] + 1)])
bottom_part = "\n".join(readme_content[indexes[1] :])
start_index, end_index = readme_comment_indexes(readme_content)
top_part = "\n".join(readme_content[:start_index + 1])
bottom_part = "\n".join(readme_content[end_index:])

with open(readme_path, "w") as file:
new_content = (
top_part
+ "\n\n"
+ "\n".join(map(lambda activity: str(activity), activity_list))
+ "\n\n"
+ bottom_part
+ "\n"
top_part
+ "\n\n"
+ "\n".join(map(lambda activity: str(activity), activity_list))
+ "\n\n"
+ bottom_part
+ "\n"
)
file.write(new_content)


def readme_comment_indexes(readme: "list[str]"):
def readme_comment_indexes(readme: "list[str]") -> "tuple[int, int]":
"""
Get index of comments generated from the COMMENT_TEMPLATE in the readme.
"""
Expand All @@ -73,6 +68,6 @@ def readme_comment_indexes(readme: "list[str]"):
end_index = trimmed.index(COMMENT_TEMPLATE.format("end"))

if start_index != -1 and end_index != -1:
return [start_index, end_index]
else:
raise ValueError("Unable to find start and end comments in readme file.")
return start_index, end_index

raise ValueError("Unable to find start and end comments in readme file.")

0 comments on commit 224c328

Please sign in to comment.