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

Mkdocs : utilise un hook de configuration plutôt que des scripts externes (1/2) #1237

Merged
merged 7 commits into from
Dec 31, 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: 0 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ jobs:
- name: Build static website
run: |
geotribu --help > content/toc_nav_ignored/snippets/code/geotribu_cli_help.txt
python scripts/050_mkdocs_populate_latest.py -c mkdocs.yml
python scripts/100_mkdocs_config_merger.py -c mkdocs.yml
mkdocs build --clean --config-file mkdocs.yml --verbose --strict
env:
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/links_checker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ jobs:

- name: Build static website
run: |
python scripts/050_mkdocs_populate_latest.py
python scripts/100_mkdocs_config_merger.py -c mkdocs.yml
mkdocs build --clean --config-file mkdocs.yml --quiet --strict
env:
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/pr_checker_build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ jobs:
export MKDOCS_SITE_URL="https://${NETLIFY_SITE_PREFIX}--${NETLIFY_SITE_NAME}.netlify.app/"

# merge different configs
python scripts/050_mkdocs_populate_latest.py -c ${{ env.MKDOCS_CONFIG_FILENAME }}
python scripts/100_mkdocs_config_merger.py -c ${{ env.MKDOCS_CONFIG_FILENAME }}

# build
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,4 @@ linkchecker_report.html
# fichiers liés aux vidéos Gource
gource.ini
avatars/
mkdocs-generated-configuration.yml
5 changes: 0 additions & 5 deletions config/extra_latest.yml

This file was deleted.

140 changes: 140 additions & 0 deletions hooks/mkdocs/G000_load_subconfigs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#! python3 # noqa: E265

# ############################################################################
# ########## Libraries #############
# ##################################

# standard library
import logging
from pathlib import Path
from typing import Literal, Optional

# 3rd party
import mkdocs.plugins
from material import __version__ as material_version
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.pages import Page
from mkdocs.utils.meta import get_data

# ###########################################################################
# ########## Global ################
# ##################################


logger = logging.getLogger("mkdocs")
log_prefix = f"[{__name__}] "

# ###########################################################################
# ########## Functions #############
# ##################################


def get_latest_content(
content_type: Literal["articles", "rdp"],
count: int = 10,
social_card_image_base: str = "https://geotribu.fr/assets/images/social/",
):
output_contents_list: list[Page] = []

if content_type == "articles":
glob_pattern = "202*/202*.md"
elif content_type == "rdp":
glob_pattern = "202*/rdp_202*.md"

for content in sorted(
Path(f"content/{content_type}/").glob(glob_pattern), reverse=True
)[:count]:
with content.open(encoding="utf-8-sig", errors="strict") as f:
source = f.read()

page_meta = get_data(source)[1]

page_rel = str(content.relative_to("content/"))[:-3]

if page_meta.get("image") is None or page_meta.get("image") == "":
social_card_url = f"{social_card_image_base}{page_rel}.png"
output_contents_list.append(
get_data(source)[1] | {"url_rel": page_rel} | {"image": social_card_url}
)
else:
output_contents_list.append(get_data(source)[1] | {"url_rel": page_rel})

return output_contents_list


def is_mkdocs_theme_material_insiders() -> Optional[bool]:
"""Check if the material theme is community or insiders edition.

Returns:
bool: True if the theme is Insiders edition. False if community.
"""
if material_version is not None and "insiders" in material_version:
logger.debug(log_prefix + "Material theme edition INSIDERS")
return True
else:
logger.debug(log_prefix + "Material theme edition COMMUNITY")
return False


# ###########################################################################
# ########## Hooks #################
# ##################################


@mkdocs.plugins.event_priority(10)
def on_config(config: MkDocsConfig) -> MkDocsConfig:
"""The config event is the first event called on build and
is run immediately after the user configuration is loaded and validated.
Any alterations to the config should be made here.

See: https://www.mkdocs.org/user-guide/plugins/#on_config

Args:
config (config_options.Config): global configuration object

Returns:
MkDocsConfig: global configuration object
"""
# determine the website flavor
config_filename = Path(config.get("config_file_path")).name
if config_filename == "mkdocs.yml":
config["extra"]["website_flavor"] = "insiders"
elif config_filename == "mkdocs-free.yml":
config["extra"]["website_flavor"] = "community"
else:
config["extra"]["website_flavor"] = "minimal"

# check if insiders version is installed
if (
config["extra"]["website_flavor"] == "insiders"
and not is_mkdocs_theme_material_insiders()
):
logger.warning(
log_prefix
+ f"Le fichier {config.get('config_file_path')} contient des paramètres ou "
"plugins uniquement disponibles dans la version Insiders (payante) du thème "
"Material. Or c'est la version community (gratuite) qui est installée "
f"({material_version}). La génération va probablement échouer. Deux solutions :"
"A. Installer la version Insiders (requiert un jeton GitHub). "
"B. Utiliser la configuration basée sur la version communautaire (gratuite), "
"par exemple : 'mkdocs build -f mkdocs-free.yml'"
)
config["extra"]["website_flavor"] = "community"

logger.info(
log_prefix + f"Génération du site {config.get('site_name')} "
f"en version {config.get('extra').get('website_flavor').upper()}"
)

# latest contents
latest_contents: dict = {"articles": [], "rdp": []}
for k in latest_contents:
latest_contents[k] = get_latest_content(
content_type=k,
social_card_image_base=f"{config.get('site_url')}assets/images/social/",
)

config["extra"]["latest"] = latest_contents
logger.info(
log_prefix + "Contenus récents ajoutés à la configuration globale du site."
)
1 change: 1 addition & 0 deletions mkdocs-free.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ site_dir: !ENV [MKDOCS_OUTPUT_DIR, "./build/mkdocs/site"]

# Scripts pendant le build
hooks:
- hooks/mkdocs/G000_load_subconfigs.py
- hooks/mkdocs/G003_social_cards_adapter.py
- hooks/mkdocs/G005_jinja_filters.py
- hooks/mkdocs/G006_authors_block.py
Expand Down
1 change: 1 addition & 0 deletions mkdocs-minimal.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ site_dir: !ENV [MKDOCS_OUTPUT_DIR, "./build/mkdocs/site"]

# Scripts pendant le build
hooks:
- hooks/mkdocs/G000_load_subconfigs.py
- hooks/mkdocs/G005_jinja_filters.py
- hooks/mkdocs/G006_authors_block.py

Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ site_dir: !ENV [MKDOCS_OUTPUT_DIR, "./build/mkdocs/site"]

# Scripts pendant le build
hooks:
- hooks/mkdocs/G000_load_subconfigs.py
# - hooks/mkdocs/G002_check_images_size.py
- hooks/mkdocs/G003_social_cards_adapter.py
- hooks/mkdocs/G005_jinja_filters.py
Expand Down
124 changes: 0 additions & 124 deletions scripts/050_mkdocs_populate_latest.py

This file was deleted.

Loading