]> kaliko git repositories - mpd-sima.git/blob - sima/utils/startopt.py
Aesthetic changes in usage messages
[mpd-sima.git] / sima / utils / startopt.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2009-2015, 2021 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, RawDescriptionHelpFormatter, SUPPRESS
23
24
25 from .utils import Wfile, Rfile, Wdir
26
27 DESCRIPTION = """
28 MPD_sima automagicaly queue new tracks in MPD playlist.
29
30 Command line options override their equivalent in configuration file.
31 If a positional arguments is provided MPD_sima execute the command and returns.
32 Commands available:
33 {}
34 """
35
36
37 def clean_dict(to_clean):
38     """Remove items which values are set to None/False"""
39     for k in list(to_clean.keys()):
40         if not to_clean.get(k):
41             to_clean.pop(k)
42
43 # COMMANDS LIST
44 CMDS = {'config-test': 'Test configuration (MPD connection and Tags plugin only)',
45         'create-db': 'Create the database',
46         'generate-config': 'Generate a configuration file to stdout',
47         }
48 # OPTIONS LIST
49 # pop out 'sw' value before creating Parser object.
50 # PAY ATTENTION:
51 #   If an option has to override its dual in conf file, the destination
52 #   identifier "dest" is to be named after that option in the conf file.
53 #   The supersedes_config_with_cmd_line_options method in ConfMan() (config.py)
54 #   is looking for command line option names identical to config file option
55 #   name it is meant to override.
56 OPTS = [
57     {
58         'sw': ['-l', '--log'],
59         'type': str,
60         'dest': 'logfile',
61         'action': Wfile,
62         'metavar': 'LOG',
63         'help': 'file to log message to, default is stdout/stderr'},
64     {
65         'sw': ['-v', '--log-level'],
66         'type': str,
67         'dest': 'verbosity',
68         'choices': ['debug', 'info', 'warning', 'error'],
69         'help': 'log messages verbosity, default is info'},
70     {
71         'sw': ['-p', '--pid'],
72         'dest': 'pidfile',
73         'action': Wfile,
74         'metavar': 'FILE',
75         'help': 'file to save PID to, default is not to store pid'},
76     {
77         'sw': ['-d', '--daemon'],
78         'dest': 'daemon',
79         'action': 'store_true',
80         'help': 'daemonize process'},
81     {
82         'sw': ['-S', '--host'],
83         'dest': 'host',
84         'help': 'host MPD in running on (IP or FQDN)'},
85     {
86         'sw': ['-P', '--port'],
87         'type': int,
88         'dest': 'port',
89         'help': 'port MPD in listening on'},
90     {
91         'sw': ['-c', '--config'],
92         'dest': 'conf_file',
93         'action': Rfile,
94         'metavar': 'CONFIG',
95         'help': 'configuration file to load'},
96     {  # TODO: To remove eventually in next major realese v0.18
97         'sw': ['--generate-config'],
98         'dest': 'generate_config',
99         'action': 'store_true',
100         'help': SUPPRESS},
101     {
102         'sw': ['--var-dir', '--var_dir'],
103         'dest': 'var_dir',
104         'action': Wdir,
105         'help': 'directory to store var content (ie. database, cache)'},
106     {  # TODO: To remove eventually in next major realese v0.18
107         'sw': ['--create-db'],
108         'action': 'store_true',
109         'dest': 'create_db',
110         'help': SUPPRESS},
111     {
112         'sw': ['command'],
113         'nargs': '?',
114         'choices': CMDS.keys(),
115         'help': 'command to run (cf. description or unix manual for more)'},
116 ]
117
118
119 class StartOpt:
120     """Command line management.
121     """
122
123     def __init__(self, script_info,):
124         self.parser = None
125         self.info = dict(script_info)
126         self.options = dict()
127         self.main()
128
129     def declare_opts(self):
130         """
131         Declare options in ArgumentParser object.
132         """
133         cmds = '\n'.join([f'    * {k}: {v}' for k, v in CMDS.items()])
134         self.parser = ArgumentParser(description=DESCRIPTION.format(cmds),
135                                      prog=self.info.get('prog'),
136                                      epilog='Happy Listening',
137                                      formatter_class=RawDescriptionHelpFormatter,
138                                      )
139         self.parser.add_argument('--version', action='version',
140                         version='%(prog)s {version}'.format(**self.info))
141         # Add all options declare in OPTS
142         for opt in OPTS:
143             opt_names = opt.pop('sw')
144             self.parser.add_argument(*opt_names, **opt)
145
146     def main(self):
147         """
148         Look for env. var and parse command line.
149         """
150         self.declare_opts()
151         options = vars(self.parser.parse_args())
152         # Set log file to os.devnull in daemon mode to avoid logging to
153         # std(out|err).
154         # TODO: Probably useless. To be checked
155         #if options.__dict__.get('daemon', False) and \
156         #        not options.__dict__.get('logfile', False):
157         #    options.__dict__['logfile'] = devnull
158         self.options.update(options)
159         clean_dict(self.options)
160
161
162 # VIM MODLINE
163 # vim: ai ts=4 sw=4 sts=4 expandtab