Skip to content
Snippets Groups Projects
Select Git revision
  • c295b620ffd2ead44853da22b47c62cda9919ff9
  • master default protected
  • v0.1.24
  • v0.1.23
  • v0.1.22
  • v0.1.21
  • v0.1.19
  • v0.1.18
  • v0.1.17
  • v0.1.16
  • v0.1.15
  • v0.1.14
  • v1.1
  • v.0.1.12
  • v.0.1.11
  • v.0.1.10
  • v.0.1.9
  • v.0.1.8
  • v.0.1.7
  • v.0.1.6
  • v0.1.5
21 results

__init__.py

Blame
  • config.py 2.82 KiB
    #!/usr/bin/env python 
    #-*- coding: utf-8 -*-
    
    import os
    import toml
    from pathlib import Path
    
    
    def this_or_else(this: str, other: str) -> str:
        """
        Return this if this is a non-empty string
        otherwise return other
        """
        if this is None or this.strip() == "":
            return other
        else:
            return this
    
    
    def get_home() -> str:
        """
        Get the home directory from the environment variable
        """
        return os.environ.get("HOME")
    
    
    def get_dirs(application_name):
        """
        Get the XDG dirs for data and config
        """
        dirs = {}
    
        # Get home directory
        home = get_home()
    
        # Set defaults for xdg directories
        default_data_home = "{}/.local/share/{}".format(home, application_name)
        default_config_home = "{}/.config/{}".format(home, application_name)
    
        # Set dict value to environment variable or (if none set) to default value
        dirs["data"]   = this_or_else(os.environ.get("XDG_DATA_HOME"), default_data_home)
        dirs["config"] = this_or_else(os.environ.get("XDG_CONFIG_HOME"), default_config_home)
    
        return dirs
    
    
    def initialize_config(application_name: str, default_config: str) -> dict:
        """
        Initialize a configuration. If none exists, create a default one
        """
        # Get XDG dirs
        dirs = get_dirs(application_name)
    
        # Convert the default config to a dict
        default_config = toml.loads(default_config)
    
        # Generate a environment variable name from the application name
        # E.g. "foo bar" becomes "FOO_BAR_CONFIG_PATH"
        config_path_environment_variable = "{}_CONFIG_PATH".format(application_name.upper().replace(" ", "_"))
    
        # If the environment variable is set, use that as a config path, otherwise use the default one
        config_dir = this_or_else(os.environ.get(config_path_environment_variable), dirs["config"])
        config_path = "{}/config.toml".format(config_dir.rstrip("/"))
    
        # Create the config_dir if it doesn't exist
        if not Path.is_dir(Path(config_dir)):
            Path(config_dir).mkdir(parents=True, exist_ok=True)
            print("Config directory didn't exist, created directory: {}".format(config_dir))
    
        if not Path.is_file(Path(config_path)):
            write_config(config_path, default_config)
            print("Created new default config.toml at:\n{}".format(config_path))
            config = default_config
        else:
            config = read_config(config_path)
            print("Read config from: {}".format(config_path))
    
        return config
    
    
    def write_config(config_path: str, config: dict):
        """
        Write a dict as toml to a given path
        """
        with open(config_path, "w", encoding="utf-8") as f:
            toml.dump(config, f)
    
    
    def read_config(config_path: str) -> dict:
        """
        Read a config.toml from the given path,
        return a dict containing the config
        """
        with open(config_path, "r", encoding="utf-8") as f:
            config = toml.load(f)
        return config