Uh oh!
There was an error while loading. Please reload this page.
forked from cirosantilli/linux-kernel-module-cheat
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_function.py
More file actions
Latest commit
executable file
·491 lines (441 loc) · 19.4 KB
/
Copy pathcli_function.py
File metadata and controls
executable file
·491 lines (441 loc) · 19.4 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#!/usr/bin/env python3
'''
This file is GPLv3 like the rest of this repo.
However, you may use it in a project with any license through imports,
without affecting the license of the rest of your project, even if you include
this file in the project source tree, as long as you publish any modifications
made to this file.
'''
importargparse
importbisect
importcollections
importos
importsys
importlkmc.import_path
class_Argument:
def__init__(
self,
long_or_short_1,
long_or_short_2=None,
default=None,
dest=None,
help=None,
nargs=None,
**kwargs
):
self.args= []
# argparse is crappy and cannot tell us if arguments were given or not.
# We need that information to decide if the config file should override argparse or not.
# So we just use None as a sentinel.
self.kwargs= {'default': None}
shortname, longname, key, is_option=self.get_key(
long_or_short_1,
long_or_short_2,
dest
)
ifshortnameisnotNone:
self.args.append(shortname)
ifis_option:
self.args.append(longname)
else:
self.args.append(key)
self.kwargs['metavar'] =longname
ifdefaultisnotNoneandnargsisNone:
self.kwargs['nargs'] ='?'
ifdestisnotNone:
self.kwargs['dest'] =dest
ifnargsisnotNone:
self.kwargs['nargs'] =nargs
ifdefaultisTrueordefaultisFalse:
bool_action='store_true'
self.is_bool=True
else:
self.is_bool=False
ifdefaultisNoneand (
nargsin ('*', '+')
or ('action'inkwargsandkwargs['action'] =='append')
):
default= []
ifself.is_boolandnot'action'inkwargs:
self.kwargs['action'] =bool_action
ifhelpisnotNoneandhelp!='':
ifdefaultisnotNone:
ifhelp[-1] =='\n':
if'\n\n'inhelp[:-1]:
help+='\n'
elifhelp[-1] ==' ':
pass
else:
help+=' '
help+='Default: {}'.format(default)
self.kwargs['help'] =help
self.optional= (
defaultisnotNoneor
self.is_boolor
is_optionor
nargsin ('?', '*', '+')
)
self.kwargs.update(kwargs)
self.default=default
self.longname=longname
self.key=key
self.is_option=is_option
self.nargs=nargs
def__str__(self):
returnstr(self.args) +' '+str(self.kwargs)
@staticmethod
defget_key(
long_or_short_1,
long_or_short_2=None,
dest=None,
**kwargs
):
iflong_or_short_2isNone:
shortname=None
longname=long_or_short_1
else:
shortname=long_or_short_1
longname=long_or_short_2
iflongname[0] =='-':
key=longname.lstrip('-').replace('-', '_')
is_option=True
else:
key=longname.replace('-', '_')
is_option=False
ifdestisnotNone:
key=dest
returnshortname, longname, key, is_option
classCliFunction:
'''
A function that can be called either from Python code, or from the command line.
Features:
* single argument description in format very similar to argparse
* handle default arguments transparently in both cases
* expose a configuration file mechanism to get default parameters from a file
* fix some argparse.ArgumentParser() annoyances:
** allow dashes in positional arguments:
https://stackoverflow.com/questions/12834785/having-options-in-argparse-with-a-dash
** boolean defaults automatically use store_true or store_false, and add a --no-* CLI
option to invert them if set from the config
* from a Python call, get the corresponding CLI string list. See get_cli.
* easily determine if arguments were given on the command line
https://stackoverflow.com/questions/30487767/check-if-argparse-optional-argument-is-set-or-not/30491369
This somewhat duplicates: https://click.palletsprojects.com but:
* that decorator API is insane
* CLI + Python for single functions was wontfixed: https://github.com/pallets/click/issues/40
+
Oh, and I commented on that issue pointing to this alternative and they deleted my comment:
https://github.com/pallets/click/issues/40#event-2088718624 Lol. It could have been useful
for other Googlers and as an implementation reference.
'''
def__call__(self, **kwargs):
'''
Python version of the function call. Not called by cli() indirectly,
so can be overridden to distinguish between Python and CLI calls.
:type arguments: Dict
'''
returnself._do_main(kwargs)
def_do_main(self, kwargs):
returnself.main(**self._get_args(kwargs))
def__init__(self, default_config_file=None, description=None, extra_config_params=None):
self._arguments=collections.OrderedDict()
self._default_config_file=default_config_file
self._description=description
self.extra_config_params=extra_config_params
ifself._default_config_fileisnotNone:
self.add_argument(
'--config-file',
default=self._default_config_file,
help='Path to the configuration file to use'
)
def__str__(self):
return'\n'.join(str(arg[key]) forkeyinself._arguments)
def_get_args(self, kwargs):
'''
Resolve default arguments from the config file and CLI param defaults.
Add an extra _args_given argument which determines if an argument was given or not.
Args set from the config file count as given.
'''
args_with_defaults=kwargs.copy()
# Add missing args from config file.
config_file=None
args_given= {}
if'config_file'inargs_with_defaultsandargs_with_defaults['config_file'] isnotNone:
config_file=args_with_defaults['config_file']
args_given['config_file'] =True
else:
config_file=self._default_config_file
args_given['config_file'] =False
forkeyinself._arguments:
args_given[key] =not (
notkeyinargs_with_defaultsor
args_with_defaults[key] isNoneor
self._arguments[key].nargs=='*'andargs_with_defaults[key] == []
)
ifconfig_fileisnotNone:
ifos.path.exists(config_file):
config_configs= {}
config=lkmc.import_path.import_path(config_file)
ifself.extra_config_paramsisNone:
config.set_args(config_configs)
else:
config.set_args(config_configs, self.extra_config_params)
forkeyinconfig_configs:
ifkeynotinself._arguments:
raiseException('Unknown key in config file: '+key)
ifnotargs_given[key]:
args_with_defaults[key] =config_configs[key]
args_given[key] =True
elifargs_given['config_file']:
raiseException('Config file does not exist: '+config_file)
# Add missing args from hard-coded defaults.
forkeyinself._arguments:
argument=self._arguments[key]
# TODO: in (None, []) is ugly, and will probably go wrong at some point,
# there must be a better way to do it, but I'm lazy now to think.
if (notkeyinargs_with_defaults) orargs_with_defaults[key] in (None, []):
ifargument.optional:
args_with_defaults[key] =argument.default
else:
raiseException('Value not given for mandatory argument: '+key)
args_with_defaults['_args_given'] =args_given
if'config_file'inargs_with_defaults:
delargs_with_defaults['config_file']
returnargs_with_defaults
defadd_argument(
self,
*args,
**kwargs
):
argument=_Argument(*args, **kwargs)
self._arguments[argument.key] =argument
defcli_noexit(self, cli_args=None):
'''
Call the function from the CLI. Parse command line arguments
to get all arguments. Does not exit the program after running this function.
:return: the return of main
'''
parser=argparse.ArgumentParser(
description=self._description,
formatter_class=argparse.RawTextHelpFormatter,
)
forkeyinself._arguments:
argument=self._arguments[key]
parser.add_argument(*argument.args, **argument.kwargs)
# print(key)
# print(argument.args)
# print(argument.kwargs)
ifargument.is_bool:
new_longname='--no'+argument.longname[1:]
kwargs=argument.kwargs.copy()
kwargs['default'] =notargument.default
ifkwargs['action'] in ('store_true', 'store_false'):
kwargs['action'] ='store_false'
if'help'inkwargs:
delkwargs['help']
parser.add_argument(new_longname, dest=argument.key, **kwargs)
args=parser.parse_args(args=cli_args)
returnself._do_main(vars(args))
defcli(self, *args, **kwargs):
'''
Same as cli_noxit, but also exit the program with status equal to the
return value of main. main must return an integer for this to be used.
None is considered as 0.
'''
exit_status=self.cli_noexit(*args, **kwargs)
ifexit_statusisNone:
exit_status=0
sys.exit(exit_status)
defget_cli(self, **kwargs):
'''
:rtype: List[Type(str)]
:return: the canonical command line arguments arguments that would
generate this Python function call.
(--key, value) option pairs are grouped into tuples, and all
other values are grouped in their own tuple (positional_arg,)
or (--bool-arg,).
Arguments with default values are not added, but arguments
that are set by the config are also given.
The optional arguments are sorted alphabetically, followed by
positional arguments.
The long option name is used if both long and short versions
are given.
'''
options= []
positional_dict= {}
kwargs=self._get_args(kwargs)
forkeyinkwargs:
ifnotkeyin ('_args_given',):
argument=self._arguments[key]
default=argument.default
value=kwargs[key]
ifvalue!=default:
ifargument.is_option:
ifargument.is_bool:
ifvalue:
vals= [(argument.longname,)]
else:
vals= [('--no-'+argument.longname[2:],)]
elif'action'inargument.kwargsandargument.kwargs['action'] =='append':
vals= [(argument.longname, str(val)) forvalinvalue]
else:
vals= [(argument.longname, str(value))]
forvalinvals:
bisect.insort(options, val)
else:
iftype(value) islist:
positional_dict[key] = [tuple([v]) forvinvalue]
else:
positional_dict[key] = [(str(value),)]
# Python built-in data structures suck.
# https://stackoverflow.com/questions/27726245/getting-the-key-index-in-a-python-ordereddict/27726534#27726534
positional= []
forkeyinself._arguments.keys():
ifkeyinpositional_dict:
positional.extend(positional_dict[key])
returnoptions+positional
@staticmethod
defget_key(*args, **kwargs):
return_Argument.get_key(*args, **kwargs)
defmain(self, **kwargs):
'''
Do the main function call work.
:type arguments: Dict
'''
raiseNotImplementedError
if__name__=='__main__':
classOneCliFunction(CliFunction):
def__init__(self):
super().__init__(
default_config_file='cli_function_test_config.py',
description='''\
Description of this
amazing function!
''',
)
self.add_argument('-a', '--asdf', default='A', help='Help for asdf'),
self.add_argument('-q', '--qwer', default='Q', help='Help for qwer'),
self.add_argument('-b', '--bool-true', default=True, help='Help for bool-true'),
self.add_argument('--bool-false', default=False, help='Help for bool-false'),
self.add_argument('--dest', dest='custom_dest', help='Help for dest'),
self.add_argument('--bool-cli', default=False, help='Help for bool'),
self.add_argument('--bool-nargs', default=False, nargs='?', action='store', const='')
self.add_argument('--no-default', help='Help for no-bool'),
self.add_argument('--append', action='append')
self.add_argument('pos-mandatory', help='Help for pos-mandatory', type=int),
self.add_argument('pos-optional', default=0, help='Help for pos-optional', type=int),
self.add_argument('args-star', help='Help for args-star', nargs='*'),
defmain(self, **kwargs):
delkwargs['_args_given']
returnkwargs
one_cli_function=OneCliFunction()
# Default code call.
default=one_cli_function(pos_mandatory=1)
assertdefault== {
'asdf': 'A',
'qwer': 'Q',
'bool_true': True,
'bool_false': False,
'bool_nargs': False,
'bool_cli': True,
'custom_dest': None,
'no_default': None,
'append': [],
'pos_mandatory': 1,
'pos_optional': 0,
'args_star': []
}
# Default CLI call with programmatic CLI arguments.
out=one_cli_function.cli_noexit(['1'])
assertout==default
# asdf
out=one_cli_function(pos_mandatory=1, asdf='B')
assertout['asdf'] =='B'
out['asdf'] =default['asdf']
assertout==default
# asdf and qwer
out=one_cli_function(pos_mandatory=1, asdf='B', qwer='R')
assertout['asdf'] =='B'
assertout['qwer'] =='R'
out['asdf'] =default['asdf']
out['qwer'] =default['qwer']
assertout==default
if'--bool-true':
out=one_cli_function(pos_mandatory=1, bool_true=False)
cli_out=one_cli_function.cli_noexit(['--no-bool-true', '1'])
assertout==cli_out
assertout['bool_true'] ==False
out['bool_true'] =default['bool_true']
assertout==default
if'--bool-false':
out=one_cli_function(pos_mandatory=1, bool_false=True)
cli_out=one_cli_function.cli_noexit(['--bool-false', '1'])
assertout==cli_out
assertout['bool_false'] ==True
out['bool_false'] =default['bool_false']
assertout==default
if'--bool-nargs':
out=one_cli_function(pos_mandatory=1, bool_nargs=True)
assertout['bool_nargs'] ==True
out['bool_nargs'] =default['bool_nargs']
assertout==default
out=one_cli_function(pos_mandatory=1, bool_nargs='asdf')
assertout['bool_nargs'] =='asdf'
out['bool_nargs'] =default['bool_nargs']
assertout==default
# --dest
out=one_cli_function(pos_mandatory=1, custom_dest='a')
cli_out=one_cli_function.cli_noexit(['--dest', 'a', '1'])
assertout==cli_out
assertout['custom_dest'] =='a'
out['custom_dest'] =default['custom_dest']
assertout==default
# Positional
out=one_cli_function(pos_mandatory=1, pos_optional=2, args_star=['3', '4'])
# TODO: make actual positional arguments work.
# out = one_cli_function(1, 2, '3', '4')
assertout['pos_mandatory'] ==1
assertout['pos_optional'] ==2
assertout['args_star'] == ['3', '4']
cli_out=one_cli_function.cli_noexit(['1', '2', '3', '4'])
assertout==cli_out
out['pos_mandatory'] =default['pos_mandatory']
out['pos_optional'] =default['pos_optional']
out['args_star'] =default['args_star']
assertout==default
# Star
out=one_cli_function(append=['1', '2'], pos_mandatory=1)
cli_out=one_cli_function.cli_noexit(['--append', '1', '--append', '2', '1'])
assertout==cli_out
assertout['append'] == ['1', '2']
out['append'] =default['append']
assertout==default
# Force a boolean value set on the config to be False on CLI.
assertone_cli_function.cli_noexit(['--no-bool-cli', '1'])['bool_cli'] isFalse
# Pick another config file.
assertone_cli_function.cli_noexit(['--config-file', 'cli_function_test_config_2.py', '1'])['bool_cli'] isFalse
# Extra config file for '*'.
assertone_cli_function.cli_noexit(['--config-file', 'cli_function_test_config_2.py', '1', '2', '3', '4'])['args_star'] == ['3', '4']
assertone_cli_function.cli_noexit(['--config-file', 'cli_function_test_config_2.py', '1', '2'])['args_star'] == ['asdf', 'qwer']
# get_cli
assertone_cli_function.get_cli(pos_mandatory=1, asdf='B') == [('--asdf', 'B'), ('--bool-cli',), ('1',)]
assertone_cli_function.get_cli(pos_mandatory=1, asdf='B', qwer='R') == [('--asdf', 'B'), ('--bool-cli',), ('--qwer', 'R'), ('1',)]
assertone_cli_function.get_cli(pos_mandatory=1, bool_true=False) == [('--bool-cli',), ('--no-bool-true',), ('1',)]
assertone_cli_function.get_cli(pos_mandatory=1, bool_false=True) == [('--bool-cli',), ('--bool-false',), ('1',)]
assertone_cli_function.get_cli(pos_mandatory=1, pos_optional=2, args_star=['asdf', 'qwer']) == [('--bool-cli',), ('1',), ('2',), ('asdf',), ('qwer',)]
assertone_cli_function.get_cli(pos_mandatory=1, append=['2', '3']) == [('--append', '2'), ('--append', '3',), ('--bool-cli',), ('1',)]
classNargsWithDefault(CliFunction):
def__init__(self):
super().__init__()
self.add_argument('args-star', default=['1', '2'], nargs='*'),
defmain(self, **kwargs):
returnkwargs
nargs_with_default=NargsWithDefault()
default=nargs_with_default()
assertdefault['args_star'] == ['1', '2']
default_cli=nargs_with_default.cli_noexit([])
assertdefault_cli['args_star'] == ['1', '2']
assertnargs_with_default.cli_noexit(['1', '2', '3', '4'])['args_star'] == ['1', '2', '3', '4']
iflen(sys.argv) >1:
# CLI call with argv command line arguments.
print(one_cli_function.cli())