Blame 0001-Unbundle-decorator.patch

1c9872e
From 49af450b7abfbbb4bf29f17d34339029b2a424ca Mon Sep 17 00:00:00 2001
ae64c7f
From: Igor Raits <i.gnatenko.brain@gmail.com>
ae64c7f
Date: Sat, 12 Dec 2020 14:43:19 +0100
2c90330
Subject: [PATCH] Unbundle decorator
2c90330
ae64c7f
Signed-off-by: Igor Raits <i.gnatenko.brain@gmail.com>
2c90330
---
2c90330
 NOTICE                                |   3 -
2c90330
 prometheus_client/context_managers.py |   2 +-
2c90330
 prometheus_client/decorator.py        | 427 --------------------------
2c90330
 setup.py                              |   1 +
ae64c7f
 tests/test_core.py                    |   2 +-
ae64c7f
 5 files changed, 3 insertions(+), 432 deletions(-)
2c90330
 delete mode 100644 prometheus_client/decorator.py
2c90330
2c90330
diff --git a/NOTICE b/NOTICE
2c90330
index 59efb6c..0675ae1 100644
2c90330
--- a/NOTICE
2c90330
+++ b/NOTICE
2c90330
@@ -1,5 +1,2 @@
2c90330
 Prometheus instrumentation library for Python applications
2c90330
 Copyright 2015 The Prometheus Authors
2c90330
-
2c90330
-This product bundles decorator 4.0.10 which is available under a "2-clause BSD"
2c90330
-license. For details, see prometheus_client/decorator.py.
2c90330
diff --git a/prometheus_client/context_managers.py b/prometheus_client/context_managers.py
2c90330
index 2b271a7..d18400f 100644
2c90330
--- a/prometheus_client/context_managers.py
2c90330
+++ b/prometheus_client/context_managers.py
2c90330
@@ -2,7 +2,7 @@ from __future__ import unicode_literals
2c90330
 
2c90330
 from timeit import default_timer
2c90330
 
2c90330
-from .decorator import decorate
2c90330
+from decorator import decorate
2c90330
 
2c90330
 
2c90330
 class ExceptionCounter(object):
