/usr/lib/python2.7/dist-packages/zope/configuration/config.py is in python-zope.configuration 4.0.3-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 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 | ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Configuration processor
"""
from keyword import iskeyword
import operator
import os.path
import sys
from zope.interface.adapter import AdapterRegistry
from zope.interface import Interface
from zope.interface import implementer
from zope.interface import providedBy
from zope.schema import TextLine
from zope.schema import URI
from zope.schema import ValidationError
from zope.configuration.exceptions import ConfigurationError
from zope.configuration.interfaces import IConfigurationContext
from zope.configuration.interfaces import IGroupingContext
from zope.configuration.fields import GlobalInterface
from zope.configuration.fields import GlobalObject
from zope.configuration._compat import builtins
from zope.configuration._compat import reraise
from zope.configuration._compat import string_types
from zope.configuration._compat import text_type
from zope.configuration._compat import u
zopens = 'http://namespaces.zope.org/zope'
metans = 'http://namespaces.zope.org/meta'
testns = 'http://namespaces.zope.org/test'
_import_chickens = {}, {}, ("*",) # dead chickens needed by __import__
class ConfigurationContext(object):
"""Mix-in that implements IConfigurationContext
Subclasses provide a ``package`` attribute and a ``basepath``
attribute. If the base path is not None, relative paths are
converted to absolute paths using the the base path. If the
package is not none, relative imports are performed relative to
the package.
In general, the basepath and package attributes should be
consistent. When a package is provided, the base path should be
set to the path of the package directory.
Subclasses also provide an ``actions`` attribute, which is a list
of actions, an ``includepath`` attribute, and an ``info``
attribute.
The include path is appended to each action and is used when
resolving conflicts among actions. Normally, only the a
ConfigurationMachine provides the actions attribute. Decorators
simply use the actions of the context they decorate. The
``includepath`` attribute is a tuple of names. Each name is
typically the name of an included configuration file.
The ``info`` attribute contains descriptive information helpful
when reporting errors. If not set, it defaults to an empty string.
The actions attribute is a sequence of dictionaries where each dictionary
has the following keys:
- ``discriminator``, a value that identifies the action. Two actions
that have the same (non None) discriminator conflict.
- ``callable``, an object that is called to execute the action,
- ``args``, positional arguments for the action
- ``kw``, keyword arguments for the action
- ``includepath``, a tuple of include file names (defaults to ())
- ``info``, an object that has descriptive information about
the action (defaults to '')
"""
def __init__(self):
super(ConfigurationContext, self).__init__()
self._seen_files = set()
self._features = set()
def resolve(self, dottedname):
"""Resolve a dotted name to an object.
"""
name = dottedname.strip()
if not name:
raise ValueError("The given name is blank")
if name == '.':
return self.package
names = name.split('.')
if not names[-1]:
raise ValueError(
"Trailing dots are no longer supported in dotted names")
if len(names) == 1:
# Check for built-in objects
marker = object()
obj = getattr(builtins, names[0], marker)
if obj is not marker:
return obj
if not names[0]:
# Got a relative name. Convert it to abs using package info
if self.package is None:
raise ConfigurationError(
"Can't use leading dots in dotted names, "
"no package has been set.")
pnames = self.package.__name__.split(".")
pnames.append('')
while names and not names[0]:
names.pop(0)
try:
pnames.pop()
except IndexError:
raise ConfigurationError("Invalid global name", name)
names[0:0] = pnames
# Now we should have an absolute dotted name
# Split off object name:
oname, mname = names[-1], '.'.join(names[:-1])
# Import the module
if not mname:
# Just got a single name. Must me a module
mname = oname
oname = ''
try:
mod = __import__(mname, *_import_chickens)
except ImportError as v:
if sys.exc_info()[2].tb_next is not None:
# ImportError was caused deeper
raise
raise ConfigurationError(
"ImportError: Couldn't import %s, %s" % (mname, v))
if not oname:
# see not mname case above
return mod
try:
obj = getattr(mod, oname)
return obj
except AttributeError:
# No such name, maybe it's a module that we still need to import
try:
return __import__(mname+'.'+oname, *_import_chickens)
except ImportError:
if sys.exc_info()[2].tb_next is not None:
# ImportError was caused deeper
raise
raise ConfigurationError(
"ImportError: Module %s has no global %s" % (mname, oname))
def path(self, filename):
""" Compute package-relative paths.
"""
filename = os.path.normpath(filename)
if os.path.isabs(filename):
return filename
# Got a relative path, combine with base path.
# If we have no basepath, compute the base path from the package
# path.
basepath = getattr(self, 'basepath', '')
if not basepath:
if self.package is None:
basepath = os.getcwd()
else:
if hasattr(self.package, '__path__'):
basepath = self.package.__path__[0]
else:
basepath = os.path.dirname(self.package.__file__)
basepath = os.path.abspath(os.path.normpath(basepath))
self.basepath = basepath
return os.path.normpath(os.path.join(basepath, filename))
def checkDuplicate(self, filename):
"""Check for duplicate imports of the same file.
Raises an exception if this file had been processed before. This
is better than an unlimited number of conflict errors.
"""
path = self.path(filename)
if path in self._seen_files:
raise ConfigurationError('%r included more than once' % path)
self._seen_files.add(path)
def processFile(self, filename):
"""Check whether a file needs to be processed.
Return True if processing is needed and False otherwise. If
the file needs to be processed, it will be marked as
processed, assuming that the caller will procces the file if
it needs to be procssed.
""" #' <-- bow to font-lock
path = self.path(filename)
if path in self._seen_files:
return False
self._seen_files.add(path)
return True
def action(self, discriminator, callable=None, args=(), kw=None, order=0,
includepath=None, info=None, **extra):
"""Add an action with the given discriminator, callable and arguments.
For testing purposes, the callable and arguments may be omitted.
In that case, a default noop callable is used.
The discriminator must be given, but it can be None, to indicate that
the action never conflicts.
"""
if kw is None:
kw = {}
action = extra
if info is None:
info = getattr(self, 'info', '')
if includepath is None:
includepath = getattr(self, 'includepath', ())
action.update(
dict(
discriminator=discriminator,
callable=callable,
args=args,
kw=kw,
includepath=includepath,
info=info,
order=order,
)
)
self.actions.append(action)
def hasFeature(self, feature):
"""Check whether a named feature has been provided.
Initially no features are provided
"""
return feature in self._features
def provideFeature(self, feature):
"""Declare thata named feature has been provided.
See :meth:`hasFeature` for examples.
"""
self._features.add(feature)
class ConfigurationAdapterRegistry(object):
"""Simple adapter registry that manages directives as adapters
"""
def __init__(self):
super(ConfigurationAdapterRegistry, self).__init__()
self._registry = {}
# Stores tuples of form:
# (namespace, name), schema, usedIn, info, parent
self._docRegistry = []
def register(self, interface, name, factory):
r = self._registry.get(name)
if r is None:
r = AdapterRegistry()
self._registry[name] = r
r.register([interface], Interface, '', factory)
def document(self, name, schema, usedIn, handler, info, parent=None):
if isinstance(name, string_types):
name = ('', name)
self._docRegistry.append((name, schema, usedIn, handler, info, parent))
def factory(self, context, name):
r = self._registry.get(name)
if r is None:
# Try namespace-independent name
ns, n = name
r = self._registry.get(n)
if r is None:
raise ConfigurationError("Unknown directive", ns, n)
f = r.lookup1(providedBy(context), Interface)
if f is None:
raise ConfigurationError(
"The directive %s cannot be used in this context" % (name, ))
return f
@implementer(IConfigurationContext)
class ConfigurationMachine(ConfigurationAdapterRegistry, ConfigurationContext):
"""Configuration machine
"""
package = None
basepath = None
includepath = ()
info = ''
def __init__(self):
super(ConfigurationMachine, self).__init__()
self.actions = []
self.stack = [RootStackItem(self)]
self.i18n_strings = {}
_bootstrap(self)
def begin(self, __name, __data=None, __info=None, **kw):
if __data:
if kw:
raise TypeError("Can't provide a mapping object and keyword "
"arguments")
else:
__data = kw
self.stack.append(self.stack[-1].contained(__name, __data, __info))
def end(self):
self.stack.pop().finish()
def __call__(self, __name, __info=None, **__kw):
self.begin(__name, __kw, __info)
self.end()
def getInfo(self):
return self.stack[-1].context.info
def setInfo(self, info):
self.stack[-1].context.info = info
def execute_actions(self, clear=True, testing=False):
"""Execute the configuration actions.
This calls the action callables after resolving conflicts.
"""
try:
for action in resolveConflicts(self.actions):
callable = action['callable']
if callable is None:
continue
args = action['args']
kw = action['kw']
info = action['info']
try:
callable(*args, **kw)
except (KeyboardInterrupt, SystemExit): #pragma NO COVER
raise
except:
if testing:
raise
t, v, tb = sys.exc_info()
try:
reraise(ConfigurationExecutionError(t, v, info),
None, tb)
finally:
del t, v, tb
finally:
if clear:
del self.actions[:]
class ConfigurationExecutionError(ConfigurationError):
"""An error occurred during execution of a configuration action
"""
def __init__(self, etype, evalue, info):
self.etype, self.evalue, self.info = etype, evalue, info
def __str__(self): #pragma NO COVER
return "%s: %s\n in:\n %s" % (self.etype, self.evalue, self.info)
##############################################################################
# Stack items
class IStackItem(Interface):
"""Configuration machine stack items
Stack items are created when a directive is being processed.
A stack item is created for each directive use.
"""
def contained(name, data, info):
"""Begin processing a contained directive
The data are a dictionary of attribute names mapped to unicode
strings.
The info argument is an object that can be converted to a
string and that contains information about the directive.
The begin method returns the next item to be placed on the stack.
"""
def finish():
"""Finish processing a directive
"""
@implementer(IStackItem)
class SimpleStackItem(object):
"""Simple stack item
A simple stack item can't have anything added after it. It can
only be removed. It is used for simple directives and
subdirectives, which can't contain other directives.
It also defers any computation until the end of the directive
has been reached.
"""
#XXX why this *argdata hack instead of schema, data?
def __init__(self, context, handler, info, *argdata):
newcontext = GroupingContextDecorator(context)
newcontext.info = info
self.context = newcontext
self.handler = handler
self.argdata = argdata
def contained(self, name, data, info):
raise ConfigurationError("Invalid directive %s" % str(name))
def finish(self):
# We're going to use the context that was passed to us, which wasn't
# created for the directive. We want to set it's info to the one
# passed to us while we make the call, so we'll save the old one
# and restore it.
context = self.context
args = toargs(context, *self.argdata)
actions = self.handler(context, **args)
if actions:
# we allow the handler to return nothing
for action in actions:
if not isinstance(action, dict):
action = expand_action(*action) # b/c
context.action(**action)
@implementer(IStackItem)
class RootStackItem(object):
def __init__(self, context):
self.context = context
def contained(self, name, data, info):
"""Handle a contained directive
We have to compute a new stack item by getting a named adapter
for the current context object.
"""
factory = self.context.factory(self.context, name)
if factory is None:
raise ConfigurationError("Invalid directive", name)
adapter = factory(self.context, data, info)
return adapter
def finish(self):
pass
@implementer(IStackItem)
class GroupingStackItem(RootStackItem):
"""Stack item for a grouping directive
A grouping stack item is in the stack when a grouping directive is
being processed. Grouping directives group other directives.
Often, they just manage common data, but they may also take
actions, either before or after contained directives are executed.
A grouping stack item is created with a grouping directive
definition, a configuration context, and directive data.
"""
def __init__(self, context):
super(GroupingStackItem, self).__init__(context)
def __callBefore(self):
actions = self.context.before()
if actions:
for action in actions:
if not isinstance(action, dict):
action = expand_action(*action)
self.context.action(**action)
self.__callBefore = noop
def contained(self, name, data, info):
self.__callBefore()
return RootStackItem.contained(self, name, data, info)
def finish(self):
self.__callBefore()
actions = self.context.after()
if actions:
for action in actions:
if not isinstance(action, dict):
action = expand_action(*action)
self.context.action(**action)
def noop():
pass
@implementer(IStackItem)
class ComplexStackItem(object):
"""Complex stack item
A complex stack item is in the stack when a complex directive is
being processed. It only allows subdirectives to be used.
A complex stack item is created with a complex directive
definition (IComplexDirectiveContext), a configuration context,
and directive data.
"""
def __init__(self, meta, context, data, info):
newcontext = GroupingContextDecorator(context)
newcontext.info = info
self.context = newcontext
self.meta = meta
# Call the handler contructor
args = toargs(newcontext, meta.schema, data)
self.handler = self.meta.handler(newcontext, **args)
def contained(self, name, data, info):
"""Handle a subdirective
"""
# Look up the subdirective meta data on our meta object
ns, name = name
schema = self.meta.get(name)
if schema is None:
raise ConfigurationError("Invalid directive", name)
schema = schema[0] # strip off info
handler = getattr(self.handler, name)
return SimpleStackItem(self.context, handler, info, schema, data)
def finish(self):
# when we're done, we call the handler, which might return more actions
# Need to save and restore old info
# XXX why not just use callable()?
try:
actions = self.handler()
except AttributeError as v:
if v.args[0] == '__call__':
return # noncallable
raise
except TypeError:
return # non callable
if actions:
# we allow the handler to return nothing
for action in actions:
if not isinstance(action, dict):
action = expand_action(*action)
self.context.action(**action)
##############################################################################
# Helper classes
@implementer(IConfigurationContext, IGroupingContext)
class GroupingContextDecorator(ConfigurationContext):
"""Helper mix-in class for building grouping directives
See the discussion (and test) in GroupingStackItem.
"""
def __init__(self, context, **kw):
self.context = context
for name, v in kw.items():
setattr(self, name, v)
def __getattr__(self, name,
getattr=getattr, setattr=setattr):
v = getattr(self.context, name)
# cache result in self
setattr(self, name, v)
return v
def before(self):
pass
def after(self):
pass
##############################################################################
# Directive-definition
class DirectiveSchema(GlobalInterface):
"""A field that contains a global variable value that must be a schema
"""
class IDirectivesInfo(Interface):
"""Schema for the ``directives`` directive
"""
namespace = URI(
title=u("Namespace"),
description=u("The namespace in which directives' names "
"will be defined"),
)
class IDirectivesContext(IDirectivesInfo, IConfigurationContext):
pass
@implementer(IDirectivesContext)
class DirectivesHandler(GroupingContextDecorator):
"""Handler for the directives directive
This is just a grouping directive that adds a namespace attribute
to the normal directive context.
"""
class IDirectiveInfo(Interface):
"""Information common to all directive definitions have
"""
name = TextLine(
title = u("Directive name"),
description = u("The name of the directive being defined"),
)
schema = DirectiveSchema(
title = u("Directive handler"),
description = u("The dotted name of the directive handler"),
)
class IFullInfo(IDirectiveInfo):
"""Information that all top-level directives (not subdirectives) have
"""
handler = GlobalObject(
title = u("Directive handler"),
description = u("The dotted name of the directive handler"),
)
usedIn = GlobalInterface(
title = u("The directive types the directive can be used in"),
description = u("The interface of the directives that can contain "
"the directive"
),
default = IConfigurationContext,
)
class IStandaloneDirectiveInfo(IDirectivesInfo, IFullInfo):
"""Info for full directives defined outside a directives directives
"""
def defineSimpleDirective(context, name, schema, handler,
namespace='', usedIn=IConfigurationContext):
"""Define a simple directive
Define and register a factory that invokes the simple directive
and returns a new stack item, which is always the same simple stack item.
If the namespace is '*', the directive is registered for all namespaces.
"""
namespace = namespace or context.namespace
if namespace != '*':
name = namespace, name
def factory(context, data, info):
return SimpleStackItem(context, handler, info, schema, data)
factory.schema = schema
context.register(usedIn, name, factory)
context.document(name, schema, usedIn, handler, context.info)
def defineGroupingDirective(context, name, schema, handler,
namespace='', usedIn=IConfigurationContext):
"""Define a grouping directive
Define and register a factory that sets up a grouping directive.
If the namespace is '*', the directive is registered for all namespaces.
"""
namespace = namespace or context.namespace
if namespace != '*':
name = namespace, name
def factory(context, data, info):
args = toargs(context, schema, data)
newcontext = handler(context, **args)
newcontext.info = info
return GroupingStackItem(newcontext)
factory.schema = schema
context.register(usedIn, name, factory)
context.document(name, schema, usedIn, handler, context.info)
class IComplexDirectiveContext(IFullInfo, IConfigurationContext):
pass
@implementer(IComplexDirectiveContext)
class ComplexDirectiveDefinition(GroupingContextDecorator, dict):
"""Handler for defining complex directives
See the description and tests for ComplexStackItem.
"""
def before(self):
def factory(context, data, info):
return ComplexStackItem(self, context, data, info)
factory.schema = self.schema
self.register(self.usedIn, (self.namespace, self.name), factory)
self.document((self.namespace, self.name), self.schema, self.usedIn,
self.handler, self.info)
def subdirective(context, name, schema):
context.document((context.namespace, name), schema, context.usedIn,
getattr(context.handler, name, context.handler),
context.info, context.context)
context.context[name] = schema, context.info
##############################################################################
# Features
class IProvidesDirectiveInfo(Interface):
"""Information for a <meta:provides> directive"""
feature = TextLine(
title = u("Feature name"),
description = u("""The name of the feature being provided
You can test available features with zcml:condition="have featurename".
"""),
)
def provides(context, feature):
"""Declare that a feature is provided in context.
"""
if len(feature.split()) > 1:
raise ValueError("Only one feature name allowed")
context.provideFeature(feature)
##############################################################################
# Argument conversion
def toargs(context, schema, data):
"""Marshal data to an argument dictionary using a schema
Names that are python keywords have an underscore added as a
suffix in the schema and in the argument list, but are used
without the underscore in the data.
The fields in the schema must all implement IFromUnicode.
All of the items in the data must have corresponding fields in the
schema unless the schema has a true tagged value named
'keyword_arguments'.
"""
data = dict(data)
args = {}
for name, field in schema.namesAndDescriptions(True):
field = field.bind(context)
n = name
if n.endswith('_') and iskeyword(n[:-1]):
n = n[:-1]
s = data.get(n, data)
if s is not data:
s = text_type(s)
del data[n]
try:
args[str(name)] = field.fromUnicode(s)
except ValidationError as v:
reraise(ConfigurationError("Invalid value for", n, str(v)),
None, sys.exc_info()[2])
elif field.required:
# if the default is valid, we can use that:
default = field.default
try:
field.validate(default)
except ValidationError:
raise ConfigurationError("Missing parameter:", n)
args[str(name)] = default
if data:
# we had data left over
try:
keyword_arguments = schema.getTaggedValue('keyword_arguments')
except KeyError:
keyword_arguments = False
if not keyword_arguments:
raise ConfigurationError("Unrecognized parameters:", *data)
for name in data:
args[str(name)] = data[name]
return args
##############################################################################
# Conflict resolution
def expand_action(discriminator, callable=None, args=(), kw=None,
includepath=(), info=None, order=0, **extra):
if kw is None:
kw = {}
action = extra
action.update(
dict(
discriminator=discriminator,
callable=callable,
args=args,
kw=kw,
includepath=includepath,
info=info,
order=order,
)
)
return action
def resolveConflicts(actions):
"""Resolve conflicting actions
Given an actions list, identify and try to resolve conflicting actions.
Actions conflict if they have the same non-None discriminator.
Conflicting actions can be resolved if the include path of one of
the actions is a prefix of the includepaths of the other
conflicting actions and is unequal to the include paths in the
other conflicting actions.
"""
# organize actions by discriminators
unique = {}
output = []
for i, action in enumerate(actions):
if not isinstance(action, dict):
# old-style tuple action
action = expand_action(*action)
# "order" is an integer grouping. Actions in a lower order will be
# executed before actions in a higher order. Within an order,
# actions are executed sequentially based on original action ordering
# ("i").
order = action['order'] or 0
discriminator = action['discriminator']
# "ainfo" is a tuple of (order, i, action) where "order" is a
# user-supplied grouping, "i" is an integer expressing the relative
# position of this action in the action list being resolved, and
# "action" is an action dictionary. The purpose of an ainfo is to
# associate an "order" and an "i" with a particular action; "order"
# and "i" exist for sorting purposes after conflict resolution.
ainfo = (order, i, action)
if discriminator is None:
# The discriminator is None, so this action can never conflict.
# We can add it directly to the result.
output.append(ainfo)
continue
L = unique.setdefault(discriminator, [])
L.append(ainfo)
# Check for conflicts
conflicts = {}
for discriminator, ainfos in unique.items():
# We use (includepath, order, i) as a sort key because we need to
# sort the actions by the paths so that the shortest path with a
# given prefix comes first. The "first" action is the one with the
# shortest include path. We break sorting ties using "order", then
# "i".
def bypath(ainfo):
path, order, i = ainfo[2]['includepath'], ainfo[0], ainfo[1]
return path, order, i
ainfos.sort(key=bypath)
ainfo, rest = ainfos[0], ainfos[1:]
output.append(ainfo)
_, _, action = ainfo
basepath, baseinfo, discriminator = (action['includepath'],
action['info'],
action['discriminator'])
for _, _, action in rest:
includepath = action['includepath']
# Test whether path is a prefix of opath
if (includepath[:len(basepath)] != basepath # not a prefix
or includepath == basepath):
L = conflicts.setdefault(discriminator, [baseinfo])
L.append(action['info'])
if conflicts:
raise ConfigurationConflictError(conflicts)
# Sort conflict-resolved actions by (order, i) and return them.
return [x[2] for x in sorted(output, key=operator.itemgetter(0, 1))]
class ConfigurationConflictError(ConfigurationError):
def __init__(self, conflicts):
self._conflicts = conflicts
def __str__(self): #pragma NO COVER
r = ["Conflicting configuration actions"]
items = self._conflicts.items()
items.sort()
for discriminator, infos in items:
r.append(" For: %s" % (discriminator, ))
for info in infos:
for line in text_type(info).rstrip().split(u('\n')):
r.append(u(" ") + line)
return "\n".join(r)
##############################################################################
# Bootstap code
def _bootstrap(context):
# Set enough machinery to register other directives
# Define the directive (simple directive) directive by calling it's
# handler directly
info = 'Manually registered in zope/configuration/config.py'
context.info = info
defineSimpleDirective(
context,
namespace=metans, name='directive',
schema=IStandaloneDirectiveInfo,
handler=defineSimpleDirective)
context.info = ''
# OK, now that we have that, we can use the machine to define the
# other directives. This isn't the easiest way to proceed, but it lets
# us eat our own dogfood. :)
# Standalone groupingDirective
context((metans, 'directive'),
info,
name='groupingDirective',
namespace=metans,
handler="zope.configuration.config.defineGroupingDirective",
schema="zope.configuration.config.IStandaloneDirectiveInfo"
)
# Now we can use the grouping directive to define the directives directive
context((metans, 'groupingDirective'),
info,
name='directives',
namespace=metans,
handler="zope.configuration.config.DirectivesHandler",
schema="zope.configuration.config.IDirectivesInfo"
)
# directive and groupingDirective inside directives
context((metans, 'directive'),
info,
name='directive',
namespace=metans,
usedIn="zope.configuration.config.IDirectivesContext",
handler="zope.configuration.config.defineSimpleDirective",
schema="zope.configuration.config.IFullInfo"
)
context((metans, 'directive'),
info,
name='groupingDirective',
namespace=metans,
usedIn="zope.configuration.config.IDirectivesContext",
handler="zope.configuration.config.defineGroupingDirective",
schema="zope.configuration.config.IFullInfo"
)
# Setup complex directive directive, both standalone, and in
# directives directive
context((metans, 'groupingDirective'),
info,
name='complexDirective',
namespace=metans,
handler="zope.configuration.config.ComplexDirectiveDefinition",
schema="zope.configuration.config.IStandaloneDirectiveInfo"
)
context((metans, 'groupingDirective'),
info,
name='complexDirective',
namespace=metans,
usedIn="zope.configuration.config.IDirectivesContext",
handler="zope.configuration.config.ComplexDirectiveDefinition",
schema="zope.configuration.config.IFullInfo"
)
# Finally, setup subdirective directive
context((metans, 'directive'),
info,
name='subdirective',
namespace=metans,
usedIn="zope.configuration.config.IComplexDirectiveContext",
handler="zope.configuration.config.subdirective",
schema="zope.configuration.config.IDirectiveInfo"
)
# meta:provides
context((metans, 'directive'),
info,
name='provides',
namespace=metans,
handler="zope.configuration.config.provides",
schema="zope.configuration.config.IProvidesDirectiveInfo"
)
|