feat: add type annotations and docstrings for Flask routes

Provided type annotations and detailed docstrings for all routes
in the Flask application to improve code readability and
maintainability. Updated return types to use Flask's Response
object and included explanations of arguments and return values
for each route function, enhancing overall code documentation.

This change aims to facilitate better understanding and easier
maintenance of the codebase, particularly for new contributors.
This commit is contained in:
Kumi 2024-06-19 10:02:10 +02:00
parent f80d827957
commit ccd4a1cb77
Signed by: kumi
GPG key ID: ECBCC9082395383F

View file

@ -1,4 +1,4 @@
from flask import Flask, render_template, abort, send_from_directory
from flask import Flask, render_template, abort, send_from_directory, Response
from .classes.git import Git
from .classes.markdown import RelativeURLRewriter
import logging
@ -18,24 +18,48 @@ app = Flask(__name__)
@app.route("/")
def index():
def index() -> Response:
"""Route for the index page.
Returns:
str: The rendered template for the index page.
"""
return render_template("index.html")
@app.route("/assets/<path:path>")
def send_assets(path):
def send_assets(path: str) -> Response:
"""Route for serving static assets.
Args:
path (str): The path to the asset file.
Returns:
Response: A response containing the asset file.
"""
return send_from_directory(Path(__file__).parent / "assets", path)
@app.route("/<owner>/<repo>/", methods=["GET"])
@app.route("/<owner>/<repo>/tree/main/", methods=["GET"])
@app.route("/<owner>/<repo>/tree/main/<path:path>", methods=["GET"])
def get_tree(owner, repo, path=""):
def get_tree(owner: str, repo: str, path: str = "") -> Response:
"""Route for getting the directory structure of a repository.
Args:
owner (str): The owner of the repository.
repo (str): The name of the repository.
path (str): The path within the repository.
Returns:
str: The rendered template for the directory structure.
"""
path = path.lstrip("/")
logger.debug(f"Path: {path}")
repo_url = f"https://github.com/{owner}/{repo}.git"
git = Git(repo_url)
try:
directory_structure = git.get_directory_structure(path)
filtered_structure = directory_structure
@ -54,12 +78,13 @@ def get_tree(owner, repo, path=""):
)
)
)
files = [entry for entry in filtered_structure if "/" not in entry]
# Get README.md content if it exists
readme_content = None
if f"README.md" in files:
if "README.md" in files:
readme_md = git.get_file_content(f"{path}/README.md")
base_url = f"/{owner}/{repo}/raw/main/{path}".rstrip("/")
readme_content = RelativeURLRewriter(base_url).convert(
@ -83,7 +108,17 @@ def get_tree(owner, repo, path=""):
@app.route("/<owner>/<repo>/raw/main/<path:file_path>", methods=["GET"])
def get_raw(owner, repo, file_path):
def get_raw(owner: str, repo: str, file_path: str) -> Response:
"""Route for getting the raw content of a file.
Args:
owner (str): The owner of the repository.
repo (str): The name of the repository.
file_path (str): The path of the file.
Returns:
Response: A response containing the raw content of the file.
"""
repo_url = f"https://github.com/{owner}/{repo}.git"
git = Git(repo_url)
try:
@ -112,7 +147,17 @@ def get_raw(owner, repo, file_path):
@app.route("/<owner>/<repo>/blob/main/<path:file_path>", methods=["GET"])
def preview_file(owner, repo, file_path):
def preview_file(owner: str, repo: str, file_path: str):
"""Route for previewing a file.
Args:
owner (str): The owner of the repository.
repo (str): The name of the repository.
file_path (str): The path of the file.
Returns:
str: The rendered template for the file preview.
"""
repo_url = f"https://github.com/{owner}/{repo}.git"
git = Git(repo_url)
try:
@ -124,7 +169,9 @@ def preview_file(owner, repo, file_path):
is_safe = False
if content_type == "text/markdown":
base_url = f"/{owner}/{repo}/raw/main/{"/".join(file_path.split("/")[:-1])}".rstrip("/")
base_url = f"/{owner}/{repo}/raw/main/{"/".join(file_path.split("/")[:-1])}".rstrip(
"/"
)
file_content = RelativeURLRewriter(base_url).convert(
file_content.decode("utf-8")
)
@ -141,7 +188,7 @@ def preview_file(owner, repo, file_path):
file_content=file_content,
is_text=is_text,
is_image=is_image,
is_safe=is_safe
is_safe=is_safe,
)
except Exception as e:
logger.error(f"Error previewing file {file_path} in {owner}/{repo}: {e}")
@ -149,6 +196,7 @@ def preview_file(owner, repo, file_path):
def main():
"""Main function to run the Flask app."""
port = os.environ.get("PORT", 8107)
host = os.environ.get("HOST", "127.0.0.1")
app.run(debug=True, port=port, host=host)