Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft of a more organized object modelling #41

Merged
merged 1 commit into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ dependencies = [
"mkdocstrings-python>=1.9.1",
"mkdocs-macros-plugin",
"mkdocs-site-urls",
"dynaconf",
"importlib_resources",
"httpx",
"rich",
Expand Down
150 changes: 0 additions & 150 deletions src/pulp_docs/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,153 +4,3 @@
It defines its interface.
"""

import os
import subprocess
import sys
import tempfile
import typing as t
from pathlib import Path

import click
from importlib_resources import files

TMP_DIR = Path("tmp")
WORKDIR = Path.home() / "workspace" / "multirepo-prototype"


def get_abspath(name: str) -> Path:
return Path(WORKDIR / name).absolute()


def cast_bool(value: str) -> bool:
return False if value.lower() in ("f", "false") else True


class Config:
"""
Configuration shared among CLI and mkdocs_macro.py hooks.

Params:
mkdocs_file: the base mkdocs used in serving/building
repolist: the configuration repositories (which and how to fetch)
clear_cache: whether to clear cache before downloading from remote
"""

def __init__(self, from_environ: bool = False):
if from_environ is False:
self.verbose = False
self.workdir = Path().absolute()
self.mkdocs_file = files("pulp_docs").joinpath("data/mkdocs.yml").absolute()
self.repolist = files("pulp_docs").joinpath("data/repolist.yml").absolute()
self.clear_cache = False

if env_mkdocs := os.environ.get("PULPDOCS_MKDOCS_FILE"):
self.mkdocs_file = Path(env_mkdocs)
else:
self.verbose = cast_bool(os.environ["PULPDOCS_VERBOSE"])
self.workdir = Path(os.environ["PULPDOCS_WORKDIR"])
self.mkdocs_file = Path(os.environ["PULPDOCS_MKDOCS_FILE"])
self.repolist = Path(os.environ["PULPDOCS_REPOLIST"])
self.clear_cache = cast_bool(os.environ["PULPDOCS_CLEAR_CACHE"])

def get_environ_dict(self):
return {f"PULPDOCS_{k.upper()}": str(v) for k, v in self.__dict__.items()}


pass_config = click.make_pass_decorator(Config, ensure=True)


@click.group()
@click.option("--verbose", "-v", is_flag=True)
@pass_config
def main(config: Config, verbose: bool):
"""
This is pulp-docs, a cli tool to help run and build multirepo documentation within Pulp project.
"""
config.verbose = verbose


# mkdocs help wrapper
watch_help = (
"A directory or file to watch for live reloading. Can be supplied multiple times."
)
no_reload_help = "Disable the live reloading in the development server."


@main.command()
@click.option(
"--clear-cache",
default=False,
is_flag=True,
help="Whether to clear the cache before serving (default=False).",
)
@click.option("--verbose", "-v", is_flag=True)
@click.option(
"-w",
"--watch",
help=watch_help,
type=click.Path(exists=True),
multiple=True,
default=[],
)
@click.option("--no-livereload", "livereload", flag_value=False, help=no_reload_help)
@click.option("--livereload", "livereload", flag_value=True, default=True, hidden=True)
@pass_config
def serve(
config: Config,
clear_cache: bool,
verbose: bool,
watch: t.List[Path],
livereload: bool,
):
"""Run mkdocs server."""
env = os.environ.copy()
config.clear_cache = clear_cache
config.verbose = verbose
env.update(config.get_environ_dict())

watch_list = [("--watch", watched) for watched in watch]
flag_list = []
if livereload is False:
flag_list.append(("--no-livereload",))

options: t.List[tuple] = [("--config-file", config.mkdocs_file)]
options.extend(watch_list)
options.extend(flag_list)

cmd = ["mkdocs", "serve"]
for opt in options:
cmd.extend(opt)
print("Running:", " ".join(str(s) for s in cmd))
subprocess.run(cmd, env=env)


@main.command()
@pass_config
def build(config: Config):
"""Build mkdocs site."""
config.verbose = True
env = os.environ.copy()
env.update(config.get_environ_dict())

options = (
("--config-file", config.mkdocs_file),
("--site-dir", str(Path("site").absolute())),
)
cmd = ["mkdocs", "build"]
for opt in options:
cmd.extend(opt)
print("Building:", " ".join(str(s) for s in cmd))
result = subprocess.run(cmd, env=env)
sys.exit(result.returncode)


@main.command()
@pass_config
def status(config: Config):
"""Print relevant information about repositories that will be used."""
raise NotImplementedError


if __name__ == "__main__":
sys.exit(main())
65 changes: 65 additions & 0 deletions src/pulp_docs/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from __future__ import annotations

import tempfile
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Optional

from dynaconf import Dynaconf, Validator


def init_config(setting_file: Optional[Path] = None) -> ConfigSchema:
setting_files = [setting_file] if setting_file else []
return Dynaconf(settings_file=setting_files)


class FindStrategy(Enum):
"""
Strategies on how to choose local repos, which should be used to override the defaults.

Args:
NONE: Don't use any local overrides.
CURRENT: If the CWD is a matching repo, use that.
PARENT_WORKDIR: Lookup for matching repos in the parent workdir.
LOOKUP_LIST: Use an explicit lookup_list defining the path for each repo override.
"""

NONE = 0
CURRENT = 1
PARENT_WORKDIR = 2
LOOKUP_LIST = 3


@dataclass
class ConfigSchema:
remote_sync_config: RemoteSyncConfig
repo_finder_config: RepoFinderConfig
cli_config: CliConfig

class Meta:
validators: list[Validator] = []


@dataclass
class RemoteSyncConfig:
"""
Args:
sync: Wheter or not to sync (clone and rebase) changes to a managed repo.
manged_repo_path: The local path to where the managed repo should operate.
"""

sync: bool = True
managed_repo_path: Path = Path(tempfile.gettempdir())


@dataclass
class RepoFinderConfig:
strategy: FindStrategy = FindStrategy.CURRENT
lookup_list: list[Path] = field(default_factory=list)


@dataclass
class CliConfig:
livereload: bool = True
watch_list: list[Path] = field(default_factory=list)
39 changes: 0 additions & 39 deletions src/pulp_docs/constants.py
Original file line number Diff line number Diff line change
@@ -1,40 +1 @@
ADMIN_NAME = "admin"
USER_NAME = "user"
RESTAPI_URL_TEMPLATE = "https://docs.pulpproject.org/{}/restapi.html"

DISPLAY_NAMES = {
"guides": "How-to Guides",
"learn": "Learn More",
"tutorials": "Tutorials",
"reference": "Reference",
}
GUIDES = DISPLAY_NAMES["guides"]
LEARN = DISPLAY_NAMES["learn"]
TUTORIALS = DISPLAY_NAMES["tutorials"]


class Names:
"""Display Names"""

# content types
GUIDES = "How-to Guides"
LEARN = "Learn More"
TUTORIALS = "Tutorials"
REFERENCE = "Reference"

# repo-types
OTHER = "Extra"
CORE = "Pulpcore"
CONTENT = "Plugins"

# personas
USER = "User"
ADMIN = "Admin"
DEV = "Dev"

# other
PULPCORE_TUTORIAL = "Getting Started"

@staticmethod
def get(name: str):
return getattr(Names, name.upper())
83 changes: 0 additions & 83 deletions src/pulp_docs/data/repolist.yml

This file was deleted.

13 changes: 0 additions & 13 deletions src/pulp_docs/mkdocs_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,3 @@

See: https://www.mkdocs.org/user-guide/configuration/#hooks
"""


def on_serve(server, config, builder):
"""
Hook to unwatch the temp dirs.

See: https://www.mkdocs.org/dev-guide/plugins/#on_serve
"""
tmpdir = config["docs_dir"]
mkdocs_yml = config["config_file_path"]
server.unwatch(tmpdir)
server.unwatch(mkdocs_yml)
return server
Loading
Loading