source: ogCli-Git/ogcli @ f88bcf7

Last change on this file since f88bcf7 was 5c11376, checked in by Jose M. Guisado Gomez <guigom@…>, 2 years ago

Fix --help

Non-method attributes are shown using dir() when listing available
commands.

usage: ogcli [-h] [{create,list,restore,rest,send,set,setup}]

'rest' is a class instance of OgRest? and must not be
shown when listing available commands.

Method members of OgCLI class are the available commands that ogcli can
execute.
Use inspect module in order to get class members (getmembers) and filter
only those that are a method (ismethod).

usage: ogcli [-h] [{create,list,restore,send,set,setup}]

Fixes: 0f2d1f1dba4 ("Show all valid commands when running ogcli --help")

  • Property mode set to 100755
File size: 1.5 KB
Line 
1#!/usr/bin/env python3
2
3# Copyright (C) 2020-2021 Soleta Networks <info@soleta.eu>
4#
5# This program is free software: you can redistribute it and/or modify it under
6# the terms of the GNU Affero General Public License as published by the
7# Free Software Foundation; either version 3 of the License, or
8# (at your option) any later version.
9
10from inspect import ismethod, getmembers
11
12from cli.cli import OgCLI
13import argparse
14import json
15import sys
16
17OG_CLI_CFG_PATH="/opt/opengnsys/etc/ogcli.json"
18
19class CLI():
20        def __init__(self):
21                try:
22                        with open(OG_CLI_CFG_PATH, 'r') as json_file:
23                                self.cfg = json.load(json_file)
24                except json.JSONDecodeError:
25                        sys.exit(f'ERROR: Failed parse malformed JSON file '
26                                 f'{OG_CLI_CFG_PATH}')
27                except:
28                        sys.exit(f'ERROR: cannot open {OG_CLI_CFG_PATH}')
29
30                required_cfg_params = {'api_token', 'ip', 'port'}
31                difference_cfg_params = required_cfg_params - self.cfg.keys()
32                if len(difference_cfg_params) > 0:
33                        sys.exit(f'Missing {difference_cfg_params} key in '
34                                 f'json config file')
35
36                self.ogcli = OgCLI(self.cfg)
37
38                parser = argparse.ArgumentParser(prog='ogcli')
39                parser.add_argument('command', help='Subcommand to run', nargs='?',
40                                    choices=[attr for attr, _ in getmembers(self.ogcli, lambda x: ismethod(x))
41                                             if not attr.startswith('_')])
42                args = parser.parse_args(sys.argv[1:2])
43
44                if not hasattr(self.ogcli, args.command):
45                        parser.print_help()
46                        sys.exit('Unknown command')
47
48                # Call the command with the same name.
49                getattr(self.ogcli, args.command)(sys.argv[2:])
50
51if __name__ == "__main__":
52        CLI()
Note: See TracBrowser for help on using the repository browser.