forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeneraloption.py
1769 lines (1470 loc) · 78 KB
/
generaloption.py
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright 2011-2023 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
#
"""
A class that can be used to generated options to python scripts in a general way.
Authors:
* Stijn De Weirdt (Ghent University)
* Jens Timmerman (Ghent University)
"""
import configparser
import copy
import difflib
import inspect
import operator
import os
import re
import sys
import textwrap
from configparser import ConfigParser
from functools import reduce
from io import StringIO
from optparse import Option, OptionGroup, OptionParser, OptionValueError, Values
from optparse import SUPPRESS_HELP as nohelp # supported in optparse of python v2.4
from easybuild.base.fancylogger import getLogger, setroot, setLogLevel, getDetailsLogLevels
from easybuild.base.optcomplete import autocomplete, CompleterOption
from easybuild.tools.run import subprocess_popen_text
from easybuild.tools.utilities import mk_md_table, mk_rst_table, nub, shell_quote
try:
import gettext
eb_translation = None
def get_translation():
global eb_translation
if not eb_translation:
# Finding a translation is expensive, so do only once
domain = gettext.textdomain()
eb_translation = gettext.translation(domain, gettext.bindtextdomain(domain), fallback=True)
return eb_translation
def _gettext(message):
return get_translation().gettext(message)
except ImportError:
def _gettext(message):
return message
HELP_OUTPUT_FORMATS = ['', 'md', 'rst', 'short', 'config']
def set_columns(cols=None):
"""Set os.environ COLUMNS variable
- only if it is not set already
"""
if 'COLUMNS' in os.environ:
# do nothing
return
if cols is None:
stty = '/usr/bin/stty'
if os.path.exists(stty):
try:
with open(os.devnull, 'w') as devnull:
proc = subprocess_popen_text([stty, "size"], stderr=devnull)
cols = int(proc.communicate()[0].strip().split(' ')[1])
except (AttributeError, IndexError, OSError, ValueError):
# do nothing
pass
if cols is not None:
os.environ['COLUMNS'] = "%s" % cols
def what_str_list_tuple(name):
"""Given name, return separator, class and helptext wrt separator.
(Currently supports strlist, strtuple, pathlist, pathtuple)
"""
sep = ','
helpsep = 'comma'
if name.startswith('path'):
sep = os.pathsep
helpsep = 'pathsep'
klass = None
if name.endswith('list'):
klass = list
elif name.endswith('tuple'):
klass = tuple
return sep, klass, helpsep
def check_str_list_tuple(option, opt, value): # pylint: disable=unused-argument
"""
check function for strlist and strtuple type
assumes value is comma-separated list
returns list or tuple of strings
"""
sep, klass, _ = what_str_list_tuple(option.type)
split = value.split(sep)
if klass is None:
err = _gettext("check_strlist_strtuple: unsupported type %s" % option.type)
raise OptionValueError(err)
else:
return klass(split)
def get_empty_add_flex(allvalues, self=None):
"""Return the empty element for add_flex action for allvalues"""
empty = None
if isinstance(allvalues, (list, tuple)):
if isinstance(allvalues[0], str):
empty = ''
if empty is None:
msg = "get_empty_add_flex cannot determine empty element for type %s (%s)"
msg = msg % (type(allvalues), allvalues)
exc_class = TypeError
if self is None:
raise exc_class(msg)
else:
self.log.raiseException(msg, exc_class)
return empty
class ExtOption(CompleterOption):
"""Extended options class
- enable/disable support
Actions:
- shorthelp : hook for shortend help messages
- confighelp : hook for configfile-style help messages
- store_debuglog : turns on fancylogger debugloglevel
- also: 'store_infolog', 'store_warninglog'
- add : add value to default (result is default + value)
- add_first : add default to value (result is value + default)
- extend : alias for add with strlist type
- type must support + (__add__) and one of negate (__neg__) or slicing (__getslice__)
- add_flex : similar to add / add_first, but replaces the first "empty" element with the default
- the empty element is dependent of the type
- for {str,path}{list,tuple} this is the empty string
- types must support the index method to determine the location of the "empty" element
- the replacement uses +
- e.g. a strlist type with value "0,,1"` and default [3,4] and action add_flex will
use the empty string '' as "empty" element, and will result in [0,3,4,1] (not [0,[3,4],1])
(but also a strlist with value "" and default [3,4] will result in [3,4];
so you can't set an empty list with add_flex)
- date : convert into datetime.date
- datetime : convert into datetime.datetime
- regex: compile str in regexp
- store_or_None
- set default to None if no option passed,
- set to default if option without value passed,
- set to value if option with value passed
Types:
- strlist, strtuple : convert comma-separated string in a list resp. tuple of strings
- pathlist, pathtuple : using os.pathsep, convert pathsep-separated string in a list resp. tuple of strings
- the path separator is OS-dependent
"""
EXTEND_SEPARATOR = ','
ENABLE = 'enable' # do nothing
DISABLE = 'disable' # inverse action
EXTOPTION_EXTRA_OPTIONS = ('date', 'datetime', 'regex', 'add', 'add_first', 'add_flex',)
EXTOPTION_STORE_OR = ('store_or_None', 'help') # callback type
EXTOPTION_LOG = ('store_debuglog', 'store_infolog', 'store_warninglog',)
EXTOPTION_HELP = ('shorthelp', 'confighelp', 'help')
ACTIONS = Option.ACTIONS + EXTOPTION_EXTRA_OPTIONS + EXTOPTION_STORE_OR + EXTOPTION_LOG + EXTOPTION_HELP
STORE_ACTIONS = Option.STORE_ACTIONS + EXTOPTION_EXTRA_OPTIONS + EXTOPTION_LOG + ('store_or_None',)
TYPED_ACTIONS = Option.TYPED_ACTIONS + EXTOPTION_EXTRA_OPTIONS + EXTOPTION_STORE_OR
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + EXTOPTION_EXTRA_OPTIONS
TYPE_STRLIST = ['%s%s' % (name, klass) for klass in ['list', 'tuple'] for name in ['str', 'path']]
TYPE_CHECKER = dict([(x, check_str_list_tuple) for x in TYPE_STRLIST] + list(Option.TYPE_CHECKER.items()))
TYPES = tuple(TYPE_STRLIST + list(Option.TYPES))
BOOLEAN_ACTIONS = ('store_true', 'store_false',) + EXTOPTION_LOG
def __init__(self, *args, **kwargs):
"""Add logger to init"""
CompleterOption.__init__(self, *args, **kwargs)
self.log = getLogger(self.__class__.__name__)
def _set_attrs(self, attrs):
"""overwrite _set_attrs to allow store_or callbacks"""
Option._set_attrs(self, attrs)
if self.action == 'extend':
# alias
self.action = 'add'
self.type = 'strlist'
elif self.action in self.EXTOPTION_STORE_OR:
setattr(self, 'store_or', self.action)
def store_or(option, opt_str, value, parser, *args, **kwargs): # pylint: disable=unused-argument
"""Callback for supporting options with optional values."""
# see http://stackoverflow.com/questions/1229146/parsing-empty-options-in-python
# ugly code, optparse is crap
if parser.rargs and not parser.rargs[0].startswith('-'):
val = option.check_value(opt_str, parser.rargs.pop(0))
else:
val = kwargs.get('orig_default', None)
setattr(parser.values, option.dest, val)
# without the following, --x=y doesn't work; only --x y
self.nargs = 0 # allow 0 args, will also use 0 args
if self.type is None:
# set to not None, for takes_value to return True
self.type = 'string'
self.callback = store_or
self.callback_kwargs = {
'orig_default': copy.deepcopy(self.default),
}
self.action = 'callback' # act as callback
if self.store_or in self.EXTOPTION_STORE_OR:
self.default = None
else:
self.log.raiseException("_set_attrs: unknown store_or %s" % self.store_or, exception=ValueError)
def process(self, opt, value, values, parser):
"""Handle option-as-value issues before actually processing option."""
if hasattr(parser, 'is_value_a_commandline_option'):
errmsg = parser.is_value_a_commandline_option(opt, value)
if errmsg is not None:
prefix = "%s=" % self._long_opts[0] if self._long_opts else self._short_opts[0]
self.log.raiseException("%s. Use '%s%s' if the value is correct." % (errmsg, prefix, value),
exception=OptionValueError)
return Option.process(self, opt, value, values, parser)
def take_action(self, action, dest, opt, value, values, parser):
"""Extended take_action"""
orig_action = action # keep copy
# dest is None for actions like shorthelp and confighelp
if dest and getattr(parser._long_opt.get('--' + dest, ''), 'store_or', '') == 'help':
Option.take_action(self, action, dest, opt, value, values, parser)
fn = getattr(parser, 'print_%shelp' % values.help, None)
if fn is None:
self.log.raiseException("Unsupported output format for help: %s" % value.help, exception=ValueError)
else:
fn()
parser.exit()
elif action == 'shorthelp':
parser.print_shorthelp()
parser.exit()
elif action == 'confighelp':
parser.print_confighelp()
parser.exit()
elif action in ('store_true', 'store_false',) + self.EXTOPTION_LOG:
if action in self.EXTOPTION_LOG:
action = 'store_true'
if opt.startswith("--%s-" % self.ENABLE):
# keep action
pass
elif opt.startswith("--%s-" % self.DISABLE):
# reverse action
if action in ('store_true',) + self.EXTOPTION_LOG:
action = 'store_false'
elif action in ('store_false',):
action = 'store_true'
if orig_action in self.EXTOPTION_LOG and action == 'store_true':
newloglevel = orig_action.split('_')[1][:-3].upper()
logstate = ", ".join(["(%s, %s)" % (n, l) for n, l in getDetailsLogLevels()])
self.log.debug("changing loglevel to %s, current state: %s", newloglevel, logstate)
setLogLevel(newloglevel)
self.log.debug("changed loglevel to %s, previous state: %s", newloglevel, logstate)
if hasattr(values, '_logaction_taken'):
values._logaction_taken[dest] = True
Option.take_action(self, action, dest, opt, value, values, parser)
elif action in self.EXTOPTION_EXTRA_OPTIONS:
if action in ("add", "add_first", "add_flex",):
# determine type from lvalue
# set default first
default = getattr(parser.get_default_values(), dest, None)
if default is None:
default = type(value)()
# 'add*' actions require that the default value is of type list or tuple,
# which supports composing via '+' and slicing
if not isinstance(default, (list, tuple)):
msg = "Unsupported type %s for action %s (requires list)"
self.log.raiseException(msg % (type(default), action))
if action in ('add', 'add_flex'):
lvalue = default + value
elif action == 'add_first':
lvalue = value + default
if action == 'add_flex' and lvalue:
# use lvalue here rather than default to make sure there is 1 element
# to determine the type
if not hasattr(lvalue, 'index'):
msg = "Unsupported type %s for action %s (requires index method)"
self.log.raiseException(msg % (type(lvalue), action))
empty = get_empty_add_flex(lvalue, self=self)
if empty in value:
ind = value.index(empty)
lvalue = value[:ind] + default + value[ind + 1:]
else:
lvalue = value
elif action == "regex":
lvalue = re.compile(r'' + value)
else:
msg = "Unknown extended option action %s (known: %s)"
self.log.raiseException(msg % (action, self.EXTOPTION_EXTRA_OPTIONS))
setattr(values, dest, lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
# set flag to mark as passed by action (ie not by default)
# - distinguish from setting default value through option
if hasattr(values, '_action_taken'):
values._action_taken[dest] = True
class ExtOptionGroup(OptionGroup):
"""An OptionGroup with support for configfile section names"""
RESERVED_SECTIONS = [configparser.DEFAULTSECT]
NO_SECTION = ('NO', 'SECTION')
def __init__(self, *args, **kwargs):
self.log = getLogger(self.__class__.__name__)
section_name = kwargs.pop('section_name', None)
if section_name in self.RESERVED_SECTIONS:
self.log.raiseException('Cannot use reserved name %s for section name.' % section_name)
OptionGroup.__init__(self, *args, **kwargs)
self.section_name = section_name
self.section_options = []
def add_option(self, *args, **kwargs):
"""Extract configfile section info"""
option = OptionGroup.add_option(self, *args, **kwargs)
self.section_options.append(option)
return option
class ExtOptionParser(OptionParser):
"""
Make an option parser that limits the C{-h} / C{--shorthelp} to short opts only,
C{-H} / C{--help} for all options.
Pass options through environment. Like:
- C{export PROGNAME_SOMEOPTION = value} will generate {--someoption=value}
- C{export PROGNAME_OTHEROPTION = 1} will generate {--otheroption}
- C{export PROGNAME_OTHEROPTION = 0} (or no or false) won't do anything
distinction is made based on option.action in TYPED_ACTIONS allow
C{--enable-} / C{--disable-} (using eg ExtOption option_class)
"""
shorthelp = ('h', "--shorthelp",)
longhelp = ('H', "--help",)
VALUES_CLASS = Values
DESCRIPTION_DOCSTRING = False
ALLOW_OPTION_NAME_AS_VALUE = False # exact match for option name (without the '-') as value
ALLOW_OPTION_AS_VALUE = False # exact match for option as value
ALLOW_DASH_AS_VALUE = False # any value starting with a '-'
ALLOW_TYPO_AS_VALUE = True # value with similarity score from difflib.get_close_matches
def __init__(self, *args, **kwargs):
"""
Following named arguments are specific to ExtOptionParser
(the remaining ones are passed to the parent OptionParser class)
:param help_to_string: boolean, if True, the help is written
to a newly created StingIO instance
:param help_to_file: filehandle, help is written to this filehandle
:param envvar_prefix: string, specify the environment variable prefix
to use (if you don't want the default one)
:param process_env_options: boolean, if False, don't check the
environment for options (default: True)
:param error_env_options: boolean, if True, use error_env_options_method
if an environment variable with correct envvar_prefix
exists but does not correspond to an existing option
(default: False)
:param error_env_options_method: callable; method to use to report error
in used environment variables (see error_env_options);
accepts string value + additional
string arguments for formatting the message
(default: own log.error method)
"""
self.log = getLogger(self.__class__.__name__)
self.help_to_string = kwargs.pop('help_to_string', None)
self.help_to_file = kwargs.pop('help_to_file', None)
self.envvar_prefix = kwargs.pop('envvar_prefix', None)
self.process_env_options = kwargs.pop('process_env_options', True)
self.error_env_options = kwargs.pop('error_env_options', False)
self.error_env_option_method = kwargs.pop('error_env_option_method', self.log.error)
# py2.4 epilog compatibilty with py2.7 / optparse 1.5.3
self.epilog = kwargs.pop('epilog', None)
if 'option_class' not in kwargs:
kwargs['option_class'] = ExtOption
OptionParser.__init__(self, *args, **kwargs)
# redefine formatter for py2.4 compat
if not hasattr(self.formatter, 'format_epilog'):
setattr(self.formatter, 'format_epilog', self.formatter.format_description)
if self.epilog is None:
self.epilog = []
if hasattr(self.option_class, 'ENABLE') and hasattr(self.option_class, 'DISABLE'):
epilogtxt = 'Boolean options support %(disable)s prefix to do the inverse of the action,'
epilogtxt += ' e.g. option --someopt also supports --disable-someopt.'
self.epilog.append(epilogtxt % {'disable': self.option_class.DISABLE})
self.environment_arguments = None
self.commandline_arguments = None
def is_value_a_commandline_option(self, opt, value, index=None):
"""
Determine if value is/could be an option passed via the commandline.
If it is, return the reason why (can be used as message); or return None if it isn't.
opt is the option flag to which the value is passed;
index is the index of the value on the commandline (if None, it is determined from orig_rargs and rargs)
The method tests for possible ambiguity on the commandline when the parser
interprets the argument following an option as a value, whereas it is far more likely that
it is (intended as) an option; --longopt=value is never considered ambiguous, regardless of the value.
"""
# Values that are/could be options that are passed via
# only --longopt=value is not a problem.
# When processing the enviroment and/or configfile, we always set
# --longopt=value, so no issues there either.
# following checks assume that value is a string (not a store_or_None)
if not isinstance(value, str):
return None
cmdline_index = None
try:
cmdline_index = self.commandline_arguments.index(value)
except ValueError:
# no index found for value, so not a stand-alone value
if opt.startswith('--'):
# only --longopt=value is unambigouos
return None
if index is None:
# index of last parsed arg in commandline_arguments via remainder of rargs
index = len(self.commandline_arguments) - len(self.rargs) - 1
if cmdline_index is not None and index != cmdline_index:
# This is not the value you are looking for
return None
if not self.ALLOW_OPTION_NAME_AS_VALUE:
value_as_opt = '-%s' % value
if value_as_opt in self._short_opt or value_as_opt in self._long_opt:
return "'-%s' is a valid option" % value
if (not self.ALLOW_OPTION_AS_VALUE) and (value in self._long_opt or value in self._short_opt):
return "Value '%s' is also a valid option" % value
if not self.ALLOW_DASH_AS_VALUE and value.startswith('-'):
return "Value '%s' starts with a '-'" % value
if not self.ALLOW_TYPO_AS_VALUE:
possibilities = self._long_opt.keys() + self._short_opt.keys()
# also on optionnames, i.e. without the -- / -
possibilities.extend([x.lstrip('-') for x in possibilities])
# max 3 options; minimum score is taken from EB experience
matches = difflib.get_close_matches(value, possibilities, 3, 0.85)
if matches:
return "Value '%s' too close match to option(s) %s" % (value, ', '.join(matches))
return None
def set_description_docstring(self):
"""Try to find the main docstring and add it if description is not None"""
stack = inspect.stack()[-1]
try:
docstr = stack[0].f_globals.get('__doc__', None)
except (IndexError, ValueError, AttributeError):
self.log.debug("set_description_docstring: no docstring found in latest stack globals")
docstr = None
if docstr is not None:
indent = " "
# kwargs and ** magic to deal with width
kwargs = {
'initial_indent': indent * 2,
'subsequent_indent': indent * 2,
'replace_whitespace': False,
}
width = os.environ.get('COLUMNS', None)
if width is not None:
# default textwrap width
try:
kwargs['width'] = int(width)
except ValueError:
pass
# deal with newlines in docstring
final_docstr = ['']
for line in str(docstr).strip("\n ").split("\n"):
final_docstr.append(textwrap.fill(line, **kwargs))
final_docstr.append('')
return "\n".join(final_docstr)
def format_description(self, formatter):
"""Extend to allow docstring as description"""
description = ''
if self.description == 'NONE_AND_NOT_NONE':
if self.DESCRIPTION_DOCSTRING:
description = self.set_description_docstring()
elif self.description:
description = formatter.format_description(self.get_description())
return str(description)
def set_usage(self, usage):
"""Return usage and set try to set autogenerated description."""
usage = OptionParser.set_usage(self, usage)
if self.description is None:
self.description = 'NONE_AND_NOT_NONE'
return usage
def get_default_values(self):
"""Introduce the ExtValues class with class constant
- make it dynamic, otherwise the class constant is shared between multiple instances
- class constant is used to avoid _action_taken as option in the __dict__
- only works by using reference to object
- same for _logaction_taken
"""
values = OptionParser.get_default_values(self)
class ExtValues(self.VALUES_CLASS):
_action_taken = {}
_logaction_taken = {}
newvalues = ExtValues()
newvalues.__dict__ = values.__dict__.copy()
return newvalues
def format_help(self, formatter=None):
"""For py2.4 compatibility reasons (missing epilog). This is the py2.7 / optparse 1.5.3 code"""
if formatter is None:
formatter = self.formatter
result = []
if self.usage:
result.append(self.get_usage() + "\n")
if self.description:
result.append(self.format_description(formatter) + "\n")
result.append(self.format_option_help(formatter))
result.append(self.format_epilog(formatter))
return "".join(result)
def format_epilog(self, formatter):
"""Allow multiple epilog parts"""
res = []
if not isinstance(self.epilog, (list, tuple,)):
self.epilog = [self.epilog]
for epi in self.epilog:
res.append(formatter.format_epilog(epi))
return "".join(res)
def print_shorthelp(self, fh=None):
"""Print a shortened help (no longopts)"""
for opt in self._get_all_options():
if opt._short_opts is None or len([x for x in opt._short_opts if len(x) > 0]) == 0:
opt.help = nohelp
opt._long_opts = [] # remove all long_opts
removeoptgrp = []
for optgrp in self.option_groups:
# remove all option groups that have only nohelp options
if reduce(operator.and_, [opt.help == nohelp for opt in optgrp.option_list]):
removeoptgrp.append(optgrp)
for optgrp in removeoptgrp:
self.option_groups.remove(optgrp)
self.print_help(fh)
def check_help(self, fh):
"""Checks filehandle for help functions"""
if self.help_to_string:
self.help_to_file = StringIO()
if fh is None:
fh = self.help_to_file
if hasattr(self.option_class, 'ENABLE') and hasattr(self.option_class, 'DISABLE'):
def _is_enable_disable(x):
"""Does the option start with ENABLE/DISABLE"""
_e = x.startswith("--%s-" % self.option_class.ENABLE)
_d = x.startswith("--%s-" % self.option_class.DISABLE)
return _e or _d
for opt in self._get_all_options():
# remove all long_opts with ENABLE/DISABLE naming
opt._long_opts = [x for x in opt._long_opts if not _is_enable_disable(x)]
return fh
# pylint: disable=arguments-differ
def print_help(self, fh=None):
"""Intercept print to file to print to string and remove the ENABLE/DISABLE options from help"""
fh = self.check_help(fh)
OptionParser.print_help(self, fh)
def print_mdhelp(self, fh=None):
"""Print help in MarkDown format"""
fh = self.check_help(fh)
result = []
if self.usage:
result.extend(["## Usage", '', '``%s``' % self.get_usage().replace("Usage: ", '').strip(), ''])
if self.description:
result.extend(["## Description", '', self.description, ''])
result.append(self.format_option_mdhelp())
mdhelptxt = '\n'.join(result)
if fh is None:
fh = sys.stdout
fh.write(mdhelptxt)
def format_option_mdhelp(self, formatter=None):
""" Formatting for help in rst format """
if not formatter:
formatter = self.formatter
formatter.store_option_strings(self)
res = []
titles = ["Option flag", "Option description"]
all_opts = [("Help options", self.option_list)] + \
[(group.title, group.option_list) for group in self.option_groups]
for title, opts in all_opts:
values = []
res.extend(['## ' + title, ''])
for opt in opts:
if opt.help is not nohelp:
values.append(['``%s``' % formatter.option_strings[opt], formatter.expand_default(opt)])
res.extend(mk_md_table(titles, map(list, zip(*values))))
res.append('')
return '\n'.join(res)
def print_rsthelp(self, fh=None):
""" Print help in rst format """
fh = self.check_help(fh)
result = []
if self.usage:
title = "Usage"
result.extend([title, '-' * len(title), '', '``%s``' % self.get_usage().replace("Usage: ", '').strip(), ''])
if self.description:
title = "Description"
result.extend([title, '-' * len(title), '', self.description, ''])
result.append(self.format_option_rsthelp())
rsthelptxt = '\n'.join(result)
if fh is None:
fh = sys.stdout
fh.write(rsthelptxt)
def format_option_rsthelp(self, formatter=None):
""" Formatting for help in rst format """
if not formatter:
formatter = self.formatter
formatter.store_option_strings(self)
res = []
titles = ["Option flag", "Option description"]
all_opts = [("Help options", self.option_list)] + \
[(group.title, group.option_list) for group in self.option_groups]
for title, opts in all_opts:
values = []
res.extend([title, '-' * len(title)])
for opt in opts:
if opt.help is not nohelp:
values.append(['``%s``' % formatter.option_strings[opt], formatter.expand_default(opt)])
res.extend(mk_rst_table(titles, map(list, zip(*values))))
res.append('')
return '\n'.join(res)
def print_confighelp(self, fh=None):
"""Print help as a configfile."""
# walk through all optiongroups
# append where necessary, keep track of sections
all_groups = {}
sections = []
for gr in self.option_groups:
section = gr.section_name
if not (section is None or section == ExtOptionGroup.NO_SECTION):
if section not in sections:
sections.append(section)
ag = all_groups.setdefault(section, [])
ag.extend(gr.section_options)
# set MAIN section first if exists
main_idx = sections.index('MAIN')
if main_idx > 0: # not needed if it main_idx == 0
sections.remove('MAIN')
sections.insert(0, 'MAIN')
option_template = "# %(help)s\n#%(option)s=\n"
txt = ''
for section in sections:
txt += "[%s]\n" % section
for option in all_groups[section]:
data = {
'help': option.help,
'option': option.get_opt_string().lstrip('-'),
}
txt += option_template % data
txt += "\n"
# overwrite the format_help to be able to use the the regular print_help
def format_help(*args, **kwargs): # pylint: disable=unused-argument
return txt
self.format_help = format_help
self.print_help(fh)
def _add_help_option(self):
"""Add shorthelp and longhelp"""
self.add_option("-%s" % self.shorthelp[0],
self.shorthelp[1], # *self.shorthelp[1:], syntax error in Python 2.4
action="shorthelp",
help=_gettext("show short help message and exit"))
self.add_option("-%s" % self.longhelp[0],
self.longhelp[1], # *self.longhelp[1:], syntax error in Python 2.4
action="help",
type="choice",
choices=HELP_OUTPUT_FORMATS,
default=HELP_OUTPUT_FORMATS[0],
metavar='OUTPUT_FORMAT',
help=_gettext("show full help message and exit"))
self.add_option("--confighelp",
action="confighelp",
help=_gettext("show help as annotated configfile"))
def _get_args(self, args):
"""Prepend the options set through the environment"""
self.commandline_arguments = OptionParser._get_args(self, args)
self.get_env_options()
return self.environment_arguments + self.commandline_arguments # prepend the environment options as longopts
def get_env_options_prefix(self):
"""Return the prefix to use for options passed through the environment"""
# sys.argv[0] or the prog= argument of the optionparser, strip possible extension
if self.envvar_prefix is None:
self.envvar_prefix = self.get_prog_name().rsplit('.', 1)[0].upper()
return self.envvar_prefix
def get_env_options(self):
"""Retrieve options from the environment: prefix_longopt.upper()"""
self.environment_arguments = []
if not self.process_env_options:
self.log.debug("Not processing environment for options")
return
if self.envvar_prefix is None:
self.get_env_options_prefix()
epilogprefixtxt = "All long option names can be passed as environment variables. "
epilogprefixtxt += "Variable name is %(prefix)s_<LONGNAME> "
epilogprefixtxt += "eg. --some-opt is same as setting %(prefix)s_SOME_OPT in the environment."
self.epilog.append(epilogprefixtxt % {'prefix': self.envvar_prefix})
candidates = dict([(k, v) for k, v in os.environ.items() if k.startswith("%s_" % self.envvar_prefix)])
for opt in self._get_all_options():
if opt._long_opts is None:
continue
for lo in opt._long_opts:
if len(lo) == 0:
continue
env_opt_name = "%s_%s" % (self.envvar_prefix, lo.lstrip('-').replace('-', '_').upper())
val = candidates.pop(env_opt_name, None)
if val is not None:
if opt.action in opt.TYPED_ACTIONS: # not all typed actions are mandatory, but let's assume so
self.environment_arguments.append("%s=%s" % (lo, val))
else:
# interpretation of values: 0/no/false means: don't set it
if ("%s" % val).lower() not in ("0", "no", "false",):
self.environment_arguments.append("%s" % lo)
else:
self.log.debug("Environment variable %s is not set" % env_opt_name)
if candidates:
msg = "Found %s environment variable(s) that are prefixed with %s but do not match valid option(s): %s"
if self.error_env_options:
logmethod = self.error_env_option_method
else:
logmethod = self.log.debug
logmethod(msg, len(candidates), self.envvar_prefix, ','.join(sorted(candidates)))
self.log.debug("Environment variable options with prefix %s: %s",
self.envvar_prefix, self.environment_arguments)
return self.environment_arguments
def get_option_by_long_name(self, name):
"""Return the option matching the long option name"""
for opt in self._get_all_options():
if opt._long_opts is None:
continue
for lo in opt._long_opts:
if len(lo) == 0:
continue
dest = lo.lstrip('-')
if name == dest:
return opt
return None
class GeneralOption(object):
"""
'Used-to-be simple' wrapper class for option parsing
Options with go_ prefix are for this class, the remainder is passed to the parser
- go_args : use these instead of of sys.argv[1:]
- go_columns : specify column width (in columns)
- go_useconfigfiles : use configfiles or not (default set by CONFIGFILES_USE)
if True, an option --configfiles will be added
- go_configfiles : list of configfiles to parse. Uses ConfigParser.read; last file wins
- go_configfiles_initenv : section dict of key/value dict; inserted before configfileparsing
As a special case, using all uppercase key in DEFAULT section with a case-sensitive
configparser can be used to set "constants" for easy interpolation in all sections.
- go_loggername : name of logger, default classname
- go_mainbeforedefault : set the main options before the default ones
- go_autocompleter : dict with named options to pass to the autocomplete call (eg arg_completer)
if is None: disable autocompletion; default is {} (ie no extra args passed)
Sections starting with the string 'raw_' in the sectionname will be parsed as raw sections,
meaning there will be no interpolation of the strings. This comes in handy if you want to configure strings
with templates in them.
Options process order (last one wins)
0. default defined with option
1. value in (last) configfile (last configfile wins)
2. options parsed by option parser
In case the ExtOptionParser is used
0. value set through environment variable
1. value set through commandline option
"""
OPTIONNAME_PREFIX_SEPARATOR = '-'
DEBUG_OPTIONS_BUILD = False # enable debug mode when building the options ?
USAGE = None
ALLOPTSMANDATORY = True
PARSER = ExtOptionParser
INTERSPERSED = True # mix args with options
CONFIGFILES_USE = True
CONFIGFILES_RAISE_MISSING = False
CONFIGFILES_INIT = [] # initial list of defaults, overwritten by go_configfiles options
CONFIGFILES_IGNORE = []
CONFIGFILES_MAIN_SECTION = 'MAIN' # sectionname that contains the non-grouped/non-prefixed options
CONFIGFILE_CASESENSITIVE = True
METAVAR_DEFAULT = True # generate a default metavar
METAVAR_MAP = None # metvar, list of longopts map
OPTIONGROUP_SORTED_OPTIONS = True
PROCESSED_OPTIONS_PROPERTIES = ['type', 'default', 'action', 'opt_name', 'prefix', 'section_name']
VERSION = None # set the version (will add --version)
DEFAULTSECT = configparser.DEFAULTSECT
DEFAULT_LOGLEVEL = None
DEFAULT_CONFIGFILES = None
DEFAULT_IGNORECONFIGFILES = None
SETROOTLOGGER = False
def __init__(self, **kwargs):
go_args = kwargs.pop('go_args', None)
self.no_system_exit = kwargs.pop('go_nosystemexit', None) # unit test option
self.use_configfiles = kwargs.pop('go_useconfigfiles', self.CONFIGFILES_USE) # use or ignore config files
self.configfiles = kwargs.pop('go_configfiles', self.CONFIGFILES_INIT[:]) # configfiles to parse
configfiles_initenv = kwargs.pop('go_configfiles_initenv', None) # initial environment for configfiles to parse
prefixloggername = kwargs.pop('go_prefixloggername', False) # name of logger is same as envvar prefix
mainbeforedefault = kwargs.pop('go_mainbeforedefault', False) # Set the main options before the default ones
autocompleter = kwargs.pop('go_autocompleter', {}) # Pass these options to the autocomplete call
if self.SETROOTLOGGER:
setroot()
set_columns(kwargs.pop('go_columns', None))
kwargs.update({
'option_class': ExtOption,
'usage': kwargs.get('usage', self.USAGE),
'version': self.VERSION,
})
self.parser = self.PARSER(**kwargs)
self.parser.allow_interspersed_args = self.INTERSPERSED
self.configfile_parser = None
self.configfile_remainder = {}
loggername = self.__class__.__name__
if prefixloggername:
prefix = self.parser.get_env_options_prefix()
if prefix is not None and len(prefix) > 0:
loggername = prefix.replace('.', '_') # . indicate hierarchy in logging land
self.log = getLogger(name=loggername)
self.options = None
self.args = None
self.autocompleter = autocompleter
self.auto_prefix = None
self.auto_section_name = None
self.processed_options = {}
self.config_prefix_sectionnames_map = {}
self.set_go_debug()
if mainbeforedefault:
self.main_options()
self._default_options()
else:
self._default_options()
self.main_options()
self.parseoptions(options_list=go_args)
if self.options is not None:
# None for eg usage/help
self.configfile_parser_init(initenv=configfiles_initenv)
self.parseconfigfiles()
self._set_default_loglevel()
self.postprocess()
self.validate()
def set_go_debug(self):
"""Check if debug options are on and then set fancylogger to debug.
This is not the default way to set debug, it enables debug logging
in an earlier stage to debug generaloption itself.
"""
if self.options is None:
if self.DEBUG_OPTIONS_BUILD:
setLogLevel('DEBUG')
def _default_options(self):
"""Generate default options: debug/log and configfile"""