load in new module

This commit is contained in:
Oliver Walters committed 2026-11-12 02:48:46 +00:00
1 parent 03e3872d80
commit fce02cb818
2 files changed
+220 -145

No files matched your search

+194
View File
@@ -0,0 +1,194 @@
"""Shared data for the documentation build process.
This module loads the generated InvenTree definition files (settings, status codes,
report context, etc) which are used by the custom macros defined in 'main.py'.
It is deliberately separate from 'main.py', as some static site generators
(e.g. zensical) re-execute the macros module for *every* page. As a regular
module, this file is imported (and cached) only once per build process:
- Generated data files are loaded lazily, and reloaded only if they change on disk
- Observed settings / status codes are accumulated across all pages of the build
- The 'on_config' hook values are computed once (for generators without hook support)
"""
import importlib.util
import json
import os
import threading
from pathlib import Path
from typing import Any, Optional
import yaml
HERE = Path(__file__).parent
GENERATED_DIR = HERE.joinpath('generated')
# Files where we *store* information on what has been documented during the build.
# These are checked after the build completes (see 'on_post_build' in docs/hooks.py)
OBSERVED_SETTINGS_FILE = GENERATED_DIR.joinpath('observed_settings.json')
OBSERVED_STATUS_CODES_FILE = GENERATED_DIR.joinpath('observed_status_codes.json')
_lock = threading.RLock()
# Cache of loaded data files: {filename: (mtime, data)}
_file_cache: dict[str, tuple[float, Any]] = {}
# Things which have been rendered somewhere in the documentation
_observed_settings: dict[str, dict[str, bool]] = {'global': {}, 'user': {}}
_observed_status_codes: dict[str, bool] = {}
# Cached result of the 'on_config' hook
_hook_config: Optional[dict] = None
def print_build_environment():
"""Print some useful debugging information - useful for diagnosing CI build issues.
Ref: https://docs.readthedocs.io/en/stable/reference/environment-variables.html
"""
print('loading ./docs/docs_data.py...')
for key in [
'GITHUB_ACTIONS',
'GITHUB_REF',
'READTHEDOCS',
'READTHEDOCS_GIT_IDENTIFIER',
'READTHEDOCS_GIT_CLONE_URL',
'READTHEDOCS_GIT_COMMIT_HASH',
'READTHEDOCS_PROJECT',
'READTHEDOCS_VERSION',
'READTHEDOCS_VERSION_NAME',
'READTHEDOCS_VERSION_TYPE',
]:
val = os.environ.get(key, None) or '-- MISSING --'
print(f' - {key}: {val}')
def _write_json(path: Path, data: Any):
"""Write data to a JSON file."""
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4)
def reset_observations():
"""Reset the record of observed settings and status codes.
Called once when this module is first imported (i.e. once per build process).
"""
with _lock:
_observed_settings.clear()
_observed_settings.update({'global': {}, 'user': {}})
_observed_status_codes.clear()
_write_json(OBSERVED_SETTINGS_FILE, _observed_settings)
_write_json(OBSERVED_STATUS_CODES_FILE, _observed_status_codes)
def observe_setting(key: str, group: str):
"""Record that a particular setting has been documented.
Arguments:
key: The name of the setting
group: The group of the setting (e.g. 'global', 'user', 'config')
"""
with _lock:
group_data = _observed_settings.setdefault(group, {})
if key not in group_data:
group_data[key] = True
_write_json(OBSERVED_SETTINGS_FILE, _observed_settings)
def observe_status_code(class_name: str):
"""Record that a particular status code class has been documented."""
with _lock:
if class_name not in _observed_status_codes:
_observed_status_codes[class_name] = True
_write_json(OBSERVED_STATUS_CODES_FILE, _observed_status_codes)
def load_file(filename: str) -> Any:
"""Load a generated data file (JSON or YAML), caching the result.
The file is reloaded only if it has been modified since it was last loaded.
Arguments:
filename: Name of the file, relative to the 'generated' directory
"""
path = GENERATED_DIR.joinpath(filename)
mtime = path.stat().st_mtime
with _lock:
cached = _file_cache.get(filename)
if cached and cached[0] == mtime:
return cached[1]
with open(path, encoding='utf-8') as f:
if path.suffix in ('.yml', '.yaml'):
data = yaml.load(f, yaml.BaseLoader)
else:
data = json.load(f)
_file_cache[filename] = (mtime, data)
return data
def settings(group: str) -> dict:
"""Return the settings definitions for a given group ('global', 'user', 'config')."""
return load_file('inventree_settings.json')[group]
def tags() -> Any:
"""Return the custom template tags definitions."""
return load_file('inventree_tags.yml')
def filters() -> Any:
"""Return the custom template filters definitions."""
return load_file('inventree_filters.yml')
def status_codes() -> dict:
"""Return the status code class definitions."""
return load_file('inventree_status_codes.json')
def report_context() -> dict:
"""Return the report context definitions."""
return load_file('inventree_report_context.json')
def roles() -> Any:
"""Return the user permission role definitions."""
return load_file('inventree_roles.json')
def audited_models() -> Any:
"""Return the audited model definitions."""
return load_file('inventree_audited_models.json')
def hook_config(site_url: Optional[str] = None) -> dict:
"""Return the config values provided by the 'on_config' hook in docs/hooks.py.
For static site generators which do not support mkdocs hooks (e.g. zensical),
the hook is run once here, and the result cached for subsequent pages.
"""
global _hook_config
with _lock:
if _hook_config is None:
spec = importlib.util.spec_from_file_location(
'inventree_docs_hooks', HERE.joinpath('docs', 'hooks.py')
)
hooks = importlib.util.module_from_spec(spec)
spec.loader.exec_module(hooks)
_hook_config = hooks.on_config({'site_url': site_url})
return _hook_config
print_build_environment()
reset_observations()
+26 -145
View File
@@ -1,8 +1,5 @@
"""Main entry point for the documentation build process."""
import importlib.util
import json
import logging
import os
import subprocess
import sys
@@ -13,89 +10,17 @@ from typing import Literal, Optional
import requests
import yaml
# Debugging output - useful for diagnosing CI build issues
print('loading ./docs/main.py...')
logging.getLogger('openapidocs').setLevel(logging.ERROR)
# Print out some useful debugging information
# Ref: https://docs.readthedocs.io/en/stable/reference/environment-variables.html
for key in [
'GITHUB_ACTIONS',
'GITHUB_REF',
'READTHEDOCS',
'READTHEDOCS_GIT_IDENTIFIER',
'READTHEDOCS_GIT_CLONE_URL',
'READTHEDOCS_GIT_COMMIT_HASH',
'READTHEDOCS_PROJECT',
'READTHEDOCS_VERSION',
'READTHEDOCS_VERSION_NAME',
'READTHEDOCS_VERSION_TYPE',
]:
val = os.environ.get(key, None) or '-- MISSING --'
print(f' - {key}: {val}')
# Cached settings dict values
global CONFIG_SETTINGS
global GLOBAL_SETTINGS
global USER_SETTINGS
global TAGS
global FILTERS
global REPORT_CONTEXT
global STATUS_CODES
global ROLES
# Read in the InvenTree settings file
here = Path(__file__).parent
gen_base = here.joinpath('generated')
# File where we expect to find the settings definitions
settings_file = gen_base.joinpath('inventree_settings.json')
# Generated data is loaded (and cached) by a separate module, as some static site
# generators (e.g. zensical) re-execute this file for every page.
if str(here) not in sys.path:
sys.path.append(str(here))
# File where we will *store* information on the settings we have observed
observed_settings_file = gen_base.joinpath('observed_settings.json')
# Overwrite the observed settings file
with open(observed_settings_file, 'w', encoding='utf-8') as f:
data = {'global': {}, 'user': {}}
# Write an empty dict to the file
# This is used to track which settings we have observed during the build process
f.write(json.dumps(data, indent=4))
# File where we will *store* information on the status code classes we have observed
observed_status_codes_file = gen_base.joinpath('observed_status_codes.json')
# Overwrite the observed status codes file
with open(observed_status_codes_file, 'w', encoding='utf-8') as f:
f.write(json.dumps({}, indent=4))
with open(settings_file, encoding='utf-8') as sf:
settings = json.load(sf)
GLOBAL_SETTINGS = settings['global']
USER_SETTINGS = settings['user']
CONFIG_SETTINGS = settings['config']
# Tags
with open(gen_base.joinpath('inventree_tags.yml'), encoding='utf-8') as f:
TAGS = yaml.load(f, yaml.BaseLoader)
# Filters
with open(gen_base.joinpath('inventree_filters.yml'), encoding='utf-8') as f:
FILTERS = yaml.load(f, yaml.BaseLoader)
# Status codes
with open(gen_base.joinpath('inventree_status_codes.json'), encoding='utf-8') as f:
STATUS_CODES = json.load(f)
# Report context
with open(gen_base.joinpath('inventree_report_context.json'), encoding='utf-8') as f:
REPORT_CONTEXT = json.load(f)
# User permission roles
with open(gen_base.joinpath('inventree_roles.json'), encoding='utf-8') as f:
ROLES = json.load(f)
# Audited models
with open(gen_base.joinpath('inventree_audited_models.json'), encoding='utf-8') as f:
AUDITED_MODELS = json.load(f)
import docs_data
def get_repo_url(raw=False):
@@ -169,32 +94,23 @@ def apply_hook_config(env):
Zensical does not support mkdocs hooks, so 'config.releases',
'config.assets_dir' etc are never set. When they are missing, run the
hook ourselves and inject the results into the template 'config' variable.
Zensical re-executes this module for every page, so the hook result is
cached on a module stored in sys.modules (which persists across pages).
"""
template_config = env.variables.get('config')
if template_config is None or 'releases' in template_config:
# Running under mkdocs - the hook has already been applied
if template_config is None:
return
hooks = sys.modules.get('inventree_docs_hooks')
if 'releases' in template_config:
# Running under mkdocs - the hook has already been applied,
# and define_env() is called once per build
docs_data.reset_observations()
return
if hooks is None:
spec = importlib.util.spec_from_file_location(
'inventree_docs_hooks', here.joinpath('docs', 'hooks.py')
)
hooks = importlib.util.module_from_spec(spec)
spec.loader.exec_module(hooks)
hooks.CACHED_CONFIG = hooks.on_config({
'site_url': template_config.get('site_url')
})
sys.modules['inventree_docs_hooks'] = hooks
hook_config = docs_data.hook_config(template_config.get('site_url'))
for key in ['releases', 'assets_dir', 'readthedocs', 'version_banner']:
if key in hooks.CACHED_CONFIG:
template_config[key] = hooks.CACHED_CONFIG[key]
if key in hook_config:
template_config[key] = hook_config[key]
def define_env(env):
@@ -364,18 +280,10 @@ def define_env(env):
(produced by the `export_status_codes` management command), so it can never
drift out of sync with the status codes actually defined in the source code.
"""
global STATUS_CODES
status_class = STATUS_CODES[class_name]
status_class = docs_data.status_codes()[class_name]
# Record that this status code class has been rendered somewhere in the docs
with open(observed_status_codes_file, encoding='utf-8') as f:
data = json.load(f)
data[class_name] = True
with open(observed_status_codes_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4)
docs_data.observe_status_code(class_name)
ret_data = '| Status | Value | Description |\n| --- | --- | --- |\n'
@@ -394,18 +302,7 @@ def define_env(env):
key: The name of the setting to observe
group: The group of the setting (e.g. 'global', 'user')
"""
# Read the observed settings file
with open(observed_settings_file, encoding='utf-8') as f:
data = json.load(f)
if group not in data:
data[group] = {}
data[group][key] = True
# Write the updated data back to the file
with open(observed_settings_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4)
docs_data.observe_setting(key, group)
@env.macro
def rendersetting(
@@ -441,8 +338,7 @@ def define_env(env):
short: If True, return a short version of the setting (default: False)
default: An optional default value to override the setting's default display value.
"""
global GLOBAL_SETTINGS
setting = GLOBAL_SETTINGS[key]
setting = docs_data.settings('global')[key]
# Settings are only 'observed' if they are displayed in full
if not short:
@@ -458,8 +354,7 @@ def define_env(env):
key: The name of the user setting to extract information for.
short: If True, return a short version of the setting (default: False)
"""
global USER_SETTINGS
setting = USER_SETTINGS[key]
setting = docs_data.settings('user')[key]
# Settings are only 'observed' if they are displayed in full
if not short:
@@ -480,8 +375,7 @@ def define_env(env):
key: The name of the configuration setting to extract information for.
default: An optional default value to override the setting's default display value.
"""
global CONFIG_SETTINGS
setting = CONFIG_SETTINGS[key]
setting = docs_data.settings('config')[key]
observe_setting(key, 'config')
@@ -498,11 +392,8 @@ def define_env(env):
@env.macro
def tags_and_filters():
"""Return a list of all tags and filters."""
global TAGS
global FILTERS
ret_data = ''
for ref in [['Tags', TAGS], ['Filters', FILTERS]]:
for ref in [['Tags', docs_data.tags()], ['Filters', docs_data.filters()]]:
ret_data += f'### {ref[0]}\n\n| Namespace | Name | Description |\n| --- | --- | --- |\n'
for value in ref[1]:
title = (
@@ -526,11 +417,9 @@ def define_env(env):
`users.ruleset.RULESET_CHOICES`), so it can never drift out of sync with
the roles actually defined in the source code.
"""
global ROLES
ret_data = '| Role | Description |\n| --- | --- |\n'
for role in ROLES:
for role in docs_data.roles():
description = role['description'] or role['label']
ret_data += f'| **{role["label"]}** | {description} |\n'
@@ -545,12 +434,10 @@ def define_env(env):
the models which implement `InvenTreeAuditMixin`), so it can never drift out
of sync with the models actually audited in the source code.
"""
global AUDITED_MODELS
ret_data = '| Category | Model | Model Type | Parent | Notes |\n'
ret_data += '| --- | --- | --- | --- | --- |\n'
for model in AUDITED_MODELS:
for model in docs_data.audited_models():
parent = model['parent']
notes = model['parent_note']
@@ -565,9 +452,7 @@ def define_env(env):
@env.macro
def report_context(type_: Literal['models', 'base'], model: str):
"""Extract information on a particular report context."""
global REPORT_CONTEXT
context = REPORT_CONTEXT.get(type_).get(model)
context = docs_data.report_context().get(type_).get(model)
ret_data = '| Variable | Type | Description |\n| --- | --- | --- |\n'
for k, v in context['context'].items():
@@ -606,9 +491,7 @@ def define_env(env):
`InvenTreeReportMixin`, so there is no manually-maintained per-model heading
list to keep in sync here.
"""
global REPORT_CONTEXT
models = REPORT_CONTEXT.get('models', {})
models = docs_data.report_context().get('models', {})
ret_data = ''
@@ -631,9 +514,7 @@ def define_env(env):
the `export_report_context` management command, so there is no manually-maintained
list of related models to keep in sync here.
"""
global REPORT_CONTEXT
related = REPORT_CONTEXT.get('related_models', {})
related = docs_data.report_context().get('related_models', {})
ret_data = ''