forked from loktacar/wallpapermaker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
84 lines (63 loc) · 2.08 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import copy
import imp
import sys
import os
import logging
from appdirs import AppDirs
from docopt import docopt
import ConfigParser
from plugins import option_plugins
appname = 'wpmaker'
appauthor = 'viktor'
config_file_name = '%s.conf' % appname
options = [op() for op in option_plugins]
logger = logging.getLogger('root')
def get_appdirs_paths():
appdirs = AppDirs(appname, appauthor)
dirs = (appdirs.user_data_dir, appdirs.site_data_dir)
return [os.path.join(dir, config_file_name) for dir in dirs]
def get_doc():
doc = """Usage: wpmaker.py [options]
Options:
"""
for op in sorted(options, key=lambda op: op.option):
doc += """%s
""" % op.get_doc_line()
doc += """ -h --help Displays this help message
Configuration files:
"""
for i, dir in enumerate(get_appdirs_paths()):
doc += """ (%s) %s
""" % (i, dir)
return doc
def get_config():
from docopt import docopt
doc_options = docopt(get_doc())
config = {}
# Set config to defaults
default_section = 'default'
for op in options:
config[op.option] = op.default
if op.option == 'section':
default_section = op.default
# Get config file configuration
files = get_appdirs_paths()
cfg = ConfigParser.SafeConfigParser()
cfg_files = cfg.read(files)
# Set config file section and read files
file_section = doc_options['--section'] if doc_options['--section'] else default_section
files_read = cfg.read(files)
# Parse config file
if len(files_read):
if not cfg.has_section(file_section):
raise ValueError('Section %s not found' % file_section)
for op in options:
if cfg.has_option(file_section, op.option):
config[op.option] = op.parse(cfg.get(file_section, op.option))
# Parse command line options
for key in doc_options:
if key[:2] == '--' and doc_options[key] is not None:
for op in options:
if op.option == key[2:]:
config[key[2:]] = op.parse(doc_options[key])
return config