"Fossies" - the Fresh Open Source Software Archive

Member "http-prompt-2.1.0/http_prompt/config.py" (5 Mar 2021, 1780 Bytes) of package /linux/www/http-prompt-2.1.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "config.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.0.0_vs_2.1.0.

    1 """Functions that deal with the user configuration."""
    2 
    3 import os
    4 import shutil
    5 
    6 from . import defaultconfig
    7 from . import xdg
    8 
    9 
   10 def get_user_config_path():
   11     """Get the path to the user config file."""
   12     return os.path.join(xdg.get_config_dir(), 'config.py')
   13 
   14 
   15 def initialize():
   16     """Initialize a default config file if it doesn't exist yet.
   17 
   18     Returns:
   19         tuple: A tuple of (copied, dst_path). `copied` is a bool indicating if
   20             this function created the default config file. `dst_path` is the
   21             path of the user config file.
   22     """
   23     dst_path = get_user_config_path()
   24     copied = False
   25     if not os.path.exists(dst_path):
   26         src_path = os.path.join(os.path.dirname(__file__), 'defaultconfig.py')
   27         shutil.copyfile(src_path, dst_path)
   28         copied = True
   29     return copied, dst_path
   30 
   31 
   32 def _module_to_dict(module):
   33     attrs = {}
   34     attr_names = filter(lambda n: not n.startswith('_'), dir(module))
   35     for name in attr_names:
   36         value = getattr(module, name)
   37         attrs[name] = value
   38     return attrs
   39 
   40 
   41 def load_default():
   42     """Return default config as a dict."""
   43     return _module_to_dict(defaultconfig)
   44 
   45 
   46 def load_user():
   47     """Read user config file and return it as a dict."""
   48     config_path = get_user_config_path()
   49     config = {}
   50 
   51     # TODO: This may be overkill and too slow just for reading a config file
   52     with open(config_path) as f:
   53         code = compile(f.read(), config_path, 'exec')
   54     exec(code, config)
   55 
   56     keys = list(config.keys())
   57     for k in keys:
   58         if k.startswith('_'):
   59             del config[k]
   60 
   61     return config
   62 
   63 
   64 def load():
   65     """Read default and user config files and return them as a dict."""
   66     config = load_default()
   67     config.update(load_user())
   68     return config