]> kaliko git repositories - mpd-sima.git/blob - sima/utils/startopt.py
e39330431711290d09e4e0095a85146aca8d53b8
[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':['--generate-config'],
86         'dest': 'generate_config',
87         'action': 'store_true',
88         'help': 'Generate a sample configuration file to stdout according to the current\
89          configuration. You can put other options with this one to get them in\
90          the generated configuration.'},
91     {
92         'sw':['--var-dir', '--var_dir'],
93         'dest': 'var_dir',
94         'action': Wdir,
95         'help': 'Directory to store var content (ie. database, cache)'},
96     {
97         'sw': ['--create-db'],
98         'action': 'store_true',
99         'dest': 'create_db',
100         'help': '''Create database and exit, use destination
101                    specified in --var_dir or standard location.'''},
102     {
103         'sw':['--queue-mode', '-q'],
104         'dest': 'queue_mode',
105         'choices': ['track', 'top', 'album'],
106         #'help': 'Queue mode in [track, top, album]',
107         'help': SUPPRESS, },
108     {
109         'sw':['--purge-history'],
110         'action': 'store_true',
111         'dest': 'do_purge_history',
112         'help': SUPPRESS},
113 ]
114
115
116 class StartOpt:
117     """Command line management.
118     """
119
120     def __init__(self, script_info,):
121         self.parser = None
122         self.info = dict(script_info)
123         self.options = dict()
124         self.main()
125
126     def declare_opts(self):
127         """
128         Declare options in ArgumentParser object.
129         """
130         self.parser = ArgumentParser(description=DESCRIPTION,
131                                      prog=self.info.get('prog'),
132                                      epilog='Happy Listening',
133                                     )
134         self.parser.add_argument('--version', action='version',
135                         version='%(prog)s {version}'.format(**self.info))
136         # Add all options declare in OPTS
137         for opt in OPTS:
138             opt_names = opt.pop('sw')
139             self.parser.add_argument(*opt_names, **opt)
140
141     def main(self):
142         """
143         Look for env. var and parse command line.
144         """
145         self.declare_opts()
146         options = vars(self.parser.parse_args())
147         # Set log file to os.devnull in daemon mode to avoid logging to
148         # std(out|err).
149         # TODO: Probably useless. To be checked
150         #if options.__dict__.get('daemon', False) and \
151         #        not options.__dict__.get('logfile', False):
152         #    options.__dict__['logfile'] = devnull
153         self.options.update(options)
154         clean_dict(self.options)
155
156
157 # VIM MODLINE
158 # vim: ai ts=4 sw=4 sts=4 expandtab