Secretary#

Example#

Here is an example of how a CLI download manager might use Secretary for its configuration.

cli_config.py file:

# Imports
from pathlib import Path
from libjam import Secretary

# Defining defaults
default_downloads_dir = Path.home() / 'Downloads'
if not default_downloads_dir.is_dir():
  default_downloads_dir = None
defaults = {
  'downloads-directory': default_downloads_dir,
}

# Config template
template = '''\
# An override for the default downloads directory
# downloads-directory = ''
'''

# Initialising config
secretary = Secretary('download-manager')
config = secretary.file('config', defaults, template)

# Validating values
downloads_dir = config.get('downloads-directory')
if not downloads_dir:
  config.error(
    'Could not automatically find an existing Downloads directory.',
    "Please specify the 'downloads-directory' manually.",
  )
downloads_dir = Path(downloads_dir)
if not downloads_dir.is_dir():
  config.error("The specified 'downloads-directory' does not exist.")

main_cli.py file:

from .cli_config import downloads_dir
from .download_manager import DownloadManager

download_manager = DownloadManager(downloads_dir)

# The rest of the program...

Example error:

$ python -m download_manager.cli
Configuration error in ~/.config/download-manager/config.toml:
Could not automatically find an existing Downloads directory.
Please specify the 'downloads-directory' manually.

API#

class libjam.Secretary(program: str, author: str = None, version: str = None, roaming: bool = False, ensure_exists: bool = False)#

Program config file manager.

This class is functionally a wrapper around the user_config_dir function of the platformdirs module, but with the addition of the file method.

The ensure_exists option is passed down to Files created by the file method, if not specified otherwise.

file(name: str, defaults: dict = {}, template: str = '', ensure_exists: bool = None, exit_on_error: bool = True) File#

Creates a new configuration File.

class libjam.File(file, template: str, defaults: dict, ensure_exists: bool, exit_on_error: bool)#

Bases: UserDict

A program configuration file.

Derived from the collections.UserDict class, so it can be used like a regular dictionary.

reload()#

Updates the config by reading it from the file.

error(*lines: str)#

Prints an error message to stderr and calls sys.exit with an appropriate exit code.