Skip to content

Commit

Permalink
Fixed flake8 warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
MrSpaar committed Apr 3, 2024
1 parent 825c9f2 commit de11007
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 56 deletions.
5 changes: 3 additions & 2 deletions src/markdown_spa/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from click import group

from .project import init, watch, build
from .extensions import install, uninstall, add, list

from click import group


@group(context_settings=dict(help_option_names=['-h', '--help']))
def main_group() -> int:
"""Static site generator for Markdown files."""
return 0


def main() -> None:
"""Create the main command group"""

Expand Down
15 changes: 7 additions & 8 deletions src/markdown_spa/cli/extensions.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from .utils import echo_wrap, initialize_extension, call

from os import listdir
from pathlib import Path
from shutil import rmtree
from os.path import exists
from sys import executable

from click import command, argument, option, secho
from .utils import echo_wrap, initialize_extension, call


@command()
Expand All @@ -28,19 +27,19 @@ def install(full_traceback: bool, upgrade: bool, name: str, url: str) -> int:
):
secho(err, fg="red", bold=True)
return 1

if not upgrade and (
err := echo_wrap("Cloning repository", call, f"git clone {url} {path}", full_tb=full_traceback)
):
secho(err, fg="red", bold=True)
return 1

if exists(f"{path}/requirements.txt") and (
err := echo_wrap("Installing requirements", call, f"{executable} -m pip install -r {name}/requirements.txt", full_tb=full_traceback)
):
secho(err, fg="red", bold=True)
return 1

secho("Extension installed!", fg="green", bold=True)
return 0

Expand Down Expand Up @@ -71,14 +70,14 @@ def list() -> int:

extensions = [
path for path in listdir(modules_path)
if path not in ("__pycache__", "__init__.py") and exists (f"{modules_path}/{path}/__init__.py")
if path not in ("__pycache__", "__init__.py") and exists(f"{modules_path}/{path}/__init__.py")
]

if not extensions:
secho("No extensions found!", fg="red", bold=True)
return 1

secho(f"Installed extensions: ", fg="green", bold=True, nl=False)
secho("Installed extensions: ", fg="green", bold=True, nl=False)
secho(', '.join(extensions))

return 0
Expand All @@ -97,6 +96,6 @@ def add(full_traceback: bool, name: str) -> int:
if err := initialize_extension(name, full_traceback):
secho(err, fg="red", bold=True)
return 1

secho("Extension initialized!", fg="green", bold=True)
return 0
4 changes: 2 additions & 2 deletions src/markdown_spa/cli/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def init(full_traceback: bool, path: str) -> int:
path for path in listdir(PPath(__file__).parent.parent/"extensions")
if not path.endswith(".py") and not path.startswith("__")
]

