config
¶
- class invoke.config.Config(overrides: Dict[str, Any] | None = None, defaults: Dict[str, Any] | None = None, system_prefix: str | None = None, user_prefix: str | None = None, project_location: PathLike | None = None, runtime_path: PathLike | None = None, lazy: bool = False)¶
Invoke’s primary configuration handling class.
See 配置 for details on the configuration system this class implements, including the configuration hierarchy. The rest of this class’ documentation assumes familiarity with that document.
Access
Configuration values may be accessed and/or updated using dict syntax:
config['foo']
or attribute syntax:
config.foo
Nesting works the same way - dict config values are turned into objects which honor both the dictionary protocol and the attribute-access method:
config['foo']['bar'] config.foo.bar
A note about attribute access and methods
This class implements the entire dictionary protocol: methods such as
keys
,values
,items
,pop
and so forth should all function as they do on regular dicts. It also implements new config-specific methods such asload_system
,load_collection
,merge
,clone
, etc.警告
Accordingly, this means that if you have configuration options sharing names with these methods, you must use dictionary syntax (e.g.
myconfig['keys']
) to access the configuration data.Lifecycle
At initialization time,
Config
:creates per-level data structures;
stores any levels supplied to
__init__
, such as defaults or overrides, as well as the various config file paths/filename patterns;and loads config files, if found (though typically this just means system and user-level files, as project and runtime files need more info before they can be found and loaded.)
This step can be skipped by specifying
lazy=True
.
At this point,
Config
is fully usable - and because it pre-emptively loads some config files, those config files can affect anything that comes after, like CLI parsing or loading of task collections.In the CLI use case, further processing is done after instantiation, using the
load_*
methods such asload_overrides
,load_project
, etc:the result of argument/option parsing is applied to the overrides level;
a project-level config file is loaded, as it’s dependent on a loaded tasks collection;
a runtime config file is loaded, if its flag was supplied;
then, for each task being executed:
per-collection data is loaded (only possible now that we have collection & task in hand);
shell environment data is loaded (must be done at end of process due to using the rest of the config as a guide for interpreting env var names.)
At this point, the config object is handed to the task being executed, as part of its execution
Context
.Any modifications made directly to the
Config
itself after this point end up stored in their own (topmost) config level, making it easier to debug final values.Finally, any deletions made to the
Config
(e.g. applications of dict-style mutators likepop
,clear
etc) are also tracked in their own structure, allowing the config object to honor such method calls without mutating the underlying source data.Special class attributes
The following class-level attributes are used for low-level configuration of the config system itself, such as which file paths to load. They are primarily intended for overriding by subclasses.
prefix
: Supplies the default value forfile_prefix
(directly) andenv_prefix
(uppercased). See their descriptions for details. Its default value is"invoke"
.file_prefix
: The config file ‘basename’ default (though it is not a literal basename; it can contain path parts if desired) which is appended to the configured values ofsystem_prefix
,user_prefix
, etc, to arrive at the final (pre-extension) file paths.Thus, by default, a system-level config file path concatenates the
system_prefix
of/etc/
with thefile_prefix
ofinvoke
to arrive at paths like/etc/invoke.json
.Defaults to
None
, meaning to use the value ofprefix
.env_prefix
: A prefix used (along with a joining underscore) to determine which environment variables are loaded as the env var configuration level. Since its default is the value ofprefix
capitalized, this means env vars likeINVOKE_RUN_ECHO
are sought by default.Defaults to
None
, meaning to use the value ofprefix
.
在 1.0 版本加入.
- __init__(overrides: Dict[str, Any] | None = None, defaults: Dict[str, Any] | None = None, system_prefix: str | None = None, user_prefix: str | None = None, project_location: PathLike | None = None, runtime_path: PathLike | None = None, lazy: bool = False)¶
Creates a new config object.
- 参数:
defaults (dict) – A dict containing default (lowest level) config data. Default:
global_defaults
.overrides (dict) – A dict containing override-level config data. Default:
{}
.system_prefix (str) –
Base path for the global config file location; combined with the prefix and file suffixes to arrive at final file path candidates.
Default:
/etc/
(thus e.g./etc/invoke.yaml
or/etc/invoke.json
).user_prefix (str) –
Like
system_prefix
but for the per-user config file. These variables are joined as strings, not via path-style joins, so they may contain partial file paths; for the per-user config file this often means a leading dot, to make the final result a hidden file on most systems.Default:
~/.
(e.g.~/.invoke.yaml
).project_location (str) – Optional directory path of the currently loaded
Collection
(as loaded byLoader
). When non-empty, will trigger seeking of per-project config files in this directory.runtime_path (str) –
Optional file path to a runtime configuration file.
Used to fill the penultimate slot in the config hierarchy. Should be a full file path to an existing file, not a directory path or a prefix.
lazy (bool) –
Whether to automatically load some of the lower config levels.
By default (
lazy=False
),__init__
automatically callsload_system
andload_user
to load system and user config files, respectively.For more control over what is loaded when, you can say
lazy=True
, and no automatic loading is done.备注
If you give
defaults
and/oroverrides
as__init__
kwargs instead of waiting to useload_defaults
orload_overrides
afterwards, those will still end up ‘loaded’ immediately.
- clone(into: Type[Config] | None = None) Config ¶
Return a copy of this configuration object.
The new object will be identical in terms of configured sources and any loaded (or user-manipulated) data, but will be a distinct object with as little shared mutable state as possible.
Specifically, all
dict
values within the config are recursively recreated, with non-dict leaf values subjected tocopy.copy
(note: notcopy.deepcopy
, as this can cause issues with various objects such as compiled regexen or threading locks, often found buried deep within rich aggregates like API or DB clients).The only remaining config values that may end up shared between a config and its clone are thus those ‘rich’ objects that do not
copy.copy
cleanly, or compound non-dict objects (such as lists or tuples).- 参数:
into –
A
Config
subclass that the new clone should be “upgraded” to.Used by client libraries which have their own
Config
subclasses that e.g. define additional defaults; cloning “into” one of these subclasses ensures that any new keys/subtrees are added gracefully, without overwriting anything that may have been pre-defined.Default:
None
(just clone into another regularConfig
).- 返回:
A
Config
, or an instance of the class given tointo
.
在 1.0 版本加入.
- static global_defaults() Dict[str, Any] ¶
Return the core default settings for Invoke.
Generally only for use by
Config
internals. For descriptions of these values, see 默认配置值.Subclasses may choose to override this method, calling
Config.global_defaults
and applyingmerge_dicts
to the result, to add to or modify these values.在 1.0 版本加入.
- load_collection(data: Dict[str, Any], merge: bool = True) None ¶
Update collection-driven config data.
load_collection
is intended for use by the core task execution machinery, which is responsible for obtaining collection-driven data. See 基于 Collection 的配置 for details.在 1.0 版本加入.
- load_defaults(data: Dict[str, Any], merge: bool = True) None ¶
Set or replace the ‘defaults’ configuration level, from
data
.- 参数:
- 返回:
None
.
在 1.0 版本加入.
- load_overrides(data: Dict[str, Any], merge: bool = True) None ¶
Set or replace the ‘overrides’ configuration level, from
data
.- 参数:
- 返回:
None
.
在 1.0 版本加入.
- load_project(merge: bool = True) None ¶
Load a project-level config file, if possible.
Checks the configured
_project_prefix
value derived from the path given toset_project_location
, which is typically set to the directory containing the loaded task collection.Thus, if one were to run the CLI tool against a tasks collection
/home/myuser/code/tasks.py
,load_project
would seek out files like/home/myuser/code/invoke.yml
.- 参数:
merge (bool) – Whether to merge the loaded data into the central config. Default:
True
.- 返回:
None
.
在 1.0 版本加入.
- load_runtime(merge: bool = True) None ¶
Load a runtime-level config file, if one was specified.
When the CLI framework creates a
Config
, it sets_runtime_path
, which is a full path to the requested config file. This method attempts to load that file.- 参数:
merge (bool) – Whether to merge the loaded data into the central config. Default:
True
.- 返回:
None
.
在 1.0 版本加入.
- load_shell_env() None ¶
Load values from the shell environment.
load_shell_env
is intended for execution late in aConfig
object’s lifecycle, once all other sources (such as a runtime config file or per-collection configurations) have been loaded. Loading from the shell is not terrifically expensive, but must be done at a specific point in time to ensure the “only known config keys are loaded from the env” behavior works correctly.See 环境变量 for details on this design decision and other info re: how environment variables are scanned and loaded.
在 1.0 版本加入.
- load_system(merge: bool = True) None ¶
Load a system-level config file, if possible.
Checks the configured
_system_prefix
path, which defaults to/etc
, and will thus load files like/etc/invoke.yml
.- 参数:
merge (bool) – Whether to merge the loaded data into the central config. Default:
True
.- 返回:
None
.
在 1.0 版本加入.
- load_user(merge: bool = True) None ¶
Load a user-level config file, if possible.
Checks the configured
_user_prefix
path, which defaults to~/.
, and will thus load files like~/.invoke.yml
.- 参数:
merge (bool) – Whether to merge the loaded data into the central config. Default:
True
.- 返回:
None
.
在 1.0 版本加入.
- set_project_location(path: PathLike | str | None) None ¶
Set the directory path where a project-level config file may be found.
Does not do any file loading on its own; for that, see
load_project
.在 1.0 版本加入.
- class invoke.config.DataProxy¶
Helper class implementing nested dict+attr access for
Config
.Specifically, is used both for
Config
itself, and to wrap any other dicts assigned as config values (recursively).警告
All methods (of this object or in subclasses) must take care to initialize new attributes via
self._set(name='value')
, or they’ll run into recursion errors!在 1.0 版本加入.
- __hash__ = None¶
- __weakref__¶
对象的弱引用列表
- classmethod from_data(data: Dict[str, Any], root: DataProxy | None = None, keypath: Tuple[str, ...] = ()) DataProxy ¶
Alternate constructor for ‘baby’ DataProxies used as sub-dict values.
Allows creating standalone DataProxy objects while also letting subclasses like
Config
define their own__init__
without muddling the two.- 参数:
data (dict) – This particular DataProxy’s personal data. Required, it’s the Data being Proxied.
root – Optional handle on a root DataProxy/Config which needs notification on data updates.
keypath (tuple) – Optional tuple describing the path of keys leading to this DataProxy’s location inside the
root
structure. Required ifroot
was given (and vice versa.)
在 1.0 版本加入.
- invoke.config.copy_dict(source: Dict[str, Any]) Dict[str, Any] ¶
Return a fresh copy of
source
with as little shared state as possible.Uses
merge_dicts
under the hood, with an emptybase
dict; see its documentation for details on behavior.在 1.0 版本加入.
- invoke.config.excise(dict_: Dict[str, Any], keypath: Tuple[str, ...]) None ¶
Remove key pointed at by
keypath
from nested dictdict_
, if exists.在 1.0 版本加入.
- invoke.config.merge_dicts(base: Dict[str, Any], updates: Dict[str, Any]) Dict[str, Any] ¶
Recursively merge dict
updates
into dictbase
(mutatingbase
.)Values which are themselves dicts will be recursed into.
Values which are a dict in one input and not a dict in the other input (e.g. if our inputs were
{'foo': 5}
and{'foo': {'bar': 5}}
) are irreconciliable and will generate an exception.Non-dict leaf values are run through
copy.copy
to avoid state bleed.
备注
This is effectively a lightweight
copy.deepcopy
which offers protection from mismatched types (dict vs non-dict) and avoids some core deepcopy problems (such as how it explodes on certain object types).- 返回:
The value of
base
, which is mostly useful for wrapper functions likecopy_dict
.
在 1.0 版本加入.