]> kaliko git repositories - mpd-sima.git/blob - sima/utils/startopt.py
Improved CLI error handling
[mpd-sima.git] / sima / utils / startopt.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Jack Kaliko <kaliko@azylum.org>
4 #
5 #  This file is part of sima
6 #
7 #  sima is free software: you can redistribute it and/or modify
8 #  it under the terms of the GNU General Public License as published by
9 #  the Free Software Foundation, either version 3 of the License, or
10 #  (at your option) any later version.
11 #
12 #  sima is distributed in the hope that it will be useful,
13 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #  GNU General Public License for more details.
16 #
17 #  You should have received a copy of the GNU General Public License
18 #  along with sima.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 #
21
22 from argparse import (ArgumentParser, SUPPRESS)
23
24
25 from .utils import Wfile, Rfile, Wdir
26
27 DESCRIPTION = """
28 MPD_sima automagicaly queue new tracks in MPD playlist.
29 Command line options override their equivalent in configuration file."""
30
31
32 def clean_dict(to_clean):
33     """Remove items which values are set to None/False"""
34     for k in list(to_clean.keys()):
35         if not to_clean.get(k):
36             to_clean.pop(k)
37
38
39 # OPTIONS LIST
40 # pop out 'sw' value before creating Parser object.
41 # PAY ATTENTION:
42 #   If an option has to override its dual in conf file, the destination
43 #   identifier "dest" is to be named after that option in the conf file.
44 #   The supersedes_config_with_cmd_line_options method in ConfMan() (config.py)
45 #   is looking for command line option names identical to config file option
46 #   name it is meant to override.
47 OPTS = [
48     {
49         'sw':['-l', '--log'],
50         'type': str,
51         'dest': 'logfile',
52         'action': Wfile,
53         'help': 'file to log message to, default is stdout/stderr'},
54     {
55         'sw':['-v', '--log-level'],
56         'type': str,
57         'dest': 'verbosity',
58         'choices': ['debug', 'info', 'warning', 'error'],
59         'help': 'Log messages verbosity, default is info'},
60     {
61         'sw': ['-p', '--pid'],
62         'dest': 'pidfile',
63         'action': Wfile,
64         'help': 'file to save PID to, default is not to store pid'},
65     {
66         'sw': ['-d', '--daemon'],
67         'dest': 'daemon',
68         'action': 'store_true',
69         'help': 'Daemonize process.'},
70     {
71         'sw': ['-S', '--host'],
72         'dest': 'host',
73         'help': 'Host MPD in running on (IP or FQDN)'},
74     {
75         'sw': ['-P', '--port'],
76         'type': int,
77         'dest': 'port',
78         'help': 'Port MPD in listening on'},
79     {
80         'sw':['-c', '--config'],
81         'dest': 'conf_file',
82         'action': Rfile,
83         'help': 'Configuration file to load'},
84     {
85         'sw':['--var_dir'],
86         'dest': 'var_dir',
87         'action': Wdir,
88         'help': 'Directory to store var content (ie. database, cache)'},
89     {
90         'sw': ['--create-db'],
91         'action': 'store_true',
92         'dest': 'create_db',
93         'help': '''Create database and exit, use destination
94                    specified in --var_dir or standard location.'''},
95     {
96         'sw':['--queue-mode', '-q'],
97         'dest': 'queue_mode',
98         'choices': ['track', 'top', 'album'],
99         #'help': 'Queue mode in [track, top, album]',
100         'help': SUPPRESS, },
101     {
102         'sw':['--purge_history'],
103         'action': 'store_true',
104         'dest': 'do_purge_history',
105         'help': SUPPRESS},
106 ]
107
108
109 class StartOpt(object):
110     """Command line management.
111     """
112
113     def __init__(self, script_info,):
114         self.parser = None
115         self.info = dict(script_info)
116         self.options = dict()
117         self.main()
118
119     def declare_opts(self):
120         """
121         Declare options in ArgumentParser object.
122         """
123         self.parser = ArgumentParser(description=DESCRIPTION,
124                                      prog=self.info.get('prog'),
125                                      epilog='Happy Listening',
126                                     )
127         self.parser.add_argument('--version', action='version',
128                         version='%(prog)s {version}'.format(**self.info))
129         # Add all options declare in OPTS
130         for opt in OPTS:
131             opt_names = opt.pop('sw')
132             self.parser.add_argument(*opt_names, **opt)
133
134     def main(self):
135         """
136         Look for env. var and parse command line.
137         """
138         self.declare_opts()
139         options = vars(self.parser.parse_args())
140         # Set log file to os.devnull in daemon mode to avoid logging to
141         # std(out|err).
142         # TODO: Probably useless. To be checked
143         #if options.__dict__.get('daemon', False) and \
144         #        not options.__dict__.get('logfile', False):
145         #    options.__dict__['logfile'] = devnull
146         self.options.update(options)
147         clean_dict(self.options)
148
149
150 # VIM MODLINE
151 # vim: ai ts=4 sw=4 sts=4 expandtab