dirs_str = "\n - ".join(["", *dirs])
inp = prompt(
f"Choose extensions to enable (space-separated, empty to skip): {dirs_str}\n",
Expand All @@ -48,7 +48,7 @@ def init(full_traceback: bool, path: str) -> int:
if diff := set(extensions).difference(dirs):
secho(f"Unknown extensions: {', '.join(diff)}", fg="red", bold=True)
return 1

chdir(path)
for extension in extensions:
secho(f"Initializing {extension}... ", fg="yellow", bold=True)
Expand Down
7 changes: 3 additions & 4 deletions src/markdown_spa/cli/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from ..generator import Generator, Dependency, get_extension

from os.path import isdir
from sys import executable
from os import access, W_OK, R_OK
Expand All @@ -8,6 +6,7 @@
from subprocess import PIPE, CalledProcessError, run

from click import secho, prompt
from ..generator import Generator, Dependency, get_extension


def echo_wrap(message: str, func: Callable[..., Optional[str]], *args, full_tb: bool = False, **kwargs) -> Optional[str]:
Expand All @@ -24,8 +23,8 @@ def echo_wrap(message: str, func: Callable[..., Optional[str]], *args, full_tb:
if err:
secho("failed", fg="red", bold=True)
return err
secho(f"done", fg="green", bold=True)

secho("done", fg="green", bold=True)


def call(command) -> Optional[str]:
Expand Down
4 changes: 2 additions & 2 deletions src/markdown_spa/extensions/SASS/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from ...generator import Extension, Dependency, Option

from shutil import copy
from os.path import exists
from os import makedirs, remove

from ...generator import Extension, Dependency, Option


class SASS(Extension):
DEPENDENCIES = (
Expand Down
4 changes: 2 additions & 2 deletions src/markdown_spa/extensions/Sitemap/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from ...generator import Extension, Option

from shutil import copy
from datetime import datetime
from configparser import ConfigParser

from ...generator import Extension, Option


class Sitemap(Extension):
OPTIONS = {
Expand Down
4 changes: 2 additions & 2 deletions src/markdown_spa/extensions/Tailwind/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from ...generator import Extension, Dependency, Option

from os import remove
from shutil import copy
from os.path import exists

from ...generator import Extension, Dependency, Option


class Tailwind(Extension):
DEPENDENCIES = (
Expand Down
17 changes: 9 additions & 8 deletions src/markdown_spa/generator/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from os import environ
from os.path import exists
from typing import Optional
from dataclasses import dataclass
from importlib.util import find_spec
from configparser import ConfigParser
Expand All @@ -9,6 +8,7 @@

T = TypeVar("T", str, bool, int, float)


@dataclass
class Option(Generic[T]):
"""Represents an option for an extension"""
Expand All @@ -21,6 +21,7 @@ class Option(Generic[T]):
def __post_init__(self) -> None:
self.is_path = self.is_path or self.is_template


@dataclass
class Dependency:
"""Represents a dependency for an extension"""
Expand All @@ -33,14 +34,14 @@ class Dependency:

def __post_init__(self) -> None:
self.pip_package = self.pip_package or self.module

def __repr__(self) -> str:
return self.pip_package


class IniConfig:
"""Class for loading markdown_spa config from config.ini file."""

def __init__(self, root: str, ini_file: str = "config.ini") -> None:
self.root = root
self.parser = ConfigParser()
Expand Down Expand Up @@ -95,7 +96,7 @@ def check_options(self, section: str, options: dict[str, Option]) -> Optional[st
if option.is_path and not exists(path):
faulty_options.append(f"{name} ({path}) not found")
continue

if faulty_options:
faulty_options_str = "\n - ".join(faulty_options)
return f"Error in section [{section}]: \n - {faulty_options_str}"
Expand All @@ -116,7 +117,7 @@ def base_url(self) -> str:
self.__base_url = f"http://127.0.0.1:{self.port}"

if var := environ.get("REPO"):
user, repo = var.split("/")
user, repo = var.split("/")
self.__base_url = f"https://{user}.github.io" if "github.io" in repo else f"https://{user}.github.io/{repo}"

return self.__base_url
Expand All @@ -129,15 +130,15 @@ def json(self) -> bool:
"GENERATOR", "json", fallback=False
)
return self.__json

@property
def dist_path(self) -> str:
"""The path to the dist folder"""
if not hasattr(self, "__dist_path"):
path = self.parser.get("GENERATOR", "dist_path", fallback="generated")
self.__dist_path = f"{self.root}/{path}"
return self.__dist_path

@property
def pages_path(self) -> str:
"""The path to the pages folder"""
Expand All @@ -153,7 +154,7 @@ def assets_path(self) -> str:
path = self.parser.get("GENERATOR", "assets_path", fallback="assets")
self.__assets_path = f"{self.root}/{path}"
return self.__assets_path

@property
def dist_assets_path(self) -> str:
"""The path to the assets folder in the dist folder"""
Expand Down
6 changes: 3 additions & 3 deletions src/markdown_spa/generator/extension.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from .config import Option, Dependency, T

from pathlib import Path
from importlib import import_module
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Type, final

from .config import Option, Dependency, T

if TYPE_CHECKING:
from . import Generator

Expand All @@ -30,7 +30,7 @@ def TO_WATCH(cls) -> list[str]:
@abstractmethod
def render(self) -> None:
"""Called either via `markdown_spa build` or `markdown_spa watch` (if TO_WATCH is not empty)"""
...
...

@staticmethod
@abstractmethod
Expand Down
46 changes: 23 additions & 23 deletions src/markdown_spa/generator/generator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
from .config import IniConfig
from .extension import Extension, get_extension

from json import dump
from os.path import isdir
from shutil import copytree
Expand All @@ -11,6 +8,9 @@
from markdown import Markdown
from jinja2 import Environment, FileSystemLoader, Template

from .config import IniConfig
from .extension import Extension, get_extension


class Page(TypedDict):
"""Represents a markdown page"""
Expand Down Expand Up @@ -40,11 +40,11 @@ def __init__(self, root: str = "", ini_path: str = "config.ini", full_tb: bool =
def __to_checkbox(m: Match) -> str:
checked: str = ' checked' if m.group(1).lower() == 'x' else ''
return f"<input type='checkbox' disabled{checked} aria-label='checkbox list item'> {m.group(2)}"

def __read_meta(self, path: str) -> dict[str, str]:
meta: dict[str, str] = self.config.defaults()

with open(path) as f:
with open(path, encoding="utf-8") as f:
while (len(line := f.readline()) > 2 and (match := Generator.TAG_RE.match(line))):
meta[match.group("key")] = match.group("value")

Expand All @@ -58,8 +58,8 @@ def __prepare(self, full_path: str) -> dict[str, Page]:
ext = item_path[item_path.rfind(".")+1:]

uri = item_path.removeprefix(f"{self.config.pages_path}/") \
.removesuffix(f".{ext}") \
.removesuffix("index")
.removesuffix(f".{ext}") \
.removesuffix("index")

# File already processed, processing dir
if isdir(item_path) and uri in entry:
Expand All @@ -82,11 +82,11 @@ def __prepare(self, full_path: str) -> dict[str, Page]:
meta=self.config.defaults(),
children=self.__prepare(item_path)
)

return entry
def __render_md(self, page: Page, uri: str) -> str:
with open(f"{self.config.pages_path}/{uri or 'index'}.md") as f:

def __render_md(self, uri: str) -> str:
with open(f"{self.config.pages_path}/{uri or 'index'}.md", encoding="utf-8") as f:
content = self.md.convert(Generator.QUOTE_RE.sub(
r"\2\n{.quote .quote-\1}", f.read()
))
Expand All @@ -97,7 +97,7 @@ def __render_md(self, page: Page, uri: str) -> str:
.replace("<pre", "<pre tabindex='0'")

def __render_html(self, page: Page, uri: str) -> str:
with open(f"{self.config.pages_path}/{uri or 'index'}.{page['ext']}") as f:
with open(f"{self.config.pages_path}/{uri or 'index'}.{page['ext']}", encoding="utf-8") as f:
for _ in range(len(page["meta"])):
f.readline()

Expand All @@ -109,26 +109,26 @@ def __render_html(self, page: Page, uri: str) -> str:
def __render_tree(self, tree: dict[str, Page]) -> None:
for uri, page in tree.items():
makedirs(f"{self.config.dist_path}/{uri}", exist_ok=True)

if page["ext"] == "md":
content = self.__render_md(page, uri)
content = self.__render_md(uri)
else:
content = self.__render_html(page, uri)
content = self.__render_html(page, uri)

content = Generator.INTERNAL_LINK_RE.sub(
rf'\1="{self.config.base_url}\2"', content
)

with open(f"{self.config.dist_path}/{uri}/index.html", "w") as f:
with open(f"{self.config.dist_path}/{uri}/index.html", "w", encoding="utf-8") as f:
f.write(Generator.INTERNAL_LINK_RE.sub(rf'\1="{self.config.base_url}\2"',
self.base_template.render(
uri=uri, nav=self.nav, meta=page["meta"], page_content=content,
assets_path=self.config.assets_path.removeprefix(self.config.root+"/")
)
self.base_template.render(
uri=uri, nav=self.nav, meta=page["meta"], page_content=content,
assets_path=self.config.assets_path.removeprefix(self.config.root+"/")
)
))

if self.config.json:
with open(f"{self.config.dist_path}/{uri}/index.json", "w") as f:
with open(f"{self.config.dist_path}/{uri}/index.json", "w", encoding="utf-8") as f:
dump({**page["meta"], "uri": uri, "page_content": content}, f, indent=4)

if page["children"]:
Expand All @@ -138,7 +138,7 @@ def load_config(self) -> Optional[str]:
"""Loads config from config_path"""
if error := self.config.load_config():
return error

for extension in self.config.extensions:
try:
instance = get_extension(extension)(self)
Expand Down Expand Up @@ -171,7 +171,7 @@ def render_pages(self) -> Optional[str]:
if self.full_tb:
raise e
return f"Error while rendering nav template: {e}"

try:
self.base_template = self.env.get_template(self.config.base_template)
self.__render_tree(self.tree)
Expand Down

0 comments on commit de11007

Please sign in to comment.