Blame SOURCES/0001-Remove-the-bundled-decorator-package.patch

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