2c90330
diff --git a/prometheus_client/decorator.py b/prometheus_client/decorator.py
2c90330
deleted file mode 100644
2c90330
index 1ad2c97..0000000
2c90330
--- a/prometheus_client/decorator.py
2c90330
+++ /dev/null
2c90330
@@ -1,427 +0,0 @@
2c90330
-# #########################     LICENSE     ############################ #
2c90330
-
2c90330
-# Copyright (c) 2005-2016, Michele Simionato
2c90330
-# All rights reserved.
2c90330
-
2c90330
-# Redistribution and use in source and binary forms, with or without
2c90330
-# modification, are permitted provided that the following conditions are
2c90330
-# met:
2c90330
-
2c90330
-#   Redistributions of source code must retain the above copyright
2c90330
-#   notice, this list of conditions and the following disclaimer.
2c90330
-#   Redistributions in bytecode form must reproduce the above copyright
2c90330
-#   notice, this list of conditions and the following disclaimer in
2c90330
-#   the documentation and/or other materials provided with the
2c90330
-#   distribution.
2c90330
-
2c90330
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2c90330
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2c90330
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2c90330
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2c90330
-# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
2c90330
-# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
2c90330
-# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
2c90330
-# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
2c90330
-# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
2c90330
-# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
2c90330
-# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
2c90330
-# DAMAGE.
2c90330
-
2c90330
-"""
2c90330
-Decorator module, see http://pypi.python.org/pypi/decorator
2c90330
-for the documentation.
2c90330
-"""
2c90330
-from __future__ import print_function
2c90330
-
2c90330
-import collections
2c90330
-import inspect
2c90330
-import itertools
2c90330
-import operator
2c90330
-import re
2c90330
-import sys
2c90330
-
2c90330
-__version__ = '4.0.10'
2c90330
-
2c90330
-if sys.version_info >= (3,):
2c90330
-    from inspect import getfullargspec
2c90330
-
2c90330
-
2c90330
-    def get_init(cls):
2c90330
-        return cls.__init__
2c90330
-else:
2c90330
-    class getfullargspec(object):
2c90330
-        "A quick and dirty replacement for getfullargspec for Python 2.X"
2c90330
-
2c90330
-        def __init__(self, f):
2c90330
-            self.args, self.varargs, self.varkw, self.defaults = \
2c90330
-                inspect.getargspec(f)
2c90330
-            self.kwonlyargs = []
2c90330
-            self.kwonlydefaults = None
2c90330
-
2c90330
-        def __iter__(self):
2c90330
-            yield self.args
2c90330
-            yield self.varargs
2c90330
-            yield self.varkw
2c90330
-            yield self.defaults
2c90330
-
2c90330
-        getargspec = inspect.getargspec
2c90330
-
2c90330
-
2c90330
-    def get_init(cls):
2c90330
-        return cls.__init__.__func__
2c90330
-
2c90330
-# getargspec has been deprecated in Python 3.5
2c90330
-ArgSpec = collections.namedtuple(
2c90330
-    'ArgSpec', 'args varargs varkw defaults')
2c90330
-
2c90330
-
2c90330
-def getargspec(f):
2c90330
-    """A replacement for inspect.getargspec"""
2c90330
-    spec = getfullargspec(f)
2c90330
-    return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
2c90330
-
2c90330
-
2c90330
-DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
2c90330
-
2c90330
-
2c90330
-# basic functionality
2c90330
-class FunctionMaker(object):
2c90330
-    """
2c90330
-    An object with the ability to create functions with a given signature.
2c90330
-    It has attributes name, doc, module, signature, defaults, dict and
2c90330
-    methods update and make.
2c90330
-    """
2c90330
-
2c90330
-    # Atomic get-and-increment provided by the GIL
2c90330
-    _compile_count = itertools.count()
2c90330
-
2c90330
-    def __init__(self, func=None, name=None, signature=None,
2c90330
-                 defaults=None, doc=None, module=None, funcdict=None):
2c90330
-        self.shortsignature = signature
2c90330
-        if func:
2c90330
-            # func can be a class or a callable, but not an instance method
2c90330
-            self.name = func.__name__
2c90330
-            if self.name == '<lambda>':  # small hack for lambda functions
2c90330
-                self.name = '_lambda_'
2c90330
-            self.doc = func.__doc__
2c90330
-            self.module = func.__module__
2c90330
-            if inspect.isfunction(func):
2c90330
-                argspec = getfullargspec(func)
2c90330
-                self.annotations = getattr(func, '__annotations__', {})
2c90330
-                for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
2c90330
-                          'kwonlydefaults'):
2c90330
-                    setattr(self, a, getattr(argspec, a))
2c90330
-                for i, arg in enumerate(self.args):
2c90330
-                    setattr(self, 'arg%d' % i, arg)
2c90330
-                if sys.version_info < (3,):  # easy way
2c90330
-                    self.shortsignature = self.signature = (
2c90330
-                        inspect.formatargspec(
2c90330
-                            formatvalue=lambda val: "", *argspec)[1:-1])
2c90330
-                else:  # Python 3 way
2c90330
-                    allargs = list(self.args)
2c90330
-                    allshortargs = list(self.args)
2c90330
-                    if self.varargs:
2c90330
-                        allargs.append('*' + self.varargs)
2c90330
-                        allshortargs.append('*' + self.varargs)
2c90330
-                    elif self.kwonlyargs:
2c90330
-                        allargs.append('*')  # single star syntax
2c90330
-                    for a in self.kwonlyargs:
2c90330
-                        allargs.append('%s=None' % a)
2c90330
-                        allshortargs.append('%s=%s' % (a, a))
2c90330
-                    if self.varkw:
2c90330
-                        allargs.append('**' + self.varkw)
2c90330
-                        allshortargs.append('**' + self.varkw)
2c90330
-                    self.signature = ', '.join(allargs)
2c90330
-                    self.shortsignature = ', '.join(allshortargs)
2c90330
-                self.dict = func.__dict__.copy()
2c90330
-        # func=None happens when decorating a caller
2c90330
-        if name:
2c90330
-            self.name = name
2c90330
-        if signature is not None:
2c90330
-            self.signature = signature
2c90330
-        if defaults:
2c90330
-            self.defaults = defaults
2c90330
-        if doc:
2c90330
-            self.doc = doc
2c90330
-        if module:
2c90330
-            self.module = module
2c90330
-        if funcdict:
2c90330
-            self.dict = funcdict
2c90330
-        # check existence required attributes
2c90330
-        assert hasattr(self, 'name')
2c90330
-        if not hasattr(self, 'signature'):
2c90330
-            raise TypeError('You are decorating a non function: %s' % func)
2c90330
-
2c90330
-    def update(self, func, **kw):
2c90330
-        "Update the signature of func with the data in self"
2c90330
-        func.__name__ = self.name
2c90330
-        func.__doc__ = getattr(self, 'doc', None)
2c90330
-        func.__dict__ = getattr(self, 'dict', {})
2c90330
-        func.__defaults__ = getattr(self, 'defaults', ())
2c90330
-        func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
2c90330
-        func.__annotations__ = getattr(self, 'annotations', None)
2c90330
-        try:
2c90330
-            frame = sys._getframe(3)
2c90330
-        except AttributeError:  # for IronPython and similar implementations
2c90330
-            callermodule = '?'
2c90330
-        else:
2c90330
-            callermodule = frame.f_globals.get('__name__', '?')
2c90330
-        func.__module__ = getattr(self, 'module', callermodule)
2c90330
-        func.__dict__.update(kw)
2c90330
-
2c90330
-    def make(self, src_templ, evaldict=None, addsource=False, **attrs):
2c90330
-        "Make a new function from a given template and update the signature"
2c90330
-        src = src_templ % vars(self)  # expand name and signature
2c90330
-        evaldict = evaldict or {}
2c90330
-        mo = DEF.match(src)
2c90330
-        if mo is None:
2c90330
-            raise SyntaxError('not a valid function template\n%s' % src)
2c90330
-        name = mo.group(1)  # extract the function name
2c90330
-        names = set([name] + [arg.strip(' *') for arg in
2c90330
-                              self.shortsignature.split(',')])
2c90330
-        for n in names:
2c90330
-            if n in ('_func_', '_call_'):
2c90330
-                raise NameError('%s is overridden in\n%s' % (n, src))
2c90330
-
2c90330
-        if not src.endswith('\n'):  # add a newline for old Pythons
2c90330
-            src += '\n'
2c90330
-
2c90330
-        # Ensure each generated function has a unique filename for profilers
2c90330
-        # (such as cProfile) that depend on the tuple of (<filename>,
2c90330
-        # <definition line>, <function name>) being unique.
2c90330
-        filename = '<decorator-gen-%d>' % (next(self._compile_count),)
2c90330
-        try:
2c90330
-            code = compile(src, filename, 'single')
2c90330
-            exec(code, evaldict)
2c90330
-        except:
2c90330
-            print('Error in generated code:', file=sys.stderr)
2c90330
-            print(src, file=sys.stderr)
2c90330
-            raise
2c90330
-        func = evaldict[name]
2c90330
-        if addsource:
2c90330
-            attrs['__source__'] = src
2c90330
-        self.update(func, **attrs)
2c90330
-        return func
2c90330
-
2c90330
-    @classmethod
2c90330
-    def create(cls, obj, body, evaldict, defaults=None,
2c90330
-               doc=None, module=None, addsource=True, **attrs):
2c90330
-        """
2c90330
-        Create a function from the strings name, signature and body.
2c90330
-        evaldict is the evaluation dictionary. If addsource is true an
2c90330
-        attribute __source__ is added to the result. The attributes attrs
2c90330
-        are added, if any.
2c90330
-        """
2c90330
-        if isinstance(obj, str):  # "name(signature)"
2c90330
-            name, rest = obj.strip().split('(', 1)
2c90330
-            signature = rest[:-1]  # strip a right parens
2c90330
-            func = None
2c90330
-        else:  # a function
2c90330
-            name = None
2c90330
-            signature = None
2c90330
-            func = obj
2c90330
-        self = cls(func, name, signature, defaults, doc, module)
2c90330
-        ibody = '\n'.join('    ' + line for line in body.splitlines())
2c90330
-        return self.make('def %(name)s(%(signature)s):\n' + ibody,
2c90330
-                         evaldict, addsource, **attrs)
2c90330
-
2c90330
-
2c90330
-def decorate(func, caller):
2c90330
-    """
2c90330
-    decorate(func, caller) decorates a function using a caller.
2c90330
-    """
2c90330
-    evaldict = dict(_call_=caller, _func_=func)
2c90330
-    fun = FunctionMaker.create(
2c90330
-        func, "return _call_(_func_, %(shortsignature)s)",
2c90330
-        evaldict, __wrapped__=func)
2c90330
-    if hasattr(func, '__qualname__'):
2c90330
-        fun.__qualname__ = func.__qualname__
2c90330
-    return fun
2c90330
-
2c90330
-
2c90330
-def decorator(caller, _func=None):
2c90330
-    """decorator(caller) converts a caller function into a decorator"""
2c90330
-    if _func is not None:  # return a decorated function
2c90330
-        # this is obsolete behavior; you should use decorate instead
2c90330
-        return decorate(_func, caller)
2c90330
-    # else return a decorator function
2c90330
-    if inspect.isclass(caller):
2c90330
-        name = caller.__name__.lower()
2c90330
-        doc = 'decorator(%s) converts functions/generators into ' \
2c90330
-              'factories of %s objects' % (caller.__name__, caller.__name__)
2c90330
-    elif inspect.isfunction(caller):
2c90330
-        if caller.__name__ == '<lambda>':
2c90330
-            name = '_lambda_'
2c90330
-        else:
2c90330
-            name = caller.__name__
2c90330
-        doc = caller.__doc__
2c90330
-    else:  # assume caller is an object with a __call__ method
2c90330
-        name = caller.__class__.__name__.lower()
2c90330
-        doc = caller.__call__.__doc__
2c90330
-    evaldict = dict(_call_=caller, _decorate_=decorate)
2c90330
-    return FunctionMaker.create(
2c90330
-        '%s(func)' % name, 'return _decorate_(func, _call_)',
2c90330
-        evaldict, doc=doc, module=caller.__module__,
2c90330
-        __wrapped__=caller)
2c90330
-
2c90330
-
2c90330
-# ####################### contextmanager ####################### #
2c90330
-
2c90330
-try:  # Python >= 3.2
2c90330
-    from contextlib import _GeneratorContextManager
2c90330
-except ImportError:  # Python >= 2.5
2c90330
-    from contextlib import GeneratorContextManager as _GeneratorContextManager
2c90330
-
2c90330
-
2c90330
-class ContextManager(_GeneratorContextManager):
2c90330
-    def __call__(self, func):
2c90330
-        """Context manager decorator"""
2c90330
-        return FunctionMaker.create(
2c90330
-            func, "with _self_: return _func_(%(shortsignature)s)",
2c90330
-            dict(_self_=self, _func_=func), __wrapped__=func)
2c90330
-
2c90330
-
2c90330
-init = getfullargspec(_GeneratorContextManager.__init__)
2c90330
-n_args = len(init.args)
2c90330
-if n_args == 2 and not init.varargs:  # (self, genobj) Python 2.7
2c90330
-    def __init__(self, g, *a, **k):
2c90330
-        return _GeneratorContextManager.__init__(self, g(*a, **k))
2c90330
-
2c90330
-
2c90330
-    ContextManager.__init__ = __init__
2c90330
-elif n_args == 2 and init.varargs:  # (self, gen, *a, **k) Python 3.4
2c90330
-    pass
2c90330
-elif n_args == 4:  # (self, gen, args, kwds) Python 3.5
2c90330
-    def __init__(self, g, *a, **k):
2c90330
-        return _GeneratorContextManager.__init__(self, g, a, k)
2c90330
-
2c90330
-
2c90330
-    ContextManager.__init__ = __init__
2c90330
-
2c90330
-contextmanager = decorator(ContextManager)
2c90330
-
2c90330
-
2c90330
-# ############################ dispatch_on ############################ #
2c90330
-
2c90330
-def append(a, vancestors):
2c90330
-    """
2c90330
-    Append ``a`` to the list of the virtual ancestors, unless it is already
2c90330
-    included.
2c90330
-    """
2c90330
-    add = True
2c90330
-    for j, va in enumerate(vancestors):
2c90330
-        if issubclass(va, a):
2c90330
-            add = False
2c90330
-            break
2c90330
-        if issubclass(a, va):
2c90330
-            vancestors[j] = a
2c90330
-            add = False
2c90330
-    if add:
2c90330
-        vancestors.append(a)
2c90330
-
2c90330
-
2c90330
-# inspired from simplegeneric by P.J. Eby and functools.singledispatch
2c90330
-def dispatch_on(*dispatch_args):
2c90330
-    """
2c90330
-    Factory of decorators turning a function into a generic function
2c90330
-    dispatching on the given arguments.
2c90330
-    """
2c90330
-    assert dispatch_args, 'No dispatch args passed'
2c90330
-    dispatch_str = '(%s,)' % ', '.join(dispatch_args)
2c90330
-
2c90330
-    def check(arguments, wrong=operator.ne, msg=''):
2c90330
-        """Make sure one passes the expected number of arguments"""
2c90330
-        if wrong(len(arguments), len(dispatch_args)):
2c90330
-            raise TypeError('Expected %d arguments, got %d%s' %
2c90330
-                            (len(dispatch_args), len(arguments), msg))
2c90330
-
2c90330
-    def gen_func_dec(func):
2c90330
-        """Decorator turning a function into a generic function"""
2c90330
-
2c90330
-        # first check the dispatch arguments
2c90330
-        argset = set(getfullargspec(func).args)
2c90330
-        if not set(dispatch_args) <= argset:
2c90330
-            raise NameError('Unknown dispatch arguments %s' % dispatch_str)
2c90330
-
2c90330
-        typemap = {}
2c90330
-
2c90330
-        def vancestors(*types):
2c90330
-            """
2c90330
-            Get a list of sets of virtual ancestors for the given types
2c90330
-            """
2c90330
-            check(types)
2c90330
-            ras = [[] for _ in range(len(dispatch_args))]
2c90330
-            for types_ in typemap:
2c90330
-                for t, type_, ra in zip(types, types_, ras):
2c90330
-                    if issubclass(t, type_) and type_ not in t.__mro__:
2c90330
-                        append(type_, ra)
2c90330
-            return [set(ra) for ra in ras]
2c90330
-
2c90330
-        def ancestors(*types):
2c90330
-            """
2c90330
-            Get a list of virtual MROs, one for each type
2c90330
-            """
2c90330
-            check(types)
2c90330
-            lists = []
2c90330
-            for t, vas in zip(types, vancestors(*types)):
2c90330
-                n_vas = len(vas)
2c90330
-                if n_vas > 1:
2c90330
-                    raise RuntimeError(
2c90330
-                        'Ambiguous dispatch for %s: %s' % (t, vas))
2c90330
-                elif n_vas == 1:
2c90330
-                    va, = vas
2c90330
-                    mro = type('t', (t, va), {}).__mro__[1:]
2c90330
-                else:
2c90330
-                    mro = t.__mro__
2c90330
-                lists.append(mro[:-1])  # discard t and object
2c90330
-            return lists
2c90330
-
2c90330
-        def register(*types):
2c90330
-            """
2c90330
-            Decorator to register an implementation for the given types
2c90330
-            """
2c90330
-            check(types)
2c90330
-
2c90330
-            def dec(f):
2c90330
-                check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
2c90330
-                typemap[types] = f
2c90330
-                return f
2c90330
-
2c90330
-            return dec
2c90330
-
2c90330
-        def dispatch_info(*types):
2c90330
-            """
2c90330
-            An utility to introspect the dispatch algorithm
2c90330
-            """
2c90330
-            check(types)
2c90330
-            lst = []
2c90330
-            for anc in itertools.product(*ancestors(*types)):
2c90330
-                lst.append(tuple(a.__name__ for a in anc))
2c90330
-            return lst
2c90330
-
2c90330
-        def _dispatch(dispatch_args, *args, **kw):
2c90330
-            types = tuple(type(arg) for arg in dispatch_args)
2c90330
-            try:  # fast path
2c90330
-                f = typemap[types]
2c90330
-            except KeyError:
2c90330
-                pass
2c90330
-            else:
2c90330
-                return f(*args, **kw)
2c90330
-            combinations = itertools.product(*ancestors(*types))
2c90330
-            next(combinations)  # the first one has been already tried
2c90330
-            for types_ in combinations:
2c90330
-                f = typemap.get(types_)
2c90330
-                if f is not None:
2c90330
-                    return f(*args, **kw)
2c90330
-
2c90330
-            # else call the default implementation
2c90330
-            return func(*args, **kw)
2c90330
-
2c90330
-        return FunctionMaker.create(
2c90330
-            func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
2c90330
-            dict(_f_=_dispatch), register=register, default=func,
2c90330
-            typemap=typemap, vancestors=vancestors, ancestors=ancestors,
2c90330
-            dispatch_info=dispatch_info, __wrapped__=func)
2c90330
-
2c90330
-    gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
2c90330
-    return gen_func_dec
2c90330
diff --git a/setup.py b/setup.py
ae64c7f
index 0c80a56..7a434b2 100644
2c90330
--- a/setup.py
2c90330
+++ b/setup.py
ae64c7f
@@ -27,6 +27,7 @@ setup(
2c90330
         'prometheus_client.openmetrics',
2c90330
         'prometheus_client.twisted',
2c90330
     ],
2c90330
+    install_requires=['decorator'],
2c90330
     extras_require={
2c90330
         'twisted': ['twisted'],
2c90330
     },
ae64c7f
diff --git a/tests/test_core.py b/tests/test_core.py
1c9872e
index 5a81f12..d81f0a8 100644
ae64c7f
--- a/tests/test_core.py
ae64c7f
+++ b/tests/test_core.py
ae64c7f
@@ -11,7 +11,7 @@ from prometheus_client.core import (
ae64c7f
     HistogramMetricFamily, Info, InfoMetricFamily, Metric, Sample,
ae64c7f
     StateSetMetricFamily, Summary, SummaryMetricFamily, UntypedMetricFamily,
ae64c7f
 )
ae64c7f
-from prometheus_client.decorator import getargspec
1c9872e
+from inspect import getargspec
ae64c7f
 
ae64c7f
 try:
ae64c7f
     import unittest2 as unittest
2c90330
-- 
ae64c7f
2.29.2
2c90330