ferronier 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ferronier/__init__.py +18 -0
- ferronier/__main__.py +261 -0
- ferronier/data/__init__.py +155 -0
- ferronier/data/fileformat.py +37 -0
- ferronier/data/preprocessor.py +69 -0
- ferronier/data/source/dict.py +23 -0
- ferronier/data/source/local.py +66 -0
- ferronier/data/source/merge.py +34 -0
- ferronier/data/source/remote.py +56 -0
- ferronier/data/source/self.py +28 -0
- ferronier/expand.py +285 -0
- ferronier/markdown.py +75 -0
- ferronier/plugins.py +169 -0
- ferronier/py.typed +0 -0
- ferronier/themes/__init__.py +103 -0
- ferronier/themes/portail/__init__.py +22 -0
- ferronier/themes/portail/templates/card.html +76 -0
- ferronier/themes/ressourcerie/__init__.py +20 -0
- ferronier/themes/ressourcerie/content/index.html +2 -0
- ferronier/themes/ressourcerie/static/css/bootstrap.min.css +6 -0
- ferronier/themes/ressourcerie/static/css/bootstrap.min.css.map +1 -0
- ferronier/themes/ressourcerie/static/css/fa-brands.min.css +6 -0
- ferronier/themes/ressourcerie/static/css/fa-solid.min.css +6 -0
- ferronier/themes/ressourcerie/static/css/ferronier.css +185 -0
- ferronier/themes/ressourcerie/static/css/fontawesome.min.css +8 -0
- ferronier/themes/ressourcerie/static/img/brigit.png +0 -0
- ferronier/themes/ressourcerie/static/img/favicon.ico +0 -0
- ferronier/themes/ressourcerie/static/img/komit.png +0 -0
- ferronier/themes/ressourcerie/static/js/bootstrap.bundle.min.js +7 -0
- ferronier/themes/ressourcerie/static/js/ferronier.js +34 -0
- ferronier/themes/ressourcerie/static/webfonts/fa-brands-400.woff2 +0 -0
- ferronier/themes/ressourcerie/static/webfonts/fa-solid-900.woff2 +0 -0
- ferronier/themes/ressourcerie/templates/card.html +63 -0
- ferronier/themes/ressourcerie/templates/footer.html +12 -0
- ferronier/themes/ressourcerie/templates/head-metadata.html +31 -0
- ferronier/themes/ressourcerie/templates/head.html +13 -0
- ferronier/themes/ressourcerie/templates/header-filters.html +47 -0
- ferronier/themes/ressourcerie/templates/header-intro.html +5 -0
- ferronier/themes/ressourcerie/templates/header-left.html +13 -0
- ferronier/themes/ressourcerie/templates/header-right.html +5 -0
- ferronier/themes/ressourcerie/templates/header-title.html +23 -0
- ferronier/themes/ressourcerie/templates/header.html +30 -0
- ferronier/themes/ressourcerie/templates/index.html +50 -0
- ferronier/themes/ressourcerie/templates/main.html +22 -0
- ferronier/unionpath.py +134 -0
- ferronier/utils.py +61 -0
- ferronier-0.1.0.dist-info/METADATA +30 -0
- ferronier-0.1.0.dist-info/RECORD +50 -0
- ferronier-0.1.0.dist-info/WHEEL +4 -0
- ferronier-0.1.0.dist-info/entry_points.txt +9 -0
ferronier/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Copyright 2025-2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Construit une page web à partir d'un extrait de la cartographie de la Forge."""
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
ferronier/__main__.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
# Copyright 2025-2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Construit une page web à partir d'un extrait de la cartographie de la Forge."""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import contextlib
|
|
20
|
+
import datetime
|
|
21
|
+
import functools
|
|
22
|
+
import locale
|
|
23
|
+
import logging
|
|
24
|
+
import pathlib
|
|
25
|
+
import re
|
|
26
|
+
import textwrap
|
|
27
|
+
import tomllib
|
|
28
|
+
from collections.abc import Iterable
|
|
29
|
+
|
|
30
|
+
import babel
|
|
31
|
+
import jinja2
|
|
32
|
+
import slugify
|
|
33
|
+
|
|
34
|
+
from . import __version__, data, themes
|
|
35
|
+
from .expand import ONKEYERROR, expand_items, expand_values
|
|
36
|
+
from .markdown import link_absolute2relative, markdown
|
|
37
|
+
from .plugins import PLUGINS
|
|
38
|
+
from .utils import sync
|
|
39
|
+
|
|
40
|
+
logging.basicConfig()
|
|
41
|
+
LOGGER = logging.getLogger("ferronier")
|
|
42
|
+
LOGGER.setLevel(logging.INFO)
|
|
43
|
+
|
|
44
|
+
RE_BRACKETS = re.compile(r"^([^{}]*){([^{}]+)}([^{}]*)$")
|
|
45
|
+
|
|
46
|
+
# Toutes ces valeurs peuvent être surchargées dans le fichier de configuration donné en argument
|
|
47
|
+
DEFAULT_CONF = {"plugins": {}}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def analyse_ligne_de_commande() -> argparse.Namespace:
|
|
51
|
+
"""Analyse la ligne de commande, et renvoit les options lues."""
|
|
52
|
+
parser = argparse.ArgumentParser(
|
|
53
|
+
prog="ferronier",
|
|
54
|
+
# pylint: disable=line-too-long
|
|
55
|
+
description="Un générateur de sites web statiques opérant à partir de données (au format json par exemple) plutôt qu'à partir de fichiers.",
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"--version", action="version", version=f"ferronier {__version__}"
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument(
|
|
61
|
+
"DIR",
|
|
62
|
+
help="Fichier de configuration, au format toml.",
|
|
63
|
+
type=pathlib.Path,
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"DEST", help="Dossier de destination", default="public", type=pathlib.Path
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--debug",
|
|
70
|
+
help=textwrap.dedent("""\
|
|
71
|
+
Affiche des informations de debuggage. Valeurs possibles :
|
|
72
|
+
- none : aucune information ;
|
|
73
|
+
- dump : affiche les données une fois pré-traitées ;
|
|
74
|
+
- pdb : comme `dump`, puis ouvre une console python.
|
|
75
|
+
|
|
76
|
+
Cette commande est expérimentale, utilisée pour le développement de ce logiciel, et son comportement peut changer sans prévenir.
|
|
77
|
+
"""),
|
|
78
|
+
nargs="?",
|
|
79
|
+
choices=["none", "pdb", "dump"],
|
|
80
|
+
default="none",
|
|
81
|
+
)
|
|
82
|
+
return parser.parse_args()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def maybefile(texte: str, *, cwd: pathlib.Path | None = None) -> str:
|
|
86
|
+
"""Renvoit la chaîne, ou le contenu du fichier décrit.
|
|
87
|
+
|
|
88
|
+
- Si le texte commence par `file:`, alors la suite est interprétée comme un
|
|
89
|
+
nom de fichier, qui est ouvert, et le contenu du fichier est renvoyé.
|
|
90
|
+
- Sinon, le texte lui-même est renvoyé.
|
|
91
|
+
|
|
92
|
+
:param texte: Texte, renvoyé tel quel s'il ne commence pas par `file:`, et
|
|
93
|
+
interprété comme un nom de fichier, dont le contenu est renvoyé, sinon.
|
|
94
|
+
:param cwd: Si non `None`, chemin à partir duquel doit être interprété le
|
|
95
|
+
nom de fichier décrit par `texte`.
|
|
96
|
+
"""
|
|
97
|
+
if texte.startswith("file:"):
|
|
98
|
+
filename = texte[len("file:") :]
|
|
99
|
+
if cwd is not None:
|
|
100
|
+
filename = cwd / filename
|
|
101
|
+
with open(filename, encoding="utf8") as file:
|
|
102
|
+
return file.read()
|
|
103
|
+
return texte
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def localesort(
|
|
107
|
+
iterable: Iterable[str], attribute: str | int | None = None, reverse: bool = False
|
|
108
|
+
) -> Iterable[str]:
|
|
109
|
+
"""Sort data, according to the current locale."""
|
|
110
|
+
if attribute is None:
|
|
111
|
+
key = locale.strxfrm
|
|
112
|
+
else:
|
|
113
|
+
key = lambda x: locale.strxfrm( # pylint: disable=unnecessary-lambda-assignment
|
|
114
|
+
x[attribute]
|
|
115
|
+
)
|
|
116
|
+
return sorted(iterable, key=key, reverse=reverse)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def main() -> None:
|
|
120
|
+
"""Fonction principale."""
|
|
121
|
+
# pylint: disable=too-many-locals, too-many-branches, too-many-statements
|
|
122
|
+
# Je pense que cette fonction, bien que longue, est bien documentée (grâce aux log).
|
|
123
|
+
# Si ce n'est pas le cas, il faudra la découper en sous-fonctions.
|
|
124
|
+
LOGGER.info("Analyse des arguments de la ligne de commande.")
|
|
125
|
+
options = analyse_ligne_de_commande()
|
|
126
|
+
|
|
127
|
+
LOGGER.info("Lecture du fichier de configuration")
|
|
128
|
+
with open(options.DIR, mode="rb") as configfile:
|
|
129
|
+
conf: dict = DEFAULT_CONF | tomllib.load(configfile)
|
|
130
|
+
|
|
131
|
+
LOGGER.info("Chargement des plugins")
|
|
132
|
+
PLUGINS.load(conf, options)
|
|
133
|
+
|
|
134
|
+
LOGGER.info("Vérification des répertoires")
|
|
135
|
+
try:
|
|
136
|
+
options.DEST.mkdir(exist_ok=True)
|
|
137
|
+
except OSError as error:
|
|
138
|
+
raise RuntimeError(
|
|
139
|
+
f"Erreur: Impossible de créer le répertoire {options.DEST} : {error}"
|
|
140
|
+
) from error
|
|
141
|
+
|
|
142
|
+
LOGGER.info("Génération des données exportées")
|
|
143
|
+
if not isinstance(conf.get("export", {}), dict):
|
|
144
|
+
raise TypeError(
|
|
145
|
+
# pylint: disable=line-too-long
|
|
146
|
+
f"""La donnée `export` doit être de type dictionnaire (actuellement {type(conf["export"])})."""
|
|
147
|
+
)
|
|
148
|
+
exported = conf.get("export", {})
|
|
149
|
+
exported["_conf"] = conf
|
|
150
|
+
# Redundant (because it can be accessed by `exported["_conf"]["plugins"]`) but convenient
|
|
151
|
+
exported["_plugins"] = conf.get("plugins", {})
|
|
152
|
+
exported["_meta"] = {
|
|
153
|
+
"now": datetime.datetime.now(),
|
|
154
|
+
"version": __version__,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
confdir = options.DIR.parent
|
|
158
|
+
with contextlib.chdir(confdir):
|
|
159
|
+
LOGGER.info("Téléchargement des données")
|
|
160
|
+
exported["data"] = data.preprocess(
|
|
161
|
+
data.load(conf["data"]), conf=conf.get("preprocess", {})
|
|
162
|
+
)
|
|
163
|
+
if options.debug == "dump" or options.debug is None:
|
|
164
|
+
# pylint: disable=import-outside-toplevel
|
|
165
|
+
import pprint
|
|
166
|
+
|
|
167
|
+
pprint.pprint(exported)
|
|
168
|
+
elif options.debug == "pdb":
|
|
169
|
+
try:
|
|
170
|
+
# pylint: disable=import-outside-toplevel, forgotten-debug-statement
|
|
171
|
+
import pprint
|
|
172
|
+
|
|
173
|
+
import ipdb
|
|
174
|
+
|
|
175
|
+
pprint.pprint(exported)
|
|
176
|
+
ipdb.set_trace()
|
|
177
|
+
except ImportError:
|
|
178
|
+
LOGGER.info(
|
|
179
|
+
"Install `ipdb` and re-run this command to have a nicer debugger."
|
|
180
|
+
)
|
|
181
|
+
breakpoint()
|
|
182
|
+
|
|
183
|
+
LOGGER.info("Chargement du thème")
|
|
184
|
+
theme: themes.Theme = themes.Theme(
|
|
185
|
+
conf.get("theme", None), confdir=pathlib.Path(confdir)
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
LOGGER.info("Copie des fichiers statiques des thèmes")
|
|
189
|
+
sync(theme / "static", options.DEST)
|
|
190
|
+
|
|
191
|
+
LOGGER.info("Chargement des modèles")
|
|
192
|
+
# Définition de la locale
|
|
193
|
+
conf["locale"] = babel.Locale.parse(conf.get("locale", babel.Locale.default()))
|
|
194
|
+
try:
|
|
195
|
+
locale.setlocale(locale.LC_ALL, str(conf["locale"]))
|
|
196
|
+
except locale.Error as error:
|
|
197
|
+
LOGGER.warning(
|
|
198
|
+
f"""Ignoring wrong or badly configured locale {conf["locale"]}: {error}."""
|
|
199
|
+
)
|
|
200
|
+
env = jinja2.Environment(loader=jinja2.ChoiceLoader(theme.loaders()))
|
|
201
|
+
env.filters |= {
|
|
202
|
+
"expandvalues": functools.partial(expand_values, onkeyerror=ONKEYERROR.DEFAULT),
|
|
203
|
+
"localesort": localesort,
|
|
204
|
+
"maybefile": functools.partial(maybefile, cwd=confdir),
|
|
205
|
+
"slugify": slugify.slugify,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
LOGGER.info("Pré-traitement")
|
|
209
|
+
for function in PLUGINS.hook_before_render:
|
|
210
|
+
function(exported["data"])
|
|
211
|
+
|
|
212
|
+
LOGGER.info("Génération des pages")
|
|
213
|
+
for sourcepath, _, filenames in (theme / "content").walk():
|
|
214
|
+
for sourcename in filenames:
|
|
215
|
+
destpath = options.DEST / sourcepath.relative_to(theme / "content")
|
|
216
|
+
destpath.mkdir(exist_ok=True, parents=True)
|
|
217
|
+
env.filters |= {
|
|
218
|
+
"markdown": markdown(
|
|
219
|
+
str((sourcepath / sourcename).relative_to(theme / "content"))
|
|
220
|
+
),
|
|
221
|
+
"url": functools.partial(
|
|
222
|
+
link_absolute2relative,
|
|
223
|
+
str((sourcepath / sourcename).relative_to(theme / "content")),
|
|
224
|
+
),
|
|
225
|
+
}
|
|
226
|
+
if "{" in sourcename or "}" in sourcename:
|
|
227
|
+
if match := RE_BRACKETS.match(sourcename):
|
|
228
|
+
prefix, center, suffix = match.groups()
|
|
229
|
+
destnames = [
|
|
230
|
+
(f"{prefix}{expanded}{suffix}", keys)
|
|
231
|
+
for keys, expanded in expand_items(
|
|
232
|
+
exported["data"],
|
|
233
|
+
center,
|
|
234
|
+
onkeyerror=ONKEYERROR.WARN,
|
|
235
|
+
)
|
|
236
|
+
]
|
|
237
|
+
else:
|
|
238
|
+
raise ValueError(
|
|
239
|
+
# pylint: disable=line-too-long
|
|
240
|
+
f"Exactly one pair of brackets is accepted in filename of the `content` directory. File `{sourcepath/sourcename}` violates this rule."
|
|
241
|
+
)
|
|
242
|
+
else:
|
|
243
|
+
destnames = [(sourcename, [])]
|
|
244
|
+
for destname, keys in destnames:
|
|
245
|
+
with (
|
|
246
|
+
open(sourcepath / sourcename, encoding="utf8") as source,
|
|
247
|
+
open(destpath / destname, encoding="utf8", mode="w") as dest,
|
|
248
|
+
):
|
|
249
|
+
dest.write(
|
|
250
|
+
env.from_string(source.read()).render(
|
|
251
|
+
**(exported | {"_keys": keys})
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
LOGGER.info("Post-traitement")
|
|
256
|
+
for function in PLUGINS.hook_after_render:
|
|
257
|
+
function(exported["data"])
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
if __name__ == "__main__":
|
|
261
|
+
main()
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Copyright 2025-2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Gestion des données dans le fichier de configuration : récupération et traitement."""
|
|
17
|
+
|
|
18
|
+
import dataclasses
|
|
19
|
+
import importlib.metadata
|
|
20
|
+
import logging
|
|
21
|
+
import re
|
|
22
|
+
from collections.abc import Callable
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from .. import expand
|
|
26
|
+
from ..plugins import PLUGINS
|
|
27
|
+
|
|
28
|
+
LOGGER = logging.getLogger("ferronier.data")
|
|
29
|
+
LOGGER.setLevel(logging.INFO)
|
|
30
|
+
|
|
31
|
+
RE_URL = re.compile(r"^\w*://")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def load(conf: str | dict) -> Any:
|
|
35
|
+
"""Charge les données définies dans le fichier de configuration.
|
|
36
|
+
|
|
37
|
+
C'est la fonction principale, qui :
|
|
38
|
+
- récupére les données en fonction de la source indiquée ;
|
|
39
|
+
- effecture le prétraitement éventuel.
|
|
40
|
+
|
|
41
|
+
La configuration dépend du format de données utilisée ;
|
|
42
|
+
le type de la valeur de retour dépend des données chargées.
|
|
43
|
+
|
|
44
|
+
:param conf: Configuration des données.
|
|
45
|
+
:return: Les données.
|
|
46
|
+
"""
|
|
47
|
+
# Get data
|
|
48
|
+
if isinstance(conf, str):
|
|
49
|
+
if RE_URL.match(conf):
|
|
50
|
+
return PLUGINS.hook_source["remote"]({"url": conf})
|
|
51
|
+
return PLUGINS.hook_source["local"]({"path": conf})
|
|
52
|
+
if isinstance(conf, dict):
|
|
53
|
+
LOGGER.info(f"""Getting data from source "{conf["source"]}".""")
|
|
54
|
+
if "source" not in conf:
|
|
55
|
+
raise ValueError("Expected a `data.source` value.")
|
|
56
|
+
try:
|
|
57
|
+
return PLUGINS.hook_source[conf["source"]](conf)
|
|
58
|
+
except KeyError as error:
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"""No loader found for source {conf["source"]}."""
|
|
61
|
+
) from error
|
|
62
|
+
raise TypeError(f"Wrong type for `data`: must be string or dict, not {type(conf)}.")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclasses.dataclass
|
|
66
|
+
class Preprocessor:
|
|
67
|
+
"""Gère l'application d'un prétraitement aux données.
|
|
68
|
+
|
|
69
|
+
:param functionname: Nom de la fonction à appliquer (définie dans un plugin).
|
|
70
|
+
:param root: Donnees à traiter.
|
|
71
|
+
:param args: Paramètres positionnels à passer à la fonction de traitement
|
|
72
|
+
(définis dans le fichier de configuration).
|
|
73
|
+
:param kwargs: Paramètres nommés à passer à la fonction de traitement
|
|
74
|
+
(définis dans le fichier de configuration).
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
functionname: str
|
|
78
|
+
root: Any
|
|
79
|
+
_: dataclasses.KW_ONLY
|
|
80
|
+
args: list = dataclasses.field(default_factory=list)
|
|
81
|
+
kwargs: dict = dataclasses.field(default_factory=dict)
|
|
82
|
+
|
|
83
|
+
def __call__(self, keys: list) -> Any:
|
|
84
|
+
return self.process(keys, self.root)
|
|
85
|
+
|
|
86
|
+
def process(self, keys: list, data: Any, *, prefix: list | None = None) -> None:
|
|
87
|
+
"""Applique le traitement aux données.
|
|
88
|
+
|
|
89
|
+
:param keys: Chemin des clefs sur laquelle appliquer le traitement.
|
|
90
|
+
Une clef valant `None` signifie : appliquer sur toutes les clefs.
|
|
91
|
+
:param data: Les données sur lesquelles appliquer le traitement.
|
|
92
|
+
:param prefix: Les clefs ayant mené à ces données.
|
|
93
|
+
Utile pour savoir si les données données en argument sont
|
|
94
|
+
l'ensemble des données, ou un sous-ensemble.
|
|
95
|
+
"""
|
|
96
|
+
if prefix is None:
|
|
97
|
+
prefix = []
|
|
98
|
+
if data is None:
|
|
99
|
+
data = self.root
|
|
100
|
+
if keys[0] is None:
|
|
101
|
+
if isinstance(data, list):
|
|
102
|
+
for key in range(len(data)):
|
|
103
|
+
self.process([key] + keys[1:], data, prefix=prefix)
|
|
104
|
+
elif isinstance(data, dict):
|
|
105
|
+
for key in data:
|
|
106
|
+
self.process([key] + keys[1:], data, prefix=prefix)
|
|
107
|
+
else:
|
|
108
|
+
if len(keys) == 1:
|
|
109
|
+
if self.functionname in PLUGINS.hook_preprocess_local:
|
|
110
|
+
data[keys[0]] = PLUGINS.hook_preprocess_local[self.functionname](
|
|
111
|
+
data[keys[0]], *self.args, **self.kwargs
|
|
112
|
+
)
|
|
113
|
+
elif self.functionname in PLUGINS.hook_preprocess_global:
|
|
114
|
+
PLUGINS.hook_preprocess_global[self.functionname](
|
|
115
|
+
self.root, prefix + keys, args=self.args, kwargs=self.kwargs
|
|
116
|
+
)
|
|
117
|
+
else:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
# pylint: disable=line-too-long
|
|
120
|
+
f"""No preprocessor "{self.functionname}" found in groups "ferronier.preprocess-local" or "ferronier.preprocess-global"."""
|
|
121
|
+
)
|
|
122
|
+
else:
|
|
123
|
+
self.process(keys[1:], data[keys[0]], prefix=prefix + [keys[0]])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def preprocess(data: Any, conf: dict | list) -> Any:
|
|
127
|
+
"""Applique le traitement des données définies dans le fichier de configuration.
|
|
128
|
+
|
|
129
|
+
:param data: Les données définies dans le fichier de configuration.
|
|
130
|
+
:param conf: La section `preprocess` du fichier de configuration.
|
|
131
|
+
:return: Les données, traitées.
|
|
132
|
+
"""
|
|
133
|
+
if isinstance(conf, dict):
|
|
134
|
+
for keys, function in conf.items():
|
|
135
|
+
if isinstance(function, str):
|
|
136
|
+
name = function
|
|
137
|
+
args = []
|
|
138
|
+
elif isinstance(function, list):
|
|
139
|
+
name, *args = function
|
|
140
|
+
else:
|
|
141
|
+
raise TypeError(f"Invalid type {type(function)} for function.")
|
|
142
|
+
Preprocessor(name, data, args=args)(
|
|
143
|
+
list(expand.escape_star(expand.split(keys)))
|
|
144
|
+
)
|
|
145
|
+
return data
|
|
146
|
+
if isinstance(conf, list):
|
|
147
|
+
for step in conf:
|
|
148
|
+
Preprocessor(
|
|
149
|
+
step["function"],
|
|
150
|
+
data,
|
|
151
|
+
args=step.get("args", []),
|
|
152
|
+
kwargs=step.get("kwargs", {}),
|
|
153
|
+
)(list(expand.escape_star(step["keys"])))
|
|
154
|
+
return data
|
|
155
|
+
raise TypeError(f"Invalid type {type(conf)} for argument `conf`.")
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Copyright 2025-2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Charge différents formats de fichiers"""
|
|
17
|
+
|
|
18
|
+
import csv
|
|
19
|
+
import io
|
|
20
|
+
import tomllib
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load_toml(data: bytes | str) -> Any:
|
|
25
|
+
"""Interprète l'argument comme une chaîne au format TOML."""
|
|
26
|
+
if isinstance(data, bytes):
|
|
27
|
+
return tomllib.loads(data.decode("utf8"))
|
|
28
|
+
if isinstance(data, str):
|
|
29
|
+
return tomllib.loads(data)
|
|
30
|
+
raise TypeError(f"Unsupported type `{type(data)}`.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load_csv(data: bytes | str) -> list[dict]:
|
|
34
|
+
"""Interprète l'argument comme une chaîne au format CSV."""
|
|
35
|
+
if isinstance(data, bytes):
|
|
36
|
+
data = data.decode("utf8")
|
|
37
|
+
return list(csv.DictReader(io.StringIO(data)))
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Copyright 2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Several data preprocessors."""
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
|
|
20
|
+
from ..expand import split
|
|
21
|
+
|
|
22
|
+
RE_FORMAT = re.compile(r"^{(\d+)}$")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def rename(
|
|
26
|
+
data: list | dict,
|
|
27
|
+
keys: list,
|
|
28
|
+
*,
|
|
29
|
+
args: list | None = None,
|
|
30
|
+
kwargs: dict | None = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
"""Move data around.
|
|
33
|
+
|
|
34
|
+
E.g. move `data["foo"]["bar"]` to `data["baz"][3]`.
|
|
35
|
+
"""
|
|
36
|
+
if args is None:
|
|
37
|
+
args = []
|
|
38
|
+
if len(args) != 1:
|
|
39
|
+
raise ValueError(
|
|
40
|
+
# pylint: disable=line-too-long
|
|
41
|
+
"Exactly one argument is accepted to `rename` preprocess function: the destination path."
|
|
42
|
+
)
|
|
43
|
+
if kwargs:
|
|
44
|
+
raise ValueError(
|
|
45
|
+
"No named arguments are accepted to `rename` preprocess function."
|
|
46
|
+
)
|
|
47
|
+
dest = list(split(args[0]))
|
|
48
|
+
source = keys
|
|
49
|
+
|
|
50
|
+
# Replacing interpolated strings
|
|
51
|
+
# That is, replace '{i}' by 'source[i]', and so on.
|
|
52
|
+
for i, key in enumerate(list(dest)):
|
|
53
|
+
try:
|
|
54
|
+
dest[i] = source[int(RE_FORMAT.match(dest[i]).groups()[0])] # type: ignore
|
|
55
|
+
except AttributeError:
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
# Setting data to the near destination item (so that data[dest[-1]] is the last item).
|
|
59
|
+
root = data
|
|
60
|
+
for key in dest[:-1]:
|
|
61
|
+
if key not in data:
|
|
62
|
+
data[key] = {} # type: ignore
|
|
63
|
+
data = data[key] # type: ignore
|
|
64
|
+
|
|
65
|
+
# Looking for the near source item
|
|
66
|
+
for key in source[:-1]:
|
|
67
|
+
root = root[key]
|
|
68
|
+
data[dest[-1]] = root[source[-1]] # type: ignore
|
|
69
|
+
del root[source[-1]]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Copyright 2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Load data from multiple sources"""
|
|
17
|
+
|
|
18
|
+
from ...data import load as parent_load
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def load(conf: dict) -> dict:
|
|
22
|
+
"""Load data from multiple sources"""
|
|
23
|
+
return {key: parent_load(value) for key, value in conf.get("data", {}).items()}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Copyright 2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Load data from local filesystem."""
|
|
17
|
+
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from ...plugins import PLUGINS
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def formatdata(data: Any, fileformat: str | None, path: str) -> Any:
|
|
24
|
+
"""Interpret data with a given format.
|
|
25
|
+
|
|
26
|
+
:param data: The data to parse.
|
|
27
|
+
:param fileformat: The file format (or None, if unknown).
|
|
28
|
+
:param path: The data path (file path or url). Used to guess file format,
|
|
29
|
+
if not explicitely defined.
|
|
30
|
+
"""
|
|
31
|
+
if fileformat is None and "." in path:
|
|
32
|
+
# Format is implicitely defined
|
|
33
|
+
fileformat = path.rsplit(".", maxsplit=1)[1]
|
|
34
|
+
if fileformat not in PLUGINS.hook_fileformat:
|
|
35
|
+
# No plugin defined to process the guessed file format.
|
|
36
|
+
# Back to no processing
|
|
37
|
+
fileformat = None
|
|
38
|
+
|
|
39
|
+
if fileformat:
|
|
40
|
+
try:
|
|
41
|
+
return PLUGINS.hook_fileformat[fileformat](data)
|
|
42
|
+
except KeyError as error:
|
|
43
|
+
raise ValueError(
|
|
44
|
+
f"""No processor found for file format `{fileformat}`."""
|
|
45
|
+
) from error
|
|
46
|
+
|
|
47
|
+
# No format defined: do not preprocess data
|
|
48
|
+
return data
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load(conf: dict) -> Any:
|
|
52
|
+
"""Load data from local filesystem."""
|
|
53
|
+
if isinstance(conf, dict):
|
|
54
|
+
try:
|
|
55
|
+
source = conf["path"]
|
|
56
|
+
except KeyError as error:
|
|
57
|
+
raise ValueError("Expected a `data.path` value.") from error
|
|
58
|
+
else:
|
|
59
|
+
raise TypeError(f"Unsupported type `{type(conf)}`.")
|
|
60
|
+
|
|
61
|
+
with open(source, mode="rb") as file:
|
|
62
|
+
return formatdata(
|
|
63
|
+
file.read(),
|
|
64
|
+
fileformat=conf.get("format", None),
|
|
65
|
+
path=conf["path"],
|
|
66
|
+
)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Copyright 2026 Louis Paternault
|
|
2
|
+
#
|
|
3
|
+
# This is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero Public License
|
|
14
|
+
# along with this. If not, see <http://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Merge data from multiple sources"""
|
|
17
|
+
|
|
18
|
+
import itertools
|
|
19
|
+
from collections.abc import Mapping, Sequence
|
|
20
|
+
|
|
21
|
+
from ...data import load as parent_load
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load(conf: dict) -> dict | list:
|
|
25
|
+
"""Merge data from multiple sources"""
|
|
26
|
+
data = [parent_load(value) for value in conf.get("data", {})]
|
|
27
|
+
if all(isinstance(item, Sequence) for item in data):
|
|
28
|
+
return list(itertools.chain(*data))
|
|
29
|
+
if all(isinstance(item, Mapping) for item in data):
|
|
30
|
+
merged = {}
|
|
31
|
+
for item in reversed(data): # First item has precedence
|
|
32
|
+
merged |= item
|
|
33
|
+
return merged
|
|
34
|
+
raise TypeError("All types of `merge` data must be lists or dicts.")
|