/usr/lib/python3/dist-packages/oslo_config/sphinxext.py is in python3-oslo.config 1:3.9.0-3.
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 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 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from docutils import nodes
from docutils.parsers import rst
from docutils.parsers.rst import directives
from docutils.statemachine import ViewList
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain
from sphinx.domains import ObjType
from sphinx.roles import XRefRole
from sphinx.util.nodes import make_refnode
from sphinx.util.nodes import nested_parse_with_titles
from oslo_config import cfg
from oslo_config import generator
import six
def _list_table(headers, data, title='', columns=None):
"""Build a list-table directive.
:param add: Function to add one row to output.
:param headers: List of header values.
:param data: Iterable of row data, yielding lists or tuples with rows.
"""
yield '.. list-table:: %s' % title
yield ' :header-rows: 1'
if columns:
yield ' :widths: %s' % (','.join(str(c) for c in columns))
yield ''
yield ' - * %s' % headers[0]
for h in headers[1:]:
yield ' * %s' % h
for row in data:
yield ' - * %s' % row[0]
for r in row[1:]:
yield ' * %s' % r
yield ''
def _indent(text, n=2):
padding = ' ' * n
return '\n'.join(padding + l for l in text.splitlines())
def _make_anchor_target(group_name, option_name):
# We need to ensure this is unique across entire documentation
# http://www.sphinx-doc.org/en/stable/markup/inline.html#ref-role
target = '%s.%s' % (cfg._normalize_group_name(group_name),
option_name.lower())
return target
_TYPE_DESCRIPTIONS = {
cfg.StrOpt: 'string',
cfg.BoolOpt: 'boolean',
cfg.IntOpt: 'integer',
cfg.FloatOpt: 'floating point',
cfg.ListOpt: 'list',
cfg.DictOpt: 'dict',
cfg.MultiStrOpt: 'multi-valued',
cfg._ConfigFileOpt: 'list of filenames',
cfg._ConfigDirOpt: 'list of directory names',
}
def _get_choice_text(choice):
if choice is None:
return '<None>'
elif choice == '':
return "''"
return six.text_type(choice)
def _format_group(app, namespace, group_name, group_obj, opt_list):
group_name = group_name or 'DEFAULT'
app.info('[oslo.config] %s %s' % (namespace, group_name))
yield '.. oslo.config:group:: %s' % group_name
if namespace:
yield ' :namespace: %s' % namespace
yield ''
if group_obj and group_obj.help:
yield _indent(group_obj.help.rstrip())
yield ''
for opt in opt_list:
opt_type = _TYPE_DESCRIPTIONS.get(type(opt),
'unknown type')
yield '.. oslo.config:option:: %s' % opt.dest
yield ''
yield _indent(':Type: %s' % opt_type)
for default in generator._format_defaults(opt):
if default:
default = '``' + default + '``'
yield _indent(':Default: %s' % default)
if getattr(opt.type, 'min', None) is not None:
yield _indent(':Minimum Value: %s' % opt.type.min)
if getattr(opt.type, 'max', None) is not None:
yield _indent(':Maximum Value: %s' % opt.type.max)
if getattr(opt.type, 'choices', None):
choices_text = ', '.join([_get_choice_text(choice)
for choice in opt.type.choices])
yield _indent(':Valid Values: %s' % choices_text)
try:
if opt.mutable:
yield _indent(
':Mutable: This option can be changed without restarting.',
)
except AttributeError as err:
# NOTE(dhellmann): keystoneauth defines its own Opt class,
# and neutron (at least) returns instances of those
# classes instead of oslo_config Opt instances. The new
# mutable attribute is the first property where the API
# isn't supported in the external class, so we can use
# this failure to emit a warning. See
# https://bugs.launchpad.net/keystoneauth/+bug/1548433 for
# more details.
import warnings
if not isinstance(cfg.Opt, opt):
warnings.warn(
'Incompatible option class for %s (%r): %s' %
(opt.dest, opt.__class__, err),
)
else:
warnings.warn('Failed to fully format sample for %s: %s' %
(opt.dest, err))
yield ''
try:
help_text = opt.help % {'default': 'the value above'}
except (TypeError, KeyError):
# There is no mention of the default in the help string,
# or the string had some unknown key
help_text = opt.help
if help_text:
yield _indent(help_text)
yield ''
if opt.deprecated_opts:
for line in _list_table(
['Group', 'Name'],
((d.group or 'DEFAULT',
d.name or opt.dest or 'UNSET')
for d in opt.deprecated_opts),
title='Deprecated Variations'):
yield _indent(line)
if opt.deprecated_for_removal:
yield _indent('.. warning::')
yield _indent(' This option is deprecated for removal.')
yield _indent(' Its value may be silently ignored ')
yield _indent(' in the future.')
yield ''
if opt.deprecated_reason:
yield _indent(' :Reason: ' + opt.deprecated_reason)
yield ''
yield ''
def _format_option_help(app, namespaces, split_namespaces):
"""Generate a series of lines of restructuredtext.
Format the option help as restructuredtext and return it as a list
of lines.
"""
opts = generator._list_opts(namespaces)
if split_namespaces:
for namespace, opt_list in opts:
for group, opts in opt_list:
if isinstance(group, cfg.OptGroup):
group_name = group.name
else:
group_name = group
group = None
lines = _format_group(
app=app,
namespace=namespace,
group_name=group_name,
group_obj=group,
opt_list=opts,
)
for line in lines:
yield line
else:
# Merge the options from different namespaces that belong to
# the same group together and format them without the
# namespace.
by_section = {}
group_objs = {}
for ignore, opt_list in opts:
for group, group_opts in opt_list:
if isinstance(group, cfg.OptGroup):
group_name = group.name
else:
group_name = group
group = None
group_objs.setdefault(group_name, group)
by_section.setdefault(group_name, []).extend(group_opts)
for group_name, group_opts in sorted(by_section.items()):
lines = _format_group(
app=app,
namespace=None,
group_name=group_name,
group_obj=group_objs.get(group_name),
opt_list=group_opts,
)
for line in lines:
yield line
class ShowOptionsDirective(rst.Directive):
option_spec = {
'split-namespaces': directives.flag,
'config-file': directives.unchanged,
}
has_content = True
def run(self):
env = self.state.document.settings.env
app = env.app
split_namespaces = 'split-namespaces' in self.options
config_file = self.options.get('config-file')
if config_file:
app.info('loading config file %s' % config_file)
conf = cfg.ConfigOpts()
conf.register_opts(generator._generator_opts)
conf(
args=['--config-file', config_file],
project='oslo.config.sphinxext',
)
namespaces = conf.namespace[:]
else:
namespaces = [
c.strip()
for c in self.content
if c.strip()
]
result = ViewList()
source_name = '<' + __name__ + '>'
for line in _format_option_help(app, namespaces, split_namespaces):
result.append(line, source_name)
node = nodes.section()
node.document = self.state.document
nested_parse_with_titles(self.state, result, node)
return node.children
class ConfigGroupXRefRole(XRefRole):
"Handles :oslo.config:group: roles pointing to configuration groups."
def __init__(self):
super(ConfigGroupXRefRole, self).__init__(
warn_dangling=True,
)
def process_link(self, env, refnode, has_explicit_title, title, target):
# The anchor for the group link is the group name.
return target, target
class ConfigOptXRefRole(XRefRole):
"Handles :oslo.config:option: roles pointing to configuration options."
def __init__(self):
super(ConfigOptXRefRole, self).__init__(
warn_dangling=True,
)
def process_link(self, env, refnode, has_explicit_title, title, target):
if not has_explicit_title:
title = target
if '.' in target:
group, opt_name = target.split('.')
else:
group = 'DEFAULT'
opt_name = target
anchor = _make_anchor_target(group, opt_name)
return title, anchor
class ConfigGroup(rst.Directive):
has_content = True
option_spec = {
'namespace': directives.unchanged,
}
def run(self):
env = self.state.document.settings.env
app = env.app
group_name = ' '.join(self.content)
namespace = self.options.get('namespace')
cached_groups = env.domaindata['oslo.config']['groups']
# Store the current group for use later in option directives
env.temp_data['oslo.config:group'] = group_name
app.info('oslo.config group %r' % group_name)
# Store the location where this group is being defined
# for use when resolving cross-references later.
# FIXME: This should take the source namespace into account, too
cached_groups[group_name] = env.docname
result = ViewList()
source_name = '<' + __name__ + '>'
def _add(text):
"Append some text to the output result view to be parsed."
result.append(text, source_name)
if namespace:
title = '%s: %s' % (namespace, group_name)
else:
title = group_name
_add(title)
_add('-' * len(title))
node = nodes.section()
node.document = self.state.document
nested_parse_with_titles(self.state, result, node)
first_child = node.children[0]
# Compute the normalized target and set the node to have that
# as an id
target_name = cfg._normalize_group_name(group_name)
first_child['ids'].append(target_name)
indexnode = addnodes.index(entries=[])
return [indexnode] + node.children
class ConfigOption(ObjectDescription):
"Description of a configuration option (.. option)."
def handle_signature(self, sig, signode):
"""Transform an option description into RST nodes."""
optname = sig
self.env.app.info('oslo.config option %s' % optname)
# Insert a node into the output showing the option name
signode += addnodes.desc_name(optname, optname)
signode['allnames'] = [optname]
return optname
def add_target_and_index(self, firstname, sig, signode):
cached_options = self.env.domaindata['oslo.config']['options']
# Look up the current group name from the processing context
currgroup = self.env.temp_data.get('oslo.config:group')
# Compute the normalized target name for the option and give
# that to the node as an id
target_name = _make_anchor_target(currgroup, sig)
signode['ids'].append(target_name)
self.state.document.note_explicit_target(signode)
# Store the location of the option definition for later use in
# resolving cross-references
# FIXME: This should take the source namespace into account, too
cached_options[target_name] = self.env.docname
class ConfigDomain(Domain):
"""oslo.config domain."""
name = 'oslo.config'
label = 'oslo.config'
object_types = {
'configoption': ObjType('configuration option', 'option'),
}
directives = {
'group': ConfigGroup,
'option': ConfigOption,
}
roles = {
'option': ConfigOptXRefRole(),
'group': ConfigGroupXRefRole(),
}
initial_data = {
'options': {},
'groups': {},
}
def resolve_xref(self, env, fromdocname, builder,
typ, target, node, contnode):
if typ == 'option':
group_name, option_name = target.split('.', 1)
return make_refnode(
builder,
fromdocname,
env.domaindata['oslo.config']['options'][target],
target,
contnode,
option_name,
)
if typ == 'group':
return make_refnode(
builder,
fromdocname,
env.domaindata['oslo.config']['groups'][target],
target,
contnode,
target,
)
return None
def setup(app):
app.add_directive('show-options', ShowOptionsDirective)
app.add_domain(ConfigDomain)
|