Skip to content
Snippets Groups Projects
Commit 7f8a7a93 authored by Paul McCarthy's avatar Paul McCarthy :mountain_bicyclist:
Browse files

ENH: Run config files through jinja, so we can inject variables (e.g. FSLDIR,

BIPDIR, etc)
parent cf99feef
No related branches found
No related tags found
1 merge request!4ENH: Config file templating
...@@ -26,6 +26,8 @@ import os ...@@ -26,6 +26,8 @@ import os
import os.path as op import os.path as op
import operator import operator
import jinja2 as j2
# python >= 3.11 # python >= 3.11
try: try:
...@@ -321,7 +323,7 @@ class Config: ...@@ -321,7 +323,7 @@ class Config:
@staticmethod @staticmethod
def load_config_file(cfgfile, selectors=None): def load_config_file(cfgfile, selectors=None, env=None):
"""Load a BIP configuration file. The file is assumed to be a TOML """Load a BIP configuration file. The file is assumed to be a TOML
file, named as described in the config_file_identifier documentation. file, named as described in the config_file_identifier documentation.
...@@ -337,16 +339,27 @@ class Config: ...@@ -337,16 +339,27 @@ class Config:
'T1_struct_bet_f' : 0.5 'T1_struct_bet_f' : 0.5
'T1_struct_fast_classes' : 3 'T1_struct_fast_classes' : 3
Re-labelling is not applied to the main "config.toml" configuration This re-labelling is not applied to the main "config.toml"
file. configuration file.
If selectors are provided, alternate values stored in the file may be
used - refer to the resolve_selectors method.
Configuration files may contain variables using Jinja2 syntax - if
an "env" dictionary is provided, the file contents are passed through
Jinja2 to resolve these variable references.
""" """
if selectors is None: if selectors is None:
selectors = {} selectors = {}
with open(cfgfile, 'rb') as f: with open(cfgfile, 'rt') as f:
settings = tomllib.load(f) settings = f.read()
if env is not None:
settings = j2.Template(settings).render(**env)
settings = tomllib.loads(settings)
ident = Config.config_file_identifier(cfgfile) ident = Config.config_file_identifier(cfgfile)
selectors = {k : selectors[k] for k in sorted(selectors.keys())} selectors = {k : selectors[k] for k in sorted(selectors.keys())}
settings = Config.resolve_selectors(settings, selectors) settings = Config.resolve_selectors(settings, selectors)
...@@ -378,6 +391,7 @@ class Config: ...@@ -378,6 +391,7 @@ class Config:
return settings return settings
# env=None - run all files through equivalent of op.expandvars
def __init__(self, cfgdir=None, selectors=None, overrides=None): def __init__(self, cfgdir=None, selectors=None, overrides=None):
"""Create a Config object. Read configuration files from cfgdir. """Create a Config object. Read configuration files from cfgdir.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment