/usr/lib/python2.7/dist-packages/fuseparts/subbedopts.py is in python-fuse 2:0.2.1-10.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #
# Copyright (C) 2006 Csaba Henk <csaba.henk@creo.hu>
#
# This program can be distributed under the terms of the GNU LGPL.
# See the file COPYING.
#
from optparse import Option, OptionParser, OptParseError, OptionConflictError
from optparse import HelpFormatter, IndentedHelpFormatter, SUPPRESS_HELP
from fuseparts.setcompatwrap import set
##########
###
### Generic suboption parsing stuff.
###
##########
class SubOptsHive(object):
"""
Class for collecting unhandled suboptions.
"""
def __init__(self):
self.optlist = set()
self.optdict = {}
def _str_core(self):
sa = []
for k, v in self.optdict.iteritems():
sa.append(str(k) + '=' + str(v))
ra = (list(self.optlist) + sa) or ["(none)"]
ra.sort()
return ra
def __str__(self):
return "< opts: " + ", ".join(self._str_core()) + " >"
def canonify(self):
"""
Transform self to an equivalent canonical form:
delete optdict keys with False value, move optdict keys
with True value to optlist, stringify other values.
"""
for k, v in self.optdict.iteritems():
if v == False:
self.optdict.pop(k)
elif v == True:
self.optdict.pop(k)
self.optlist.add(v)
else:
self.optdict[k] = str(v)
def filter(self, other):
"""
Throw away those options which are not in the other one.
Returns a new instance with the rejected options.
"""
self.canonify()
other.canonify()
rej = self.__class__()
rej.optlist = self.optlist.difference(other.optlist)
self.optlist.difference_update(rej.optlist)
for x in self.optdict.copy():
if x not in other.optdict:
self.optdict.pop(x)
rej.optdict[x] = None
return rej
def add(self, opt, val=None):
"""Add a suboption."""
ov = opt.split('=', 1)
o = ov[0]
v = len(ov) > 1 and ov[1] or None
if (v):
if val != None:
raise AttributeError, "ambiguous option value"
val = v
if val == False:
return
if val in (None, True):
self.optlist.add(o)
else:
self.optdict[o] = val
class SubbedOpt(Option):
"""
`Option` derivative enhanced with the attribute of being a suboption of
some other option (like ``foo`` and ``bar`` for ``-o`` in ``-o foo,bar``).
"""
ATTRS = Option.ATTRS + ["subopt", "subsep", "subopts_hive"]
ACTIONS = Option.ACTIONS + ("store_hive",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("store_hive",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("store_hive",)
def __init__(self, *opts, **attrs):
self.subopt_map = {}
if "subopt" in attrs:
self._short_opts = []
self._long_opts = []
self._set_opt_strings(opts)
self.baseopt = self._short_opts[0] or self._long_opts[0]
opts = ()
Option.__init__(self, *opts, **attrs)
def __str__(self):
pf = ""
if hasattr(self, "subopt") and self.subopt:
pf = " %s...,%s,..." % (self.baseopt, self.subopt)
return Option.__str__(self) + pf
def _check_opt_strings(self, opts):
return opts
def _check_dest(self):
try:
Option._check_dest(self)
except IndexError:
if self.subopt:
self.dest = "__%s__%s" % (self.baseopt, self.subopt)
self.dest = self.dest.replace("-", "")
else:
raise
def get_opt_string(self):
if hasattr(self, 'subopt'):
return self.subopt
else:
return Option.get_opt_string(self)
def take_action(self, action, dest, opt, value, values, parser):
if action == "store_hive":
if not hasattr(values, dest) or getattr(values, dest) == None:
if hasattr(self, "subopts_hive") and self.subopts_hive:
hive = self.subopts_hive
else:
hive = parser.hive_class()
setattr(values, dest, hive)
for o in value.split(self.subsep or ","):
oo = o.split('=')
ok = oo[0]
ov = None
if (len(oo) > 1):
ov = oo[1]
if ok in self.subopt_map:
self.subopt_map[ok].process(ok, ov, values, parser)
else:
getattr(values, dest).add(*oo)
return
Option.take_action(self, action, dest, opt, value, values, parser)
def register_sub(self, o):
"""Register argument a suboption for `self`."""
if o.subopt in self.subopt_map:
raise OptionConflictError(
"conflicting suboption handlers for `%s'" % o.subopt,
o)
self.subopt_map[o.subopt] = o
CHECK_METHODS = []
for m in Option.CHECK_METHODS:
#if not m == Option._check_dest:
if not m.__name__ == '_check_dest':
CHECK_METHODS.append(m)
CHECK_METHODS.append(_check_dest)
class SubbedOptFormatter(HelpFormatter):
def format_option_strings(self, option):
if hasattr(option, "subopt") and option.subopt:
res = '-o ' + option.subopt
if option.takes_value():
res += "="
res += option.metavar or 'FOO'
return res
return HelpFormatter.format_option_strings(self, option)
class SubbedOptIndentedFormatter(IndentedHelpFormatter, SubbedOptFormatter):
def format_option_strings(self, option):
return SubbedOptFormatter.format_option_strings(self, option)
class SubbedOptParse(OptionParser):
"""
This class alters / enhances `OptionParser` with *suboption handlers*.
That is, calling `sop.add_option('-x', subopt=foo)` installs a handler
which will be triggered if there is ``-x foo`` in the command line being
parsed (or, eg., ``-x foo,bar``).
Moreover, ``-x`` implicitly gets a handler which collects the unhandled
suboptions of ``-x`` into a `SubOptsHive` instance (accessible post festam
via the `x` attribute of the returned Values object). (The only exception
is when ``-x`` has *explicitly* been added with action ``store_hive``.
This opens up the possibility of customizing the ``-x`` handler at some
rate.)
Suboption handlers have all the nice features of normal option handlers,
eg. they are displayed in the automatically generated help message
(and can have their own help info).
"""
def __init__(self, *args, **kw):
if not 'formatter' in kw:
kw['formatter'] = SubbedOptIndentedFormatter()
if not 'option_class' in kw:
kw['option_class'] = SubbedOpt
if 'hive_class' in kw:
self.hive_class = kw.pop('hive_class')
else:
self.hive_class = SubOptsHive
OptionParser.__init__(self, *args, **kw)
def add_option(self, *args, **kwargs):
if 'action' in kwargs and kwargs['action'] == 'store_hive':
if 'subopt' in kwargs:
raise OptParseError(
"""option can't have a `subopt' attr and `action="store_hive"' at the same time""")
if not 'type' in kwargs:
kwargs['type'] = 'string'
elif 'subopt' in kwargs:
o = self.option_class(*args, **kwargs)
oo = self.get_option(o.baseopt)
if oo:
if oo.action != "store_hive":
raise OptionConflictError(
"can't add subopt as option has already a handler that doesn't do `store_hive'",
oo)
else:
self.add_option(o.baseopt, action='store_hive',
metavar="sub1,[sub2,...]")
oo = self.get_option(o.baseopt)
oo.register_sub(o)
args = (o,)
kwargs = {}
return OptionParser.add_option(self, *args, **kwargs)
|