config2py.tools#

Various tools

Functions

extract_exports(exports, *[, on_missing])

Get a dict of {name: value} pairs from the name="value" pairs of unix export lines (that is, lines of the ``export NAME="VALUE" format

get_configs_local_store([config_src, ...])

Get the local store of configs.

simple_config_getter([configs_src, ...])

Make a simple config getter from a "central" config source specification.

source_config_params(*config_params)

A decorator factory that sources config params, based on their names, to a config getter that will be provided when calling the wrapped function.

Classes

Configs

SecureTextFiles(*args[, follow_symlinks, ...])

A dol.TextFiles (one text file per key) whose value files are 0o600.

config2py.tools.Configs#

alias of SecureTextFiles

class config2py.tools.SecureTextFiles(*args, follow_symlinks=True, on_unsafe_folder='warn', **kwargs)[source]#

Bases: TextFiles

A dol.TextFiles (one text file per key) whose value files are 0o600.

Config values are often secrets (API keys); plain TextFiles writes them with the umask default (commonly world-readable 0o644). Still an isinstance of TextFiles, so it is a drop-in replacement (see i2mint/config2py#33).

Like TextFiles, values are UTF-8 on disk whatever the locale, and a failed write raises KeyError. Unlike it, the value is encoded before the file is opened, so an unencodable value doesn’t leave an emptied file behind (see i2mint/config2py#35).

Like TextFiles (and open), a value file that is a symlink is followed, and its target is the file written (and tightened to 0o600). That is deliberate: it keeps value files symlinked from elsewhere (a dotfiles repo, say) working, and in config2py’s own configs folder (0o700) only its owner can plant a link (see i2mint/config2py#37). If others can write to a folder you pass in, they can plant a link that redirects your secrets: the store warns about such a folder (on_unsafe_folder), and follow_symlinks=False refuses to write through a link (see i2mint/config2py#45).

__setitem__ relies on three dol internals: _id_of_key, store.validate_key and _data_of_obj. dol is unpinned, so test_secure_text_files_dol_contract checks they still exist.

config2py.tools.extract_exports(exports, *, on_missing='warn')[source]#

Get a dict of {name: value} pairs from the name="value" pairs of unix export lines (that is, lines of the ``export NAME="VALUE" format

Parameters:
  • exports – Filepath (str or os.PathLike) or string contents thereof

  • on_missing (str) – What to do when exports looks like a filepath (a single, non-blank line with no export in it) that is not an existing file: "warn" (the default) issues a MissingConfigFileWarning and returns {}, "raise" raises FileNotFoundError, "ignore" returns {} (see i2mint/config2py#27).

Return type:

dict

Returns:

A dict of extracted {name: value} pairs

>>> extract_exports('export KEY="secret"\nexport TOKEN="arbitrary"')
{'KEY': 'secret', 'TOKEN': 'arbitrary'}
>>> extract_exports('export KEY="secret"')  # a single line of content works too
{'KEY': 'secret'}

A mistyped path is not silently read as empty content:

>>> extract_exports('no/such/path/.env', on_missing='raise')
Traceback (most recent call last):
  ...
FileNotFoundError: [Errno 2] No such config file: 'no/such/path/.env'

Use case:#

You have access to environment variables through os.environ, but if you want to extract exports from only a specific file (env vars are often placed in different linked files), or the exports are defined in a string you hold, then this simple parser can be useful.

config2py.tools.get_configs_local_store(config_src='/home/runner/.config/config2py/configs', *, configs_name='configs', follow_symlinks=True, on_unsafe_folder='warn', kind='auto')[source]#

Get the local store of configs.

Parameters:
  • config_src – A specification of the local config store. By default: If it’s a directory, it’s assumed to be a folder of text files. If it’s a file, it’s assumed to be an ini or cfg file. If it’s a string, it’s assumed to be an app name, from which to create a folder (a pathlib.Path is always a path).

  • follow_symlinks (bool) – Whether the store may write through a symlink at a value (or ini) file’s path. False refuses to (see i2mint/config2py#45).

  • on_unsafe_folder (str) – "warn" (default), "raise" or "ignore" when a folder store’s root (or, for an ini file, its folder; a sticky one like /tmp is fine) is owned by another user or writable by its group or by others (see SecureTextFiles).

  • kind (str) – How to read config_src: "auto" (default), "path" or "app". In "auto" mode, a pathlib.Path, an absolute path, or a string containing os.sep or os.altsep is a path, and any other string is an app name, even if a directory of that name exists in the current working directory (so as not to change where existing callers read and write; only an existing .ini/.cfg file of that name is used as a file). kind="path" makes a bare name such as "configs" mean that directory (or file); kind="app" makes any string an app name. See i2mint/config2py#28.

The default, DFLT_CONFIG_FOLDER, is config2py’s own configs folder. It is created here, on first use, rather than at import (see i2mint/config2py#26).

config2py.tools.simple_config_getter(configs_src='/home/runner/.config/config2py/configs', *, first_look_in_env_vars=True, ask_user_if_key_not_found=None, config_store_factory=<function get_configs_local_store>)[source]#

Make a simple config getter from a “central” config source specification.

The purpose of this function is to implement a common pattern of getting configs: One that, by default (but optionally), looks in environment variables first, then in a central config store, created via a simple configs_src specification and then, if the key is not found in this “central” store, optionally (but not by default) asks the user for the value and stores it in the central config store.

Parameters:
  • configs_src (str) – A specification of the central config store. By default: If it’s a directory (with at least a slash), it’s assumed to be a folder of text files. If it’s a file, it’s assumed to be an ini or cfg file. If it’s a string, it’s assumed to be an app name, from which to create a folder

  • first_look_in_env_vars (bool) – Whether to look in environment variables first

  • ask_user_if_key_not_found (bool) – Whether to ask the user if the key is not found (and subsequently store the key in the central config store)

  • config_store_factory (Callable) – A function that takes a config source specification and returns the central config store

config2py.tools.source_config_params(*config_params)[source]#

A decorator factory that sources config params, based on their names, to a config getter that will be provided when calling the wrapped function.

Parameters:

config_params – The names of the config params to source

Returns:

A decorator that sources the config params to the config getter

>>> @source_config_params('a', 'b')
... def foo(a, b, c):
...     return a, b, c
>>> config = {'a': 1, 'b': 2, 'c': 3}
>>> foo(a='a', b='b', c=3, _config_getter=config.get)
(1, 2, 3)

A common use case is when you need to partialize a function with configs but the config source is not defined yet.

>>> from functools import partial
>>> bar = partial(foo, a='a')

a is set, but you’ll be able to call bar with different config sources,

>>> bar(b='b', c=3, _config_getter=config.get)
(1, 2, 3)
>>> other_config = {'a': 11, 'b': 22, 'c': 33}
>>> bar(b='b', c=3, _config_getter=other_config.get)
(11, 22, 3)

What if the function as kwargs? No problem, the decorator will handle it. Just make sure to use the same names for the kwargs as the config params.

>>> @source_config_params('a', 'b', 'd')
... def foo(a, b, c, **kwargs):
...     return a, b, c, kwargs
>>> config = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> foo(a='a', b='b', c=3, d='d', _config_getter=config.get)
(1, 2, 3, {'d': 4})

As you can see, d is sourced as well.