mirror of
https://github.com/revanced/revanced-static-api.git
synced 2025-04-29 22:24:37 +02:00
refactor: black formatting
This commit is contained in:
parent
07dc65e1ee
commit
1beb377b4b
171
src/app/api.py
171
src/app/api.py
@ -2,96 +2,113 @@ from abc import abstractmethod
|
||||
|
||||
import requests
|
||||
|
||||
class Api():
|
||||
_api_key: str
|
||||
|
||||
@abstractmethod
|
||||
def __init__(self, api_key: str = None) -> None:
|
||||
self._api_key: str = api_key
|
||||
|
||||
@abstractmethod
|
||||
def get_release(self, repository: str, all: bool = False, prerelease: bool = False) -> dict | list:
|
||||
'''Gets the release(s) for a repository.
|
||||
|
||||
Args:
|
||||
repository (str): The repository to get releases for.
|
||||
all (bool, optional): Whether to get all releases or not. Defaults to False.
|
||||
prerelease (bool, optional): Whether to get prereleases or not. Defaults to False.
|
||||
Returns:
|
||||
dict | list: The release(s) for the repository.
|
||||
'''
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def get_contributor(self, repository):
|
||||
'''Gets the contributors for a repository.
|
||||
class Api:
|
||||
_api_key: str
|
||||
|
||||
@abstractmethod
|
||||
def __init__(self, api_key: str = None) -> None:
|
||||
self._api_key: str = api_key
|
||||
|
||||
@abstractmethod
|
||||
def get_release(
|
||||
self, repository: str, all: bool = False, prerelease: bool = False
|
||||
) -> dict | list:
|
||||
"""Gets the release(s) for a repository.
|
||||
|
||||
Args:
|
||||
repository (str): The repository to get releases for.
|
||||
all (bool, optional): Whether to get all releases or not. Defaults to False.
|
||||
prerelease (bool, optional): Whether to get prereleases or not. Defaults to False.
|
||||
Returns:
|
||||
dict | list: The release(s) for the repository.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def get_contributor(self, repository):
|
||||
"""Gets the contributors for a repository.
|
||||
|
||||
Args:
|
||||
repository (str): The repository to get contributors for.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
Args:
|
||||
repository (str): The repository to get contributors for.
|
||||
'''
|
||||
raise NotImplementedError
|
||||
|
||||
class GitHubApi(Api):
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
def get_contributor(self, repository):
|
||||
def transform_contributor(contributor: dict) -> dict:
|
||||
'''Transforms a contributor into a dict.
|
||||
def get_contributor(self, repository):
|
||||
def transform_contributor(contributor: dict) -> dict:
|
||||
"""Transforms a contributor into a dict.
|
||||
|
||||
Args:
|
||||
contributor (dict): The contributor to transform.
|
||||
Args:
|
||||
contributor (dict): The contributor to transform.
|
||||
|
||||
Returns:
|
||||
dict: The transformed contributor.
|
||||
'''
|
||||
Returns:
|
||||
dict: The transformed contributor.
|
||||
"""
|
||||
|
||||
return {
|
||||
'username': contributor['login'],
|
||||
'avatar': contributor['avatar_url'], # TODO: Proxy via a CDN.
|
||||
'link': contributor['html_url'],
|
||||
'contributions': contributor['contributions']
|
||||
}
|
||||
return {
|
||||
"username": contributor["login"],
|
||||
"avatar": contributor["avatar_url"], # TODO: Proxy via a CDN.
|
||||
"link": contributor["html_url"],
|
||||
"contributions": contributor["contributions"],
|
||||
}
|
||||
|
||||
def sort_and_delete_key(contributor: dict) -> int:
|
||||
contributions = contributor['contributions']
|
||||
del contributor['contributions']
|
||||
return contributions
|
||||
def sort_and_delete_key(contributor: dict) -> int:
|
||||
contributions = contributor["contributions"]
|
||||
del contributor["contributions"]
|
||||
return contributions
|
||||
|
||||
contributors = requests.get(f'https://api.github.com/repos/{repository}/contributors').json()
|
||||
contributors = list(map(transform_contributor, contributors)) # List might not be needed.
|
||||
contributors.sort(key=sort_and_delete_key, reverse=True)
|
||||
contributors = requests.get(
|
||||
f"https://api.github.com/repos/{repository}/contributors"
|
||||
).json()
|
||||
contributors = list(
|
||||
map(transform_contributor, contributors)
|
||||
) # List might not be needed.
|
||||
contributors.sort(key=sort_and_delete_key, reverse=True)
|
||||
|
||||
return contributors
|
||||
return contributors
|
||||
|
||||
def get_release(self, repository: str, all: bool = False, prerelease: bool = False) -> dict | list:
|
||||
def transform_release(release: dict) -> dict:
|
||||
'''Transforms a release dict into a dict.
|
||||
def get_release(
|
||||
self, repository: str, all: bool = False, prerelease: bool = False
|
||||
) -> dict | list:
|
||||
def transform_release(release: dict) -> dict:
|
||||
"""Transforms a release dict into a dict.
|
||||
|
||||
Args:
|
||||
release (dict): The release dict to transform.
|
||||
Args:
|
||||
release (dict): The release dict to transform.
|
||||
|
||||
Returns:
|
||||
dict: The transformed release dict.
|
||||
'''
|
||||
Returns:
|
||||
dict: The transformed release dict.
|
||||
"""
|
||||
|
||||
return {
|
||||
# TODO: Check if theres any need for this: 'id': release['id'].
|
||||
'tag': release['tag_name'],
|
||||
'prerelease': release['prerelease'],
|
||||
'published_at': release['published_at'],
|
||||
'assets': [
|
||||
{
|
||||
'name': asset['name'],
|
||||
'download_url': asset['browser_download_url'] # TODO: Proxy via a CDN.
|
||||
} for asset in release['assets']
|
||||
]
|
||||
}
|
||||
return {
|
||||
# TODO: Check if theres any need for this: 'id': release['id'].
|
||||
"tag": release["tag_name"],
|
||||
"prerelease": release["prerelease"],
|
||||
"published_at": release["published_at"],
|
||||
"assets": [
|
||||
{
|
||||
"name": asset["name"],
|
||||
"download_url": asset[
|
||||
"browser_download_url"
|
||||
], # TODO: Proxy via a CDN.
|
||||
}
|
||||
for asset in release["assets"]
|
||||
],
|
||||
}
|
||||
|
||||
# A little bit of code duplication but more readable than a ternary operation.
|
||||
if all:
|
||||
releases: list = requests.get(f'https://api.github.com/repos/{repository}/releases').json()
|
||||
return list(map(transform_release, releases)) # List might not be needed.
|
||||
else:
|
||||
latest_release: object = requests.get(f'https://api.github.com/repos/{repository}/releases/latest?prerelease={prerelease}').json()
|
||||
return transform_release(latest_release)
|
||||
# A little bit of code duplication but more readable than a ternary operation.
|
||||
if all:
|
||||
releases: list = requests.get(
|
||||
f"https://api.github.com/repos/{repository}/releases"
|
||||
).json()
|
||||
return list(map(transform_release, releases)) # List might not be needed.
|
||||
else:
|
||||
latest_release: object = requests.get(
|
||||
f"https://api.github.com/repos/{repository}/releases/latest?prerelease={prerelease}"
|
||||
).json()
|
||||
return transform_release(latest_release)
|
||||
|
@ -1,5 +1,6 @@
|
||||
import json
|
||||
|
||||
|
||||
def load_config() -> dict:
|
||||
with open('config.json', 'r') as config_file:
|
||||
return json.load(config_file)
|
||||
with open("config.json", "r") as config_file:
|
||||
return json.load(config_file)
|
||||
|
@ -4,107 +4,113 @@ from app import api
|
||||
from app.utils import get_repository_name, write_json, read_json, create_if_not_exists
|
||||
from abc import abstractmethod
|
||||
|
||||
class Api():
|
||||
_api: api.Api
|
||||
|
||||
def __init__(self, name: str, api: api.Api = api.GitHubApi()) -> None:
|
||||
self.name = name
|
||||
self._api = api
|
||||
class Api:
|
||||
_api: api.Api
|
||||
|
||||
@abstractmethod
|
||||
def generate(self, config, path):
|
||||
'''
|
||||
Generates the api based on the config to the path.
|
||||
def __init__(self, name: str, api: api.Api = api.GitHubApi()) -> None:
|
||||
self.name = name
|
||||
self._api = api
|
||||
|
||||
@abstractmethod
|
||||
def generate(self, config, path):
|
||||
"""
|
||||
Generates the api based on the config to the path.
|
||||
|
||||
Args:
|
||||
config (dict): The config for the api
|
||||
path (str): The path where the api should be generated
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
Args:
|
||||
config (dict): The config for the api
|
||||
path (str): The path where the api should be generated
|
||||
'''
|
||||
raise NotImplementedError
|
||||
|
||||
class ReleaseApi(Api):
|
||||
def __init__(self, api) -> None:
|
||||
super().__init__("release", api)
|
||||
pass
|
||||
|
||||
def generate(self, config, path):
|
||||
path = join(path, 'release')
|
||||
def __init__(self, api) -> None:
|
||||
super().__init__("release", api)
|
||||
pass
|
||||
|
||||
repositories = config["repositories"]
|
||||
def generate(self, config, path):
|
||||
path = join(path, "release")
|
||||
|
||||
for repository in repositories:
|
||||
release = self._api.get_release(repository)
|
||||
repository_name = get_repository_name(repository)
|
||||
|
||||
tag = release['tag']
|
||||
|
||||
release_path = join(path, repository_name)
|
||||
release_json = json.dumps(release)
|
||||
|
||||
create_if_not_exists(release_path)
|
||||
|
||||
write_json(release_json, join(release_path, f'{tag}.json'), overwrite=False)
|
||||
write_json(release_json, join(release_path, 'latest.json')) # Overwrite the latest release
|
||||
|
||||
# At last join the current tag to an index file
|
||||
index_path = join(path, f'{repository_name}.json')
|
||||
|
||||
index = read_json(index_path, [])
|
||||
if tag not in index: # TODO: Check if there a better way to do this
|
||||
index.append(tag) # Add the current tag to the index
|
||||
repositories = config["repositories"]
|
||||
|
||||
for repository in repositories:
|
||||
release = self._api.get_release(repository)
|
||||
repository_name = get_repository_name(repository)
|
||||
|
||||
tag = release["tag"]
|
||||
|
||||
release_path = join(path, repository_name)
|
||||
release_json = json.dumps(release)
|
||||
|
||||
create_if_not_exists(release_path)
|
||||
|
||||
write_json(release_json, join(release_path, f"{tag}.json"), overwrite=False)
|
||||
write_json(
|
||||
release_json, join(release_path, "latest.json")
|
||||
) # Overwrite the latest release
|
||||
|
||||
# At last join the current tag to an index file
|
||||
index_path = join(path, f"{repository_name}.json")
|
||||
|
||||
index = read_json(index_path, [])
|
||||
if tag not in index: # TODO: Check if there a better way to do this
|
||||
index.append(tag) # Add the current tag to the index
|
||||
|
||||
write_json(index, index_path)
|
||||
|
||||
write_json(index, index_path)
|
||||
|
||||
class ContributorApi(Api):
|
||||
def __init__(self, api) -> None:
|
||||
super().__init__("contributor", api)
|
||||
pass
|
||||
def __init__(self, api) -> None:
|
||||
super().__init__("contributor", api)
|
||||
pass
|
||||
|
||||
def generate(self, config, path):
|
||||
path = join(path, 'contributor')
|
||||
def generate(self, config, path):
|
||||
path = join(path, "contributor")
|
||||
|
||||
create_if_not_exists(path)
|
||||
repositories = config["repositories"]
|
||||
create_if_not_exists(path)
|
||||
repositories = config["repositories"]
|
||||
|
||||
for repository in repositories:
|
||||
repository_name = get_repository_name(repository)
|
||||
for repository in repositories:
|
||||
repository_name = get_repository_name(repository)
|
||||
|
||||
contributors = self._api.get_contributor(repository)
|
||||
contributors_path = join(path, f'{repository_name}.json')
|
||||
contributors = self._api.get_contributor(repository)
|
||||
contributors_path = join(path, f"{repository_name}.json")
|
||||
|
||||
write_json(contributors, contributors_path)
|
||||
|
||||
write_json(contributors, contributors_path)
|
||||
|
||||
class SocialApi(Api):
|
||||
def __init__(self, api) -> None:
|
||||
super().__init__("social", api)
|
||||
|
||||
def generate(self, config, path):
|
||||
new_social = config
|
||||
|
||||
social_path = join(path, f"social.json")
|
||||
social = read_json(social_path, new_social)
|
||||
def __init__(self, api) -> None:
|
||||
super().__init__("social", api)
|
||||
|
||||
write_json(social, social_path)
|
||||
def generate(self, config, path):
|
||||
new_social = config
|
||||
|
||||
class ApiProvider():
|
||||
_apis: list[Api]
|
||||
social_path = join(path, f"social.json")
|
||||
social = read_json(social_path, new_social)
|
||||
|
||||
def __init__(self, apis: list[Api]) -> None:
|
||||
self._apis = apis
|
||||
write_json(social, social_path)
|
||||
|
||||
def get(self, name: str) -> Api:
|
||||
for api in self._apis:
|
||||
if api.name == name:
|
||||
return api
|
||||
|
||||
return None
|
||||
class ApiProvider:
|
||||
_apis: list[Api]
|
||||
|
||||
def __init__(self, apis: list[Api]) -> None:
|
||||
self._apis = apis
|
||||
|
||||
def get(self, name: str) -> Api:
|
||||
for api in self._apis:
|
||||
if api.name == name:
|
||||
return api
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class DefaultApiProvider(ApiProvider):
|
||||
def __init__(self):
|
||||
self._api = api.GitHubApi() # Use GitHub as default api
|
||||
|
||||
super().__init__([
|
||||
ReleaseApi(self._api),
|
||||
ContributorApi(self._api),
|
||||
SocialApi(self._api)]
|
||||
)
|
||||
def __init__(self):
|
||||
self._api = api.GitHubApi() # Use GitHub as default api
|
||||
|
||||
super().__init__(
|
||||
[ReleaseApi(self._api), ContributorApi(self._api), SocialApi(self._api)]
|
||||
)
|
||||
|
@ -1,21 +1,25 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def write_json(text: str | dict | list, to, overwrite=True):
|
||||
if not os.path.exists(to) or overwrite:
|
||||
with open(to, 'w') as f:
|
||||
if not isinstance(text, str):
|
||||
text = json.dumps(text)
|
||||
f.write(text)
|
||||
if not os.path.exists(to) or overwrite:
|
||||
with open(to, "w") as f:
|
||||
if not isinstance(text, str):
|
||||
text = json.dumps(text)
|
||||
f.write(text)
|
||||
|
||||
|
||||
def read_json(path, default):
|
||||
if os.path.exists(path):
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
return default
|
||||
if os.path.exists(path):
|
||||
with open(path, "r") as f:
|
||||
return json.load(f)
|
||||
return default
|
||||
|
||||
|
||||
def create_if_not_exists(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def get_repository_name(repository: str):
|
||||
return repository.split('/')[-1]
|
||||
return repository.split("/")[-1]
|
||||
|
17
src/main.py
17
src/main.py
@ -3,15 +3,16 @@ from app.generator import DefaultApiProvider
|
||||
|
||||
config = load_config()
|
||||
|
||||
output = config['output']
|
||||
apis = config['api']
|
||||
output = config["output"]
|
||||
apis = config["api"]
|
||||
|
||||
api_provider = DefaultApiProvider()
|
||||
|
||||
for api in apis:
|
||||
types = api['type'].split('+')
|
||||
del api['type'] # Don't need the type for the api anymore below
|
||||
for type in types:
|
||||
api_type = api_provider.get(type)
|
||||
if api_type is None: continue
|
||||
api_type.generate(api, output)
|
||||
types = api["type"].split("+")
|
||||
del api["type"] # Don't need the type for the api anymore below
|
||||
for type in types:
|
||||
api_type = api_provider.get(type)
|
||||
if api_type is None:
|
||||
continue
|
||||
api_type.generate(api, output)
|
||||
|
Loading…
x
Reference in New Issue
Block